YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
partitem.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2006-2021 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-FileCopyrightText: 2006-2010 RobotCub Consortium
4 * SPDX-License-Identifier: LGPL-2.1-or-later
5 */
6
7#include "partitem.h"
8#include "log.h"
9
10#include <yarp/os/LogStream.h>
11#include <yarp/dev/Drivers.h>
12#include <yarp/dev/PolyDriver.h>
13
14#include <QDebug>
15#include <QEvent>
16#include <QResizeEvent>
17#include <QFileDialog>
18#include <QXmlStreamWriter>
19#include <QXmlStreamAttribute>
20#include <QMessageBox>
21#include <QSettings>
22#include <cmath>
23#include <cstdio>
24
25PartItem::PartItem(std::string robotName, int id, std::string partName, ResourceFinder& _finder,
28 bool enable_calib_all, QWidget *parent) :
29 QWidget(parent),
30 m_sequenceWindow(nullptr),
31 m_partId(id),
32 m_mixedEnabled(false),
33 m_positionDirectEnabled(false),
34 m_pwmEnabled(false),
35 m_currentEnabled(false),
36 m_currentPidDlg(nullptr),
37 m_part_speedVisible(false),
38 m_part_motorPositionVisible(false),
39 m_part_dutyVisible(false),
40 m_part_currentVisible(false),
41 m_finder(&_finder),
42 m_iMot(nullptr),
43 m_iinfo(nullptr),
44 m_slow_k(0)
45{
46 m_layout = new FlowLayout();
47 setLayout(m_layout);
48
49 //PolyDriver *cartesiandd[MAX_NUMBER_ACTIVATED];
50
51 if (robotName.at(0) == '/') {
52 robotName.erase(0, 1);
53 }
54 if (partName.at(0) == '/') {
55 partName.erase(0, 1);
56 }
57 m_robotPartPort = std::string("/") + robotName +std::string("/") + partName;
58 m_partName = partName;
59 m_robotName = robotName;
60
61 //checking existence of the port
62 int ind = 0;
63 QString portLocalName = QString("/yarpmotorgui%1/%2").arg(ind).arg(m_robotPartPort.c_str());
64
65
67 nameToCheck += "/rpc:o";
68
69 // NameClient &nic=NameClient::getNameClient();
70 yDebug("Checking the existence of: %s \n", nameToCheck.toLatin1().data());
71 // Address adr=nic.queryName(nameToCheck.c_str());
72
73 Contact adr=Network::queryName(nameToCheck.toLatin1().data());
74
75 //Contact c = yarp::os::Network::queryName(portLocalName.c_str());
76 yDebug("ADDRESS is: %s \n", adr.toString().c_str());
77
78 while(adr.isValid()){
79 ind++;
80
81 portLocalName = QString("/yarpmotorgui%1/%2").arg(ind).arg(m_robotPartPort.c_str());
82
84 nameToCheck += "/rpc:o";
85 // adr=nic.queryName(nameToCheck.c_str());
86 adr=Network::queryName(nameToCheck.toLatin1().data());
87 }
88
89 m_interfaceError = false;
90
91 // Initializing the polydriver options and instantiating the polydrivers
92 m_partOptions.put("local", portLocalName.toLatin1().data());
93 m_partOptions.put("device", "remote_controlboard");
94 m_partOptions.put("remote", m_robotPartPort);
95 m_partOptions.put("carrier", "udp");
96
97 m_partsdd = new PolyDriver();
98
99 // Opening the drivers
100 m_interfaceError = !openPolyDrivers();
101 if (m_interfaceError == true)
102 {
103 yError("Opening PolyDriver for part %s failed...", m_robotPartPort.c_str());
104 QMessageBox::critical(nullptr, "Error opening a device", QString("Error while opening device for part ").append(m_robotPartPort.c_str()));
105 }
106
107 /*********************************************************************/
108 /**************** PartMover Content **********************************/
109
110 if (!m_finder->isNull()){
111 yDebug("Setting a valid finder \n");
112 }
113
114 QString sequence_portname = QString("/yarpmotorgui/%1/sequence:o").arg(partName.c_str());
115 m_sequence_port.open(sequence_portname.toLatin1().data());
116
119
120 if (m_interfaceError == false)
121 {
122 int i = 0;
123 std::string jointname;
125 m_iPos->getAxes(&number_of_joints);
126
127 m_controlModes.resize(number_of_joints); //for (i = 0; i < number_of_joints; i++) m_controlModes = 0;
128 m_refTrajectorySpeeds.resize(number_of_joints);
129 for (i = 0; i < number_of_joints; i++) {
130 m_refTrajectorySpeeds[i] = std::nan("");
131 }
132 m_refTrajectoryPositions.resize(number_of_joints);
133 for (i = 0; i < number_of_joints; i++) {
134 m_refTrajectoryPositions[i] = std::nan("");
135 }
136 m_refTorques.resize(number_of_joints);
137 for (i = 0; i < number_of_joints; i++) {
138 m_refTorques[i] = std::nan("");
139 }
140 m_refVelocitySpeeds.resize(number_of_joints);
141 for (i = 0; i < number_of_joints; i++) {
142 m_refVelocitySpeeds[i] = std::nan("");
143 }
144 m_torques.resize(number_of_joints);
145 for (i = 0; i < number_of_joints; i++) {
146 m_torques[i] = std::nan("");
147 }
148 m_positions.resize(number_of_joints);
149 for (i = 0; i < number_of_joints; i++) {
150 m_positions[i] = std::nan("");
151 }
152 m_speeds.resize(number_of_joints);
153 for (i = 0; i < number_of_joints; i++) {
154 m_speeds[i] = std::nan("");
155 }
156 m_currents.resize(number_of_joints);
157 for (i = 0; i < number_of_joints; i++) {
158 m_currents[i] = std::nan("");
159 }
160 m_motorPositions.resize(number_of_joints);
161 for (i = 0; i < number_of_joints; i++) {
162 m_motorPositions[i] = std::nan("");
163 }
164 m_dutyCycles.resize(number_of_joints);
165 for (i = 0; i < number_of_joints; i++) {
166 m_dutyCycles[i] = std::nan("");
167 }
168 m_done.resize(number_of_joints);
169 m_interactionModes.resize(number_of_joints);
170
171 bool ret = false;
173 do {
174 ret = m_iencs->getEncoders(m_positions.data());
175 if (!ret) {
176 yError("%s iencs->getEncoders() failed, retrying...\n", partName.c_str());
178 }
179 } while (!ret);
180
181 yInfo("%s iencs->getEncoders() ok!\n", partName.c_str());
182
183 double min_pos = 0;
184 double max_pos = 100;
185 double min_vel = 0;
186 double max_vel = 100;
187 double min_cur = -2.0;
188 double max_cur = +2.0;
189 for (int k = 0; k<number_of_joints; k++)
190 {
191 bool bpl = m_iLim->getLimits(k, &min_pos, &max_pos);
192 bool bvl = m_iLim->getVelLimits(k, &min_vel, &max_vel);
193 bool bcr = m_iCur->getCurrentRange(k, &min_cur, &max_cur);
194 if (bpl == false)
195 {
196 yError() << "Error while getting position limits, part " << partName << " joint " << k;
197 }
198 if (bvl == false || (min_vel == 0 && max_vel == 0))
199 {
200 yError() << "Error while getting velocity limits, part " << partName << " joint " << k;
201 }
202 if (bcr == false || (min_cur == 0 && max_cur == 0))
203 {
204 yError() << "Error while getting current range, part " << partName << " joint " << k;
205 }
206
207 QSettings settings("YARP", "yarpmotorgui");
208 double max_slider_vel = settings.value("velocity_slider_limit", 100.0).toDouble();
209 if (max_vel > max_slider_vel) {
211 }
212
213 m_iinfo->getAxisName(k, jointname);
215 m_iinfo->getJointType(k, jtype);
216
217 Pid myPid(0,0,0,0,0,0);
220
221 auto* joint = new JointItem(k);
222 joint->setJointName(jointname.c_str());
223 joint->setPWMRange(-100.0, 100.0);
224 joint->setCurrentRange(min_cur, max_cur);
225 m_layout->addWidget(joint);
226 joint->setPositionRange(min_pos, max_pos);
227 joint->setVelocityRange(min_vel, max_vel);
228 joint->setTrajectoryVelocityRange(max_vel);
229 joint->setTorqueRange(5.0);
230 joint->setUnits(jtype);
231 joint->enableControlPositionDirect(m_positionDirectEnabled);
232 joint->enableControlMixed(m_mixedEnabled);
233 joint->enableControlPWM(m_pwmEnabled);
234 joint->enableControlCurrent(m_currentEnabled);
235
236 int val_pos_choice = settings.value("val_pos_choice", 0).toInt();
237 int val_trq_choice = settings.value("val_trq_choice", 0).toInt();
238 int val_vel_choice = settings.value("val_vel_choice", 0).toInt();
239 int num_of_pos_decimals = settings.value("num_of_pos_decimals", 3).toInt();
240 double val_pos_custom_step = settings.value("val_pos_custom_step", 1.0).toDouble();
241 double val_trq_custom_step = settings.value("val_trq_custom_step", 1.0).toDouble();
242 double val_vel_custom_step = settings.value("val_vel_custom_step", 1.0).toDouble();
243 onSetPosSliderOptionPI(val_pos_choice, val_pos_custom_step, num_of_pos_decimals);
244 onSetVelSliderOptionPI(val_vel_choice, val_vel_custom_step);
245 onSetTrqSliderOptionPI(val_trq_choice, val_trq_custom_step);
246 onSetCurSliderOptionPI(val_trq_choice, val_trq_custom_step);
247
248 joint->setEnabledOptions(debug_param_enabled,
251
252 connect(joint, SIGNAL(changeMode(int,JointItem*)), this, SLOT(onJointChangeMode(int,JointItem*)));
253 connect(joint, SIGNAL(changeInteraction(int,JointItem*)), this, SLOT(onJointInteraction(int,JointItem*)));
254 connect(joint, SIGNAL(sliderTrajectoryPositionCommand(double, int)), this, SLOT(onSliderTrajectoryPositionCommand(double, int)));
255 connect(joint, SIGNAL(sliderTrajectoryVelocityCommand(double, int)), this, SLOT(onSliderTrajectoryVelocityCommand(double, int)));
256 connect(joint, SIGNAL(sliderMixedPositionCommand(double, int)), this, SLOT(onSliderMixedPositionCommand(double, int)));
257 connect(joint, SIGNAL(sliderMixedVelocityCommand(double, int)), this, SLOT(onSliderMixedVelocityCommand(double, int)));
258 connect(joint, SIGNAL(sliderTorqueCommand(double, int)), this, SLOT(onSliderTorqueCommand(double, int)));
259 connect(joint, SIGNAL(sliderDirectPositionCommand(double, int)), this, SLOT(onSliderDirectPositionCommand(double, int)));
260 connect(joint, SIGNAL(sliderPWMCommand(double, int)), this, SLOT(onSliderPWMCommand(double, int)));
261 connect(joint, SIGNAL(sliderCurrentCommand(double, int)), this, SLOT(onSliderCurrentCommand(double, int)));
262 connect(joint, SIGNAL(sliderVelocityCommand(double, int)), this, SLOT(onSliderVelocityCommand(double, int)));
263 connect(joint, SIGNAL(homeClicked(JointItem*)),this,SLOT(onHomeClicked(JointItem*)));
264 connect(joint, SIGNAL(idleClicked(JointItem*)),this,SLOT(onIdleClicked(JointItem*)));
265 connect(joint, SIGNAL(runClicked(JointItem*)),this,SLOT(onRunClicked(JointItem*)));
266 connect(joint, SIGNAL(pidClicked(JointItem*)),this,SLOT(onPidClicked(JointItem*)));
267 connect(joint, SIGNAL(calibClicked(JointItem*)),this,SLOT(onCalibClicked(JointItem*)));
268 }
269 }
270
271 /*********************************************************************/
272 /*********************************************************************/
273
274 m_cycleTimer.setSingleShot(true);
275 m_cycleTimer.setTimerType(Qt::PreciseTimer);
276 connect(&m_cycleTimer, SIGNAL(timeout()), this, SLOT(onCycleTimerTimeout()), Qt::QueuedConnection);
277
278 m_cycleTimeTimer.setSingleShot(true);
279 m_cycleTimeTimer.setTimerType(Qt::PreciseTimer);
280 connect(&m_cycleTimeTimer, SIGNAL(timeout()), this, SLOT(onCycleTimeTimerTimeout()), Qt::QueuedConnection);
281
282
283 m_runTimeTimer.setSingleShot(true);
284 m_runTimeTimer.setTimerType(Qt::PreciseTimer);
285 connect(&m_runTimeTimer, SIGNAL(timeout()), this, SLOT(onRunTimerTimeout()), Qt::QueuedConnection);
286
287 m_runTimer.setSingleShot(true);
288 m_runTimer.setTimerType(Qt::PreciseTimer);
289 connect(&m_runTimer, SIGNAL(timeout()), this, SLOT(onRunTimeout()), Qt::QueuedConnection);
290}
291
293{
294 disconnect(&m_runTimer, SIGNAL(timeout()), this, SLOT(onRunTimeout()));
295 m_runTimer.stop();
296
297 disconnect(&m_runTimeTimer, SIGNAL(timeout()), this, SLOT(onRunTimerTimeout()));
298 m_runTimeTimer.stop();
299
300 disconnect(&m_cycleTimer, SIGNAL(timeout()), this, SLOT(onCycleTimerTimeout()));
301 m_cycleTimer.stop();
302
303 disconnect(&m_cycleTimeTimer, SIGNAL(timeout()), this, SLOT(onCycleTimeTimerTimeout()));
304 m_cycleTimeTimer.stop();
305
306 if (m_sequenceWindow){
307 m_sequenceWindow->hide();
308 delete m_sequenceWindow;
309 }
310
311 for (int i = 0; i<m_layout->count(); i++){
312 auto* joint = (JointItem *)m_layout->itemAt(i)->widget();
313 if(joint){
314 disconnect(joint,SIGNAL(changeMode(int,JointItem*)), this, SLOT(onJointChangeMode(int,JointItem*)));
315 disconnect(joint,SIGNAL(changeInteraction(int,JointItem*)), this, SLOT(onJointInteraction(int,JointItem*)));
316 disconnect(joint,SIGNAL(homeClicked(JointItem*)),this,SLOT(onHomeClicked(JointItem*)));
317 disconnect(joint,SIGNAL(idleClicked(JointItem*)),this,SLOT(onIdleClicked(JointItem*)));
318 disconnect(joint,SIGNAL(runClicked(JointItem*)),this,SLOT(onRunClicked(JointItem*)));
319 disconnect(joint,SIGNAL(pidClicked(JointItem*)),this,SLOT(onPidClicked(JointItem*)));
320 disconnect(joint,SIGNAL(calibClicked(JointItem*)),this,SLOT(onCalibClicked(JointItem*)));
321 delete joint;
322 }
323 }
324
325 if (m_partsdd){
326 m_partsdd->close();
327 delete m_partsdd;
328 m_partsdd = nullptr;
329 }
330}
331
333{
334 m_partsdd->open(m_partOptions);
335 if (!m_partsdd->isValid()) {
336 return false;
337 }
338
339 #ifdef DEBUG_INTERFACE
341 {
343 if(!debugdd->isValid()){
344 yError("Problems opening the debug client!");
345 }
346 } else {
347 debugdd = NULL;
348 }
349 #endif
350 return true;
351}
352
354{
355 yDebug("Initializing interfaces...");
356 //default value for unopened interfaces
357 m_iPos = nullptr;
358 m_iVel = nullptr;
359 m_iVar = nullptr;
360 m_iDir = nullptr;
361 m_iencs = nullptr;
362 m_iAmp = nullptr;
363 m_iPid = nullptr;
364 m_iCur = nullptr;
365 m_iPWM = nullptr;
366 m_iTrq = nullptr;
367 m_iImp = nullptr;
368 m_iLim = nullptr;
369 m_ical = nullptr;
370 m_ictrlmode = nullptr;
371 m_iinteract = nullptr;
372 m_iremCalib = nullptr;
373 m_ijointfault = nullptr;
374}
375
377{
378 yDebug("Opening interfaces...");
379 bool ok = false;
380
381 if (m_partsdd->isValid()) {
382 ok = m_partsdd->view(m_iPid);
383 if(!ok){
384 yError("...iPid was not ok...");
385 }
386 ok &= m_partsdd->view(m_iAmp);
387 if(!ok){
388 yError("...iAmp was not ok...");
389 }
390 ok &= m_partsdd->view(m_iPos);
391 if(!ok){
392 yError("...iPos was not ok...");
393 }
394 ok &= m_partsdd->view(m_iDir);
395 if(!ok){
396 yError("...posDirect was not ok...");
397 }
398 ok &= m_partsdd->view(m_iVel);
399 if(!ok){
400 yError("...iVel was not ok...");
401 }
402 ok &= m_partsdd->view(m_iLim);
403 if(!ok){
404 yError("...iLim was not ok...");
405 }
406 ok &= m_partsdd->view(m_iencs);
407 if(!ok){
408 yError("...enc was not ok...");
409 }
410 ok &= m_partsdd->view(m_ical);
411 if(!ok){
412 yError("...cal was not ok...");
413 }
414 ok &= m_partsdd->view(m_iTrq);
415 if(!ok){
416 yError("...trq was not ok...");
417 }
418 ok = m_partsdd->view(m_iPWM);
419 if(!ok){
420 yError("...opl was not ok...");
421 }
422 ok &= m_partsdd->view(m_iImp);
423 if(!ok){
424 yError("...imp was not ok...");
425 }
426 ok &= m_partsdd->view(m_ictrlmode);
427 if(!ok){
428 yError("...ctrlmode2 was not ok...");
429 }
430 ok &= m_partsdd->view(m_iinteract);
431 if(!ok){
432 yError("...iinteract was not ok...");
433 }
434
435 //optional interfaces
436 if (!m_partsdd->view(m_ijointfault))
437 {
438 yError("...m_iJointFault was not ok...");
439 }
440
441 if (!m_partsdd->view(m_iVar))
442 {
443 yError("...iVar was not ok...");
444 }
445
446 if (!m_partsdd->view(m_iMot))
447 {
448 yError("...iMot was not ok...");
449 }
450
451 if (!m_partsdd->view(m_iremCalib))
452 {
453 yError("...remCalib was not ok...");
454 }
455
456 if (!m_partsdd->view(m_iinfo))
457 {
458 yError("...axisInfo was not ok...");
459 }
460
461 if (!m_partsdd->view(m_iCur))
462 {
463 yError("...iCur was not ok...");
464 }
465
466 if (!ok) {
467 yError("Error while acquiring interfaces!");
468 QMessageBox::critical(nullptr,"Problems acquiring interfaces.","Check if interface is running");
469 m_interfaceError = true;
470 }
471 }
472 else
473 {
474 yError("Device driver was not valid!");
475 m_interfaceError = true;
476 }
477
478 return !m_interfaceError;
479}
480
482{
483 return m_interfaceError;
484}
485
487{
488 return m_partName.c_str();
489}
490
491void PartItem::onSliderPWMCommand(double pwmVal, int index)
492{
493 m_iPWM->setRefDutyCycle(index, pwmVal);
494}
495
496void PartItem::onSliderCurrentCommand(double currentVal, int index)
497{
498 m_iCur->setRefCurrent(index, currentVal);
499}
500
501void PartItem::onSliderVelocityCommand(double speedVal, int index)
502{
503 m_iVel->velocityMove(index, speedVal);
504}
505
506void PartItem::onSliderTorqueCommand(double torqueVal, int index)
507{
508 m_iTrq->setRefTorque(index, torqueVal);
509}
510
511void PartItem::onSliderTrajectoryVelocityCommand(double trajspeedVal, int index)
512{
513 m_iPos->setRefSpeed(index, trajspeedVal);
514}
515
516
517void PartItem::onSliderDirectPositionCommand(double dirpos, int index)
518{
519 int mode;
520 m_ictrlmode->getControlMode(index, &mode);
521 if (mode == VOCAB_CM_POSITION_DIRECT)
522 {
523 m_iDir->setPosition(index, dirpos);
524 }
525 else
526 {
527 yWarning("Joint not in position direct mode so cannot send references");
528 }
529}
530
531void PartItem::onDumpAllRemoteVariables()
532{
533 if (m_iVar == nullptr)
534 {
535 return;
536 }
537
538 QString fileName = QFileDialog::getSaveFileName(this, QString("Save Dump for Remote Variables as:"), QDir::homePath()+QString("/RemoteVariablesDump.txt"));
539
540 FILE* dumpfile = fopen(fileName.toStdString().c_str(), "w");
541 if (dumpfile != nullptr)
542 {
543 yarp::os::Bottle keys;
544 if (m_iVar->getRemoteVariablesList(&keys))
545 {
546 std::string s = keys.toString();
547 size_t keys_size = keys.size();
548 for (size_t i = 0; i < keys_size; i++)
549 {
550 std::string key_name;
551 if (keys.get(i).isString())
552 {
554 key_name = keys.get(i).asString();
555 if (m_iVar->getRemoteVariable(key_name, val))
556 {
557 std::string key_value = val.toString();
558 std::string p_value = std::string(key_name).append(" ").append(key_value).append("\n");
559 fputs(p_value.c_str(), dumpfile);
560 }
561 }
562 }
563 }
565 }
566}
567
568
569void PartItem::onSliderTrajectoryPositionCommand(double posVal, int index)
570{
571 int mode;
572 m_ictrlmode->getControlMode(index, &mode);
573
574 if ( mode == VOCAB_CM_POSITION)
575 {
576 m_iPos->positionMove(index, posVal);
577 }
578 else
579 {
580 yWarning("Joint not in position mode so cannot send references");
581 }
582}
583
584void PartItem::onSliderMixedPositionCommand(double posVal, int index)
585{
586 int mode;
587 m_ictrlmode->getControlMode(index, &mode);
588
589 if ( mode == VOCAB_CM_MIXED)
590 {
591 m_iPos->positionMove(index, posVal);
592 }
593 else
594 {
595 LOG_ERROR("Joint not in mixed mode so cannot send references");
596 }
597}
598
599void PartItem::onSliderMixedVelocityCommand( double vel, int index)
600{
601 int mode;
602 m_ictrlmode->getControlMode(index, &mode);
603
604 if (mode == VOCAB_CM_MIXED)
605 {
606 m_iVel->velocityMove(index, vel);
607 }
608 else
609 {
610 LOG_ERROR("Joint not in mixed mode so cannot send references");
611 }
612}
613
614void PartItem::onJointInteraction(int interaction,JointItem *joint)
615{
616 const int jointIndex = joint->getJointIndex();
617 switch (interaction) {
619 yInfo("interaction mode of joint %d set to COMPLIANT", jointIndex);
621 break;
622 case JointItem::Stiff:
623 yInfo("interaction mode of joint %d set to STIFF", jointIndex);
625 break;
626 default:
627 break;
628 }
629}
630
631
632void PartItem::onSendPWM(int jointIndex, double pwmVal)
633{
634 double pwm_reference = 0;
635 double current_pwm = 0;
636
637 m_iPWM->setRefDutyCycle(jointIndex, pwmVal);
638
640 m_iPWM->getRefDutyCycle(jointIndex, &pwm_reference); //This is the reference
642 m_iPWM->getDutyCycle(jointIndex, &current_pwm); //This is the real PWM output
643
644 if (m_currentPidDlg){
645 m_currentPidDlg->initPWM(pwm_reference, current_pwm);
646 }
647}
648
649void PartItem::onSendStiffness(int jointIdex,double stiff,double damp,double force)
650{
652 double stiff_val=0;
653 double damp_val=0;
654 double offset_val=0;
655
656 m_iImp->setImpedance(jointIdex, stiff, damp);
657 //imp->setImpedanceOffset(jointIdex, force);
661
662 //update the impedance limits
663 double stiff_max=0.0;
664 double stiff_min=0.0;
665 double damp_max=0.0;
666 double damp_min=0.0;
667 double off_max=0.0;
668 double off_min=0.0;
671
672 if (m_currentPidDlg)
673 {
674 m_currentPidDlg->initStiffness(stiff_val, stiff_min, stiff_max,
677 }
678
679
680}
681
682void PartItem::onSendTorquePid(int jointIndex,Pid newPid,MotorTorqueParameters newTrqParam)
683{
684 Pid myTrqPid(0,0,0,0,0,0);
686 m_iPid->setPid(VOCAB_PIDTYPE_TORQUE, jointIndex, newPid);
687
688 m_iTrq->setMotorTorqueParams(jointIndex, newTrqParam);
690 m_iPid->getPid(VOCAB_PIDTYPE_TORQUE,jointIndex, &myTrqPid);
691 m_iTrq->getMotorTorqueParams(jointIndex, &TrqParam);
692
693 if (m_currentPidDlg){
694 m_currentPidDlg->initTorque(myTrqPid, TrqParam);
695 }
696}
697
698void PartItem::onSendPositionPid(int jointIndex,Pid newPid)
699{
700 Pid myPosPid(0,0,0,0,0,0);
701 m_iPid->setPid(VOCAB_PIDTYPE_POSITION, jointIndex, newPid);
703 m_iPid->getPid(VOCAB_PIDTYPE_POSITION, jointIndex, &myPosPid);
704
705 if (m_currentPidDlg){
706 m_currentPidDlg->initPosition(myPosPid);
707 }
708}
709
710void PartItem::onSendVelocityPid(int jointIndex, Pid newPid)
711{
712 Pid myVelPid(0, 0, 0, 0, 0, 0);
713 m_iPid->setPid(VOCAB_PIDTYPE_VELOCITY, jointIndex, newPid);
715 m_iPid->getPid(VOCAB_PIDTYPE_VELOCITY, jointIndex, &myVelPid);
716
717 if (m_currentPidDlg){
718 m_currentPidDlg->initVelocity(myVelPid);
719 }
720}
721
722void PartItem::onRefreshPids(int jointIndex)
723{
724 Pid myPosPid(0, 0, 0, 0, 0, 0);
725 Pid myTrqPid(0, 0, 0, 0, 0, 0);
726 Pid myVelPid(0, 0, 0, 0, 0, 0);
727 Pid myCurPid(0, 0, 0, 0, 0, 0);
729 double stiff_val = 0;
730 double damp_val = 0;
731 double stiff_max = 0;
732 double damp_max = 0;
733 double off_max = 0;
734 double stiff_min = 0;
735 double damp_min = 0;
736 double off_min = 0;
737 double impedance_offset_val = 0;
738 double pwm_reference = 0;
739 double current_pwm = 0;
740
742 m_iTrq->getTorqueRange(jointIndex, &off_min, &off_max);
743
744 // Position
745 m_iPid->getPid(VOCAB_PIDTYPE_POSITION, jointIndex, &myPosPid);
747
748 // Velocity
749 m_iPid->getPid(VOCAB_PIDTYPE_VELOCITY, jointIndex, &myVelPid);
751
752 // Current
753 if (m_iCur)
754 {
755 m_iPid->getPid(VOCAB_PIDTYPE_CURRENT, jointIndex, &myCurPid);
757 }
758
759 // Torque
760 m_iPid->getPid(VOCAB_PIDTYPE_TORQUE, jointIndex, &myTrqPid);
761 m_iTrq->getMotorTorqueParams(jointIndex, &motorTorqueParams);
763
764 //Stiff
765 m_iImp->getImpedance(jointIndex, &stiff_val, &damp_val);
766 m_iImp->getImpedanceOffset(jointIndex, &impedance_offset_val);
768
769 // PWM
770 m_iPWM->getRefDutyCycle(jointIndex, &pwm_reference);
771 m_iPWM->getDutyCycle(jointIndex, &current_pwm);
772
773 if (m_currentPidDlg)
774 {
775 m_currentPidDlg->initPosition(myPosPid);
776 m_currentPidDlg->initTorque(myTrqPid, motorTorqueParams);
777 m_currentPidDlg->initVelocity(myVelPid);
778 m_currentPidDlg->initCurrent(myCurPid);
780 m_currentPidDlg->initPWM(pwm_reference, current_pwm);
781 m_currentPidDlg->initRemoteVariables(m_iVar);
782 }
783}
784
785void PartItem::onSendCurrentPid(int jointIndex, Pid newPid)
786{
787 if (m_iCur == nullptr)
788 {
789 yError() << "iCurrent interface not opened";
790 return;
791 }
792 Pid myCurPid(0, 0, 0, 0, 0, 0);
793 m_iPid->setPid(VOCAB_PIDTYPE_CURRENT, jointIndex, newPid);
795 m_iPid->getPid(VOCAB_PIDTYPE_CURRENT, jointIndex, &myCurPid);
796
797 if (m_currentPidDlg){
798 m_currentPidDlg->initCurrent(myCurPid);
799 }
800}
801
802void PartItem::onSendSingleRemoteVariable(std::string key, yarp::os::Bottle val)
803{
804 m_iVar->setRemoteVariable(key, val);
806}
807
808void PartItem::onUpdateAllRemoteVariables()
809{
810 if (m_currentPidDlg){
811 m_currentPidDlg->initRemoteVariables(m_iVar);
812 }
813}
814
815void PartItem::onCalibClicked(JointItem *joint)
816{
817 if (!m_iremCalib)
818 {
819 QMessageBox::critical(this,"Operation not supported", QString("The IRemoteCalibrator interface was not found on this application"));
820 return;
821 }
822
823 if(QMessageBox::question(this,"Question","Do you really want to recalibrate the joint?") != QMessageBox::Yes){
824 return;
825 }
826 if (!m_iremCalib->calibrateSingleJoint(joint->getJointIndex()))
827 {
828 // provide better feedback to user by verifying if the calibrator device was set or not
829 bool isCalib = false;
830 m_iremCalib->isCalibratorDevicePresent(&isCalib);
831 if (!isCalib) {
832 QMessageBox::critical(this,"Calibration failed", QString("No calibrator device was configured to perform this action, please verify that the wrapper config file has the 'Calibrator' keyword in the attach phase"));
833 } else {
834 QMessageBox::critical(this, "Calibration failed", QString("The remote calibrator reported that something went wrong during the calibration procedure"));
835 }
836 }
837
838}
839
840void PartItem::onPidClicked(JointItem *joint)
841{
842 const int jointIndex = joint->getJointIndex();
843 QString jointName = joint->getJointName();
844 m_currentPidDlg = new PidDlg(m_partName.c_str(), jointIndex, jointName);
845 connect(m_currentPidDlg, SIGNAL(sendPositionPid(int, Pid)), this, SLOT(onSendPositionPid(int, Pid)));
846 connect(m_currentPidDlg, SIGNAL(sendVelocityPid(int, Pid)), this, SLOT(onSendVelocityPid(int, Pid)));
847 connect(m_currentPidDlg, SIGNAL(sendCurrentPid(int, Pid)), this, SLOT(onSendCurrentPid(int, Pid)));
848 connect(m_currentPidDlg, SIGNAL(sendSingleRemoteVariable(std::string, yarp::os::Bottle)), this, SLOT(onSendSingleRemoteVariable(std::string, yarp::os::Bottle)));
849 connect(m_currentPidDlg, SIGNAL(updateAllRemoteVariables()), this, SLOT(onUpdateAllRemoteVariables()));
850 connect(m_currentPidDlg, SIGNAL(sendTorquePid(int, Pid, MotorTorqueParameters)), this, SLOT(onSendTorquePid(int, Pid, MotorTorqueParameters)));
851 connect(m_currentPidDlg, SIGNAL(sendStiffness(int, double, double, double)), this, SLOT(onSendStiffness(int, double, double, double)));
852 connect(m_currentPidDlg, SIGNAL(sendPWM(int, double)), this, SLOT(onSendPWM(int, double)));
853 connect(m_currentPidDlg, SIGNAL(refreshPids(int)), this, SLOT(onRefreshPids(int)));
854 connect(m_currentPidDlg, SIGNAL(dumpRemoteVariables()), this, SLOT(onDumpAllRemoteVariables()));
855
856 this->onRefreshPids(jointIndex);
857
858 m_currentPidDlg->exec();
859
860 delete m_currentPidDlg;
861 m_currentPidDlg = nullptr;
862}
863
864void PartItem::onRunClicked(JointItem *joint)
865{
866 const int jointIndex = joint->getJointIndex();
867 double posJoint;
868 while (!m_iencs->getEncoder(jointIndex, &posJoint)){
870 }
871
872 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_POSITION);
873}
874
875void PartItem::onIdleClicked(JointItem *joint)
876{
877 const int jointIndex = joint->getJointIndex();
878 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_FORCE_IDLE);
879}
880
881void PartItem::onHomeClicked(JointItem *joint)
882{
884 const int jointIndex = joint->getJointIndex();
885 m_iPos->getAxes(&NUMBER_OF_JOINTS);
886
887 this->homeJoint(jointIndex);
888}
889
890void PartItem::onJointChangeMode(int mode,JointItem *joint)
891{
892 const int jointIndex = joint->getJointIndex();
893 switch (mode) {
894 case JointItem::Idle:{
895 yInfo("joint: %d in IDLE mode", jointIndex);
896 if (m_ictrlmode){
897 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_IDLE);
898 } else {
899 yError("ERROR: cannot do!");
900 }
901 break;
902 }
904 yInfo("joint: %d in POSITION mode", jointIndex);
905 if (m_ictrlmode){
906 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_POSITION);
907 joint->resetTarget();
908 } else {
909 yError("ERROR: cannot do!");
910 }
911 break;
912 }
914 //if(positionDirectEnabled){
915 yInfo("joint: %d in POSITION DIRECT mode", jointIndex);
916 if (m_ictrlmode){
917 joint->resetTarget();
918 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_POSITION_DIRECT);
919 } else {
920 yError("ERROR: cannot do!");
921 }
922 break;
923 /*}else{
924 LOG_ERROR("joint: %d in MIXED mode", jointIndex);
925 if(ctrlmode2){
926 ctrlmode2->setControlMode(jointIndex, VOCAB_CM_MIXED);
927 } else {
928 yError("ERROR: cannot do!");
929 }
930 break;
931 }*/
932 }
933 case JointItem::Mixed:{
934 //if(positionDirectEnabled){
935 yInfo("joint: %d in MIXED mode", jointIndex);
936 if (m_ictrlmode){
937 joint->resetTarget();
938 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_MIXED);
939 } else {
940 yError("ERROR: cannot do!");
941 }
942 break;
943 /*}else{
944 LOG_ERROR("joint: %d in VELOCITY mode", jointIndex);
945 if(ctrlmode2){
946 ctrlmode2->setVelocityMode(jointIndex);
947 } else {
948 LOG_ERROR("ERROR: cannot do!");
949 }
950 break;
951 }*/
952
953 }
955 //if(positionDirectEnabled){
956 yInfo("joint: %d in VELOCITY mode", jointIndex);
957 if (m_ictrlmode)
958 {
959 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_VELOCITY);
960 yInfo() << "Changing reference acceleration of joint " << jointIndex << " to 100000";
961 m_iVel->setRefAcceleration(jointIndex, 100000);
962 } else {
963 yError("ERROR: cannot do!");
964 }
965 break;
966// } else {
967// LOG_ERROR("joint: %d in TORQUE mode", jointIndex);
968// if(ctrlmode2){
969// ctrlmode2->setTorqueMode(jointIndex);
970// } else {
971// LOG_ERROR("ERROR: cannot do!");
972// }
973// break;
974// }
975 }
976
977 case JointItem::Torque:{
978 //if(positionDirectEnabled){
979 yInfo("joint: %d in TORQUE mode", jointIndex);
980 if (m_ictrlmode){
981 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_TORQUE);
982 } else {
983 yError("ERROR: cannot do!");
984 }
985 break;
986// } else {
987// LOG_ERROR("joint: %d in TORQUE mode", jointIndex);
988// if(ctrlmode2){
989// ctrlmode2->setTorqueMode(jointIndex);
990// } else {
991// LOG_ERROR("ERROR: cannot do!");
992// }
993// break;
994// }
995
996 }
997 case JointItem::Pwm:{
998 yInfo("joint: %d in PWM mode", jointIndex);
999 if (m_ictrlmode){
1000 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_PWM);
1001 } else {
1002 yError("ERROR: cannot do!");
1003 }
1004 break;
1005 }
1006 case JointItem::Current:{
1007 yInfo("joint: %d in CURRENT mode", jointIndex);
1008 if (m_ictrlmode){
1009 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_CURRENT);
1010 }
1011 else {
1012 yError("ERROR: cannot do!");
1013 }
1014 break;
1015 }
1016 default:
1017 break;
1018 }
1019}
1020
1022{
1023 int count = m_layout->count();
1024
1025
1026 int jointPerLineCount = (w - 20) / (MAX_WIDTH_JOINT + 10);
1027 if(jointPerLineCount > count){
1028 jointPerLineCount = count;
1029 }
1030 if(jointPerLineCount <= 0){
1031 return;
1032 }
1033
1034 int extraSpace = (w - 20) - jointPerLineCount * (MAX_WIDTH_JOINT + 10);
1035
1036
1037
1038 for(int i=0;i<count;i++){
1039 QWidget *widget = m_layout->itemAt(i)->widget();
1040 if(widget){
1041 widget->setMaximumWidth(MAX_WIDTH_JOINT + (extraSpace/jointPerLineCount));
1042 widget->setMinimumWidth(MAX_WIDTH_JOINT + (extraSpace/jointPerLineCount));
1043 }
1044
1045 }
1046}
1047
1049{
1050 return m_layout->count();
1051}
1052
1054{
1056 {
1057 return "";
1058 }
1059
1060 auto* jointWidget = (JointItem*)m_layout->itemAt(joint)->widget();
1061
1062 return jointWidget->getJointName();
1063}
1064
1066{
1067 return (JointItem*)m_layout->itemAt(jointIndex)->widget();
1068}
1069
1071{
1072 if(!isVisible()){
1073 return;
1074 }
1075
1076 resizeWidget(event->size().width());
1077}
1078
1080{
1081 if(event->type() == QEvent::WindowStateChange ){
1082 qDebug() << "State Changed " << width();
1083 int count = m_layout->count();
1084 int jointPerLineCount = (width() - 20) / (MAX_WIDTH_JOINT + 10);
1085
1086 if(jointPerLineCount > count){
1087 jointPerLineCount = count;
1088 }
1089 if(jointPerLineCount <= 0){
1090 return;
1091 }
1092 int extraSpace = (width() - 20) - jointPerLineCount * (MAX_WIDTH_JOINT + 10);
1093
1094
1096
1097 for(int i=0;i<count;i++){
1098 QWidget *widget = m_layout->itemAt(i)->widget();
1099 if(widget){
1100 widget->setMaximumWidth(MAX_WIDTH_JOINT + (extraSpace/jointPerLineCount));
1101 widget->setMinimumWidth(MAX_WIDTH_JOINT + (extraSpace/jointPerLineCount));
1102 }
1103 }
1104 }
1105
1106}
1107
1109{
1110 if (!m_iremCalib)
1111 {
1112 QMessageBox::critical(this,"Operation not supported", QString("The IRemoteCalibrator interface was not found on this application"));
1113 return;
1114 }
1115
1116 if (!m_iremCalib->calibrateWholePart())
1117 {
1118 // provide better feedback to user by verifying if the calibrator device was set or not
1119 bool isCalib = false;
1120 m_iremCalib->isCalibratorDevicePresent(&isCalib);
1121 if (!isCalib) {
1122 QMessageBox::critical(this, "Calibration failed", QString("No calibrator device was configured to perform this action, please verify that the wrapper config file for part %1 has the 'Calibrator' keyword in the attach phase").arg(m_partName.c_str()));
1123 } else {
1124 QMessageBox::critical(this, "Calibration failed", QString("The remote calibrator reported that something went wrong during the calibration procedure"));
1125 }
1126 }
1127}
1128
1129bool PartItem::homeJoint(int jointIndex)
1130{
1131 if (!m_iremCalib)
1132 {
1133 QMessageBox::critical(this, "Operation not supported", QString("The IRemoteCalibrator interface was not found on this application"));
1134 return false;
1135 }
1136
1137 if (!m_iremCalib->homingSingleJoint(jointIndex))
1138 {
1139 // provide better feedback to user by verifying if the calibrator device was set or not
1140 bool isCalib = false;
1141 m_iremCalib->isCalibratorDevicePresent(&isCalib);
1142 if (!isCalib)
1143 {
1144 QMessageBox::critical(this, "Operation failed", QString("No calibrator device was configured to perform this action, please verify that the wrapper config file for part %1 has the 'Calibrator' keyword in the attach phase").arg(m_partName.c_str()));
1145 return false;
1146 }
1147 else
1148 {
1149 QMessageBox::critical(this, "Operation failed", QString("The remote calibrator reported that something went wrong during the calibration procedure"));
1150 return false;
1151 }
1152 }
1153 return true;
1154}
1155
1157{
1158 if (!m_iremCalib)
1159 {
1160 QMessageBox::critical(this, "Operation not supported", QString("The IRemoteCalibrator interface was not found on this application"));
1161 return false;
1162 }
1163
1164 if (!m_iremCalib->homingWholePart())
1165 {
1166 // provide better feedback to user by verifying if the calibrator device was set or not
1167 bool isCalib = false;
1168 m_iremCalib->isCalibratorDevicePresent(&isCalib);
1169 if (!isCalib)
1170 {
1171 QMessageBox::critical(this, "Operation failed", QString("No calibrator device was configured to perform this action, please verify that the wrapper config file for part %1 has the 'Calibrator' keyword in the attach phase").arg(m_partName.c_str()));
1172 return false;
1173 }
1174 else
1175 {
1176 QMessageBox::critical(this, "Operation failed", QString("The remote calibrator reported that something went wrong during the calibration procedure"));
1177 return false;
1178 }
1179 }
1180 return true;
1181}
1182
1184{
1185 bool ok = true;
1186 int NUMBER_OF_JOINTS;
1187 m_iPos->getAxes(&NUMBER_OF_JOINTS);
1188
1189 if (positionElement.isNull()) {
1190 QMessageBox::critical(this, "Operation failed", QString("No custom position supplied in configuration file for part ") + QString(m_partName.c_str()));
1191 return false;
1192 }
1193
1194 //Look for group called m_robotPartPort_Position and m_robotPartPort_Velocity
1195 Bottle xtmp, ytmp;
1196 xtmp = positionElement.findGroup(m_robotPartPort + "_Position");
1197 ok = ok && (xtmp.size() == (size_t) NUMBER_OF_JOINTS + 1);
1198 ytmp = positionElement.findGroup(m_robotPartPort + "_Velocity");
1199 ok = ok && (ytmp.size() == (size_t) NUMBER_OF_JOINTS + 1);
1200
1201 if(ok)
1202 {
1203 for (int jointIndex = 0; jointIndex < NUMBER_OF_JOINTS; jointIndex++)
1204 {
1205 double position = xtmp.get(jointIndex+1).asFloat64();
1206 double velocity = ytmp.get(jointIndex + 1).asFloat64();
1207 m_iPos->setRefSpeed(jointIndex, velocity);
1208 m_iPos->positionMove(jointIndex, position);
1209 }
1210 }
1211 else
1212 {
1213 QMessageBox::critical(this, "Error", QString("Check the number of entries in the group %1").arg(m_robotPartPort.c_str()));
1214 ok = false;
1215 }
1216
1217 return ok;
1218}
1219
1221{
1222 int NUMBER_OF_JOINTS;
1223 m_iPos->getAxes(&NUMBER_OF_JOINTS);
1224
1225 for (int joint=0; joint < NUMBER_OF_JOINTS; joint++){
1226 m_ictrlmode->setControlMode(joint, VOCAB_CM_IDLE);
1227 }
1228}
1229
1231{
1232 if (!m_sequenceWindow){
1233 return false;
1234 }
1235
1236 return m_sequenceWindow->checkAndRun();
1237
1238
1239}
1240
1242{
1243 if (!m_sequenceWindow){
1244 return false;
1245 }
1246
1247 return m_sequenceWindow->checkAndRunTime();
1248
1249
1250}
1251
1253{
1254 if (!m_sequenceWindow){
1255 return false;
1256 }
1257
1258 return m_sequenceWindow->checkAndCycleTimeSeq();
1259}
1260
1262{
1263 if (!m_sequenceWindow){
1264 return false;
1265 }
1266
1267 return m_sequenceWindow->checkAndCycleSeq();
1268}
1269
1271{
1272 int NUMBER_OF_JOINTS;
1273 m_iPos->getAxes(&NUMBER_OF_JOINTS);
1274
1275 for (int joint=0; joint < NUMBER_OF_JOINTS; joint++){
1276 //iencs->getEncoder(joint, &posJoint);
1277 m_ictrlmode->setControlMode(joint, VOCAB_CM_POSITION);
1278 }
1279}
1280
1282{
1284 onOpenSequence();
1285}
1286
1292
1294{
1295 if (m_sequenceWindow)
1296 {
1297 m_sequenceWindow->close();
1298 }
1299}
1300
1302{
1303 if (!m_sequenceWindow){
1304 m_sequenceWindow = new SequenceWindow(m_partName.c_str(), m_layout->count());
1305 connect(m_sequenceWindow, SIGNAL(itemDoubleClicked(int)), this, SLOT(onSequenceWindowDoubleClicked(int)), Qt::DirectConnection);
1306 connect(this, SIGNAL(sendPartJointsValues(int, QList<double>, QList<double>)), m_sequenceWindow, SLOT(onReceiveValues(int, QList<double>, QList<double>)), Qt::DirectConnection);
1307 connect(m_sequenceWindow, SIGNAL(goToPosition(SequenceItem)), this, SLOT(onGo(SequenceItem)));
1308 connect(m_sequenceWindow, SIGNAL(runTime(QList<SequenceItem>)), this, SLOT(onSequenceRunTime(QList<SequenceItem>)), Qt::QueuedConnection);
1309 connect(m_sequenceWindow, SIGNAL(run(QList<SequenceItem>)), this, SLOT(onSequenceRun(QList<SequenceItem>)), Qt::QueuedConnection);
1310 connect(m_sequenceWindow, SIGNAL(saveSequence(QList<SequenceItem>, QString)), this, SLOT(onSaveSequence(QList<SequenceItem>, QString)), Qt::QueuedConnection);
1311 connect(m_sequenceWindow, SIGNAL(openSequence()), this, SLOT(onOpenSequence()));
1312 connect(m_sequenceWindow, SIGNAL(cycle(QList<SequenceItem>)), this, SLOT(onSequenceCycle(QList<SequenceItem>)), Qt::QueuedConnection);
1313 connect(m_sequenceWindow, SIGNAL(cycleTime(QList<SequenceItem>)), this, SLOT(onSequenceCycleTime(QList<SequenceItem>)), Qt::QueuedConnection);
1314 connect(m_sequenceWindow, SIGNAL(stopSequence()), this, SLOT(onStopSequence()), Qt::QueuedConnection);
1315
1316 connect(this, SIGNAL(runTimeSequence()), m_sequenceWindow, SLOT(onRunTimeSequence()));
1317 connect(this, SIGNAL(cycleTimeSequence()), m_sequenceWindow, SLOT(onCycleTimeSequence()));
1318 connect(this, SIGNAL(cycleSequence()), m_sequenceWindow, SLOT(onCycleSequence()));
1319 connect(this, SIGNAL(stoppedSequence()), m_sequenceWindow, SLOT(onStoppedSequence()));
1320 connect(this, SIGNAL(setCurrentIndex(int)), m_sequenceWindow, SLOT(onSetCurrentSequenceIndex(int)));
1321
1322 connect(this,SIGNAL(runTimeSequence()),this,SLOT(onSequenceActivated()));
1323 connect(this,SIGNAL(cycleTimeSequence()),this,SLOT(onSequenceActivated()));
1324 connect(this,SIGNAL(cycleSequence()),this,SLOT(onSequenceActivated()));
1325 connect(this,SIGNAL(stoppedSequence()),this,SLOT(onSequenceStopped()));
1326
1327
1328 }
1329
1330 if (!m_sequenceWindow->isVisible()){
1331 m_sequenceWindow->show();
1332 }else{
1333 m_sequenceWindow->setFocus();
1334 m_sequenceWindow->raise();
1335 m_sequenceWindow->setWindowState(Qt::WindowActive);
1336 }
1337
1338}
1339
1341{
1342 if (!m_sequenceWindow){
1343 return false;
1344 }
1345
1346 return m_sequenceWindow->checkAndGo();
1347}
1349{
1350 m_cycleTimer.stop();
1351 m_runTimer.stop();
1352 m_runTimeTimer.stop();
1353 m_cycleTimeTimer.stop();
1355}
1356
1357void PartItem::onStopSequence()
1358{
1359 stopSequence();
1360}
1361
1362void PartItem::onOpenSequence()
1363{
1364 QString fileName = QFileDialog::getOpenFileName(m_sequenceWindow, QString("Load Sequence for part %1 As").arg(m_partName.c_str()), QDir::homePath());
1365
1366 QFileInfo fInfo(fileName);
1367 if(!fInfo.exists()){
1368 return;
1369 }
1370
1371 QString desiredExtension = QString("pos%1").arg(m_partName.c_str());
1372 QString extension = fInfo.suffix();
1373
1375 QMessageBox::critical(this,"Error Loading The Sequence",
1376 QString("Wrong format (check extensions) of the file associated with: ").arg(m_partName.c_str()));
1377 return;
1378 }
1379
1380 QFile file(fileName);
1381 if (!file.open(QFile::ReadOnly | QFile::Text)){
1382 QString msg = QString("Error: Cannot read file %1: %2").arg(qPrintable(fileName))
1383 .arg(qPrintable(file.errorString()));
1384 QMessageBox::critical(this,"Error Loading The Sequence",msg);
1385 return;
1386 }
1387
1388 QXmlStreamReader reader(&file);
1389 reader.readNext();
1390
1392
1395 while(!reader.atEnd()){
1396 reader.readNext();
1397
1398 if(reader.isStartElement()){
1399 if(reader.name().contains("Sequence_")){ //Sequence_
1400 QXmlStreamAttributes attributes = reader.attributes();
1401 referencePart = attributes.value("ReferencePart").toString();
1402 }
1403
1404 if(reader.name() == "Position"){ //Position
1405 QXmlStreamAttributes attributes = reader.attributes();
1406 int index = attributes.value("Index").toInt();
1407 double timing = attributes.value("Timing").toDouble();
1408 item.setTiming(timing);
1409 item.setSequenceNumber(index);
1410 }
1411
1412 if(reader.name() == "JointPositions"){
1413 QXmlStreamAttributes attributes = reader.attributes();
1414 int count = attributes.value("Count").toInt();
1415
1416 reader.readNext();
1417 for(int i=0; i<count;i++){
1418 reader.readNext();
1419 if(reader.name() == "PosValue"){ //PosValue
1420 double pos = reader.readElementText().toDouble();
1421 item.addPositionValue(pos);
1422 }
1423 reader.readNext();
1424 }
1425
1426 }
1427
1428 if(reader.name() == "JointVelocities"){
1429 QXmlStreamAttributes attributes = reader.attributes();
1430 int count = attributes.value("Count").toInt();
1431
1432 reader.readNext();
1433 for(int i=0; i<count;i++){
1434 reader.readNext();
1435 if(reader.name() == "SpeedValue"){ //SpeedValue
1436 double speed = reader.readElementText().toDouble();
1437 item.addSpeedValue(speed);
1438 }
1439 reader.readNext();
1440 }
1441
1442 }
1443
1444 }
1445
1446 if(reader.isEndElement()){
1447 if(reader.name() == "Position"){
1448 sequenceItems.append(item);
1449 item = SequenceItem();
1450 }
1451 }
1452 }
1453
1454 file.close();
1455
1456 if (reader.hasError())
1457 {
1458 QString msg = QString("Error: Failed to parse file %1: %2").arg(qPrintable(fileName)).arg(qPrintable(reader.errorString()));
1459 QMessageBox::critical(this,"Error Loading The Sequence",msg);
1460 return;
1461 } else if (file.error() != QFile::NoError) {
1462 QString msg = QString("Error: Cannot read file %1: %2").arg(qPrintable(fileName)).arg(qPrintable(file.errorString()));
1463 QMessageBox::critical(this,"Error Loading The Sequence",msg);
1464 return;
1465 }
1466
1467 if (m_sequenceWindow){
1468 m_sequenceWindow->loadSequence(sequenceItems);
1469 }
1470
1471}
1472
1473void PartItem::onSaveSequence(QList<SequenceItem> values, QString fileName)
1474{
1475 if (fileName=="")
1476 {
1477 fileName = QFileDialog::getSaveFileName(this, QString("Save Sequence for part %1 As").arg(m_partName.c_str()), QDir::homePath());
1478 }
1479
1480 if(fileName.isEmpty()){
1481 return;
1482 }
1483
1484 QFileInfo fInfo(fileName);
1485 QString completeFileName = QString("%1/%2.pos%3").arg(fInfo.absolutePath()).arg(fInfo.baseName()).arg(m_partName.c_str());
1486 std::string completeFileName_s = completeFileName.toStdString();
1487
1488 //QFile file(completeFileName);
1489 yInfo("Saving file %s\n", completeFileName_s.c_str());
1490
1491 QFile file(completeFileName);
1492 if(!file.open(QIODevice::WriteOnly)){
1493 return;
1494 }
1495
1496 QXmlStreamWriter writer(&file);
1497 writer.setAutoFormatting(true);
1498 writer.writeStartDocument();
1499
1500 writer.writeStartElement(QString("Sequence_pos%1").arg(m_partName.c_str()));
1501
1502 writer.writeAttribute("TotPositions", QString("%1").arg(values.count()));
1503 writer.writeAttribute("ReferencePart", m_partName.c_str());
1504
1505 for(int i=0;i<values.count();i++){
1507 writer.writeStartElement("Position");
1508 writer.writeAttribute("Index",QString("%1").arg(sequenceItem.getSequenceNumber()));
1509 writer.writeAttribute("Timing",QString("%L1").arg(sequenceItem.getTiming(),0,'f',2));
1510
1511 writer.writeStartElement("JointPositions");
1512 writer.writeAttribute("Count",QString("%1").arg(sequenceItem.getPositions().count()));
1513 for(int j=0;j<sequenceItem.getPositions().count(); j++){
1514 QString s = QString("%L1").arg(sequenceItem.getPositions().at(j),0,'f',2);
1515 writer.writeTextElement("PosValue",s);
1516 }
1517 writer.writeEndElement();
1518
1519 writer.writeStartElement("JointVelocities");
1520 writer.writeAttribute("Count",QString("%1").arg(sequenceItem.getSpeeds().count()));
1521 for(int j=0;j<sequenceItem.getSpeeds().count(); j++){
1522 QString s = QString("%L1").arg(sequenceItem.getSpeeds().at(j),0,'f',2);
1523 writer.writeTextElement("SpeedValue",s);
1524 }
1525 writer.writeEndElement();
1526 writer.writeEndElement();
1527 }
1528 writer.writeEndElement();
1529 writer.writeEndDocument();
1530 file.close();
1531 LOG_INFO("File saved and closed\n");
1532
1533
1534// if(file.open(QIODevice::WriteOnly)){
1535// for(int i=0;i<values.count();i++){
1536// SequenceItem sequenceItem = values.at(i);
1537// QString s = QString("[POSITION%1] \n").arg(sequenceItem.getSequenceNumber());
1538// file.write(s.toLatin1().data(),s.length());
1539
1540// s = QString("jointPositions ");
1541// file.write(s.toLatin1().data(),s.length());
1542
1543// for(int j=0;j<sequenceItem.getPositions().count(); j++){
1544// s = QString("%L1 ").arg(sequenceItem.getPositions().at(j),0,'f',2);
1545// file.write(s.toLatin1().data(),s.length());
1546// }
1547
1548// s = QString("\njointVelocities ");
1549// file.write(s.toLatin1().data(),s.length());
1550// for(int j=0;j<sequenceItem.getSpeeds().count(); j++){
1551// s = QString("%L1 ").arg(sequenceItem.getSpeeds().at(j),0,'f',2);
1552// file.write(s.toLatin1().data(),s.length());
1553// }
1554
1555// s = QString("\ntiming ");
1556// file.write(s.toLatin1().data(),s.length());
1557// s = QString("%L1 \n").arg(sequenceItem.getTiming(),0,'f',2);
1558// file.write(s.toLatin1().data(),s.length());
1559// }
1560// file.flush();
1561// file.close();
1562
1563// LOG_ERROR("File saved and closed\n");
1564// }
1565
1566}
1567
1568void PartItem::onSequenceCycleTime(QList<SequenceItem> values)
1569{
1570 // Remove items after the first timing with value < 0
1571 if (m_cycleTimeTimer.isActive() || m_cycleTimer.isActive() || m_runTimeTimer.isActive() || m_runTimer.isActive()){
1572 return;
1573 }
1574
1575 m_cycleTimeValues.clear();
1576 for(int i=0;i<values.count();i++){
1577 SequenceItem it = values.at(i);
1578 if(it.getTiming() > 0){
1579 m_cycleTimeValues.append(it);
1580 }
1581 }
1582
1584 if (m_cycleTimeValues.count() > 0)
1585 {
1586 vals = m_cycleTimeValues.takeFirst();
1587 m_cycleTimeValues.append(vals);
1588 emit setCurrentIndex(vals.getSequenceNumber());
1589 fixedTimeMove(vals);
1590 m_cycleTimeTimer.start(vals.getTiming() * 1000);
1592 }
1593}
1594
1595void PartItem::onCycleTimeTimerTimeout()
1596{
1597 if (m_cycleTimeValues.count() > 0)
1598 {
1599 SequenceItem vals = m_cycleTimeValues.takeFirst();
1600 m_cycleTimeValues.append(vals);
1601 emit setCurrentIndex(vals.getSequenceNumber());
1602 fixedTimeMove(vals);
1603 m_cycleTimeTimer.start(vals.getTiming() * 1000);
1604 }
1605}
1606
1607void PartItem::onSequenceCycle(QList<SequenceItem> values)
1608{
1609 // Remove items after the first timing with value < 0
1610 if (m_cycleTimeTimer.isActive() || m_cycleTimer.isActive() || m_runTimeTimer.isActive() || m_runTimer.isActive()){
1611 return;
1612 }
1613
1614 m_cycleValues.clear();
1615 for(int i=0;i<values.count();i++){
1616 SequenceItem it = values.at(i);
1617 if(it.getTiming() > 0){
1618 m_cycleValues.append(it);
1619 }
1620 }
1621
1623 if (m_cycleValues.count() > 0){
1624 vals = m_cycleValues.takeFirst();
1625
1626 m_cycleValues.append(vals);
1627
1628 double *cmdPositions = new double[vals.getPositions().count()];
1629 double *cmdVelocities = new double[vals.getSpeeds().count()];
1630
1631 for(int i=0;i<vals.getPositions().count();i++){
1632 cmdPositions[i] = vals.getPositions().at(i);
1633 cmdVelocities[i] = vals.getSpeeds().at(i);
1634 //qDebug() << "vals.getSpeeds().at(i)" << vals.getSpeeds().at(i);
1635 }
1636
1637 emit setCurrentIndex(vals.getSequenceNumber());
1638 //fixedTimeMove(vals.getPositions());
1639 m_iPos->setRefSpeeds(cmdVelocities);
1640 m_iPos->positionMove(cmdPositions);
1641 m_cycleTimer.start(vals.getTiming() * 1000);
1642
1644 }
1645}
1646
1647void PartItem::onCycleTimerTimeout()
1648{
1649 if (m_cycleValues.count() > 0){
1650 SequenceItem vals = m_cycleValues.takeFirst();
1651
1652 m_cycleValues.append(vals);
1653
1654 double *cmdPositions = new double[vals.getPositions().count()];
1655 double *cmdVelocities = new double[vals.getSpeeds().count()];
1656
1657 for(int i=0;i<vals.getPositions().count();i++){
1658 cmdPositions[i] = vals.getPositions().at(i);
1659 cmdVelocities[i] = vals.getSpeeds().at(i);
1660 }
1661
1662 emit setCurrentIndex(vals.getSequenceNumber());
1663 //fixedTimeMove(vals.getPositions());
1664 m_iPos->setRefSpeeds(cmdVelocities);
1665 m_iPos->positionMove(cmdPositions);
1666
1667 m_cycleTimer.start(vals.getTiming() * 1000);
1668 }
1669}
1670
1671void PartItem::onSequenceRun(QList<SequenceItem> values)
1672{
1673 // Remove items after the first timing with value < 0
1674 if (m_cycleTimeTimer.isActive() || m_cycleTimer.isActive() || m_runTimeTimer.isActive() || m_runTimer.isActive()){
1675 return;
1676 }
1677
1678 m_runValues.clear();
1679 for(int i=0;i<values.count();i++){
1680 SequenceItem it = values.at(i);
1681 if(it.getTiming() > 0){
1682 m_runValues.append(it);
1683 }
1684 }
1685
1687 if (m_runValues.count() > 0){
1688 vals = m_runValues.takeFirst();
1689
1690 m_runValues.append(vals);
1691
1692 double *cmdPositions = new double[vals.getPositions().count()];
1693 double *cmdVelocities = new double[vals.getSpeeds().count()];
1694
1695 for(int i=0;i<vals.getPositions().count();i++){
1696 cmdPositions[i] = vals.getPositions().at(i);
1697 cmdVelocities[i] = vals.getSpeeds().at(i);
1698 //qDebug() << "vals.getSpeeds().at(i)" << vals.getSpeeds().at(i);
1699 }
1700
1701 emit setCurrentIndex(vals.getSequenceNumber());
1702 //fixedTimeMove(vals.getPositions());
1703 m_iPos->setRefSpeeds(cmdVelocities);
1704 m_iPos->positionMove(cmdPositions);
1705 m_runTimer.start(vals.getTiming() * 1000);
1706
1707 emit runSequence();
1708 }
1709}
1710void PartItem::onRunTimeout()
1711{
1712 if (m_runValues.count() > 0){
1713 SequenceItem vals = m_runValues.takeFirst();
1714 if(vals.getTiming() < 0){
1716 return;
1717 }
1718 double *cmdPositions = new double[vals.getPositions().count()];
1719 double *cmdVelocities = new double[vals.getSpeeds().count()];
1720
1721 for(int i=0;i<vals.getPositions().count();i++){
1722 cmdPositions[i] = vals.getPositions().at(i);
1723 cmdVelocities[i] = vals.getSpeeds().at(i);
1724 //qDebug() << "vals.getSpeeds().at(i)" << vals.getSpeeds().at(i);
1725 }
1726
1727 emit setCurrentIndex(vals.getSequenceNumber());
1728 //fixedTimeMove(vals.getPositions());
1729 m_iPos->setRefSpeeds(cmdVelocities);
1730 m_iPos->positionMove(cmdPositions);
1731
1732
1733 m_runTimer.start(vals.getTiming() * 1000);
1734 }else{
1736 }
1737}
1738
1739
1740
1741void PartItem::onSequenceRunTime(QList<SequenceItem> values)
1742{
1743 if (m_cycleTimeTimer.isActive() || m_cycleTimer.isActive() || m_runTimeTimer.isActive() || m_runTimer.isActive()){
1744 return;
1745 }
1746
1747 m_runTimeValues.clear();
1748
1749 for(int i=0;i<values.count();i++){
1750 SequenceItem it = values.at(i);
1751 if(it.getTiming() > 0){
1752 m_runTimeValues.append(it);
1753 }
1754 }
1755
1757 if (m_runTimeValues.count() > 0){
1758 vals = m_runTimeValues.takeFirst();
1759
1760 emit setCurrentIndex(vals.getSequenceNumber());
1761 fixedTimeMove(vals);
1762 m_runTimeTimer.start(vals.getTiming() * 1000);
1763
1765 }
1766
1767}
1768
1769void PartItem::onRunTimerTimeout()
1770{
1771 if (m_runTimeValues.count() > 0){
1772 SequenceItem vals = m_runTimeValues.takeFirst();
1773 if(vals.getTiming() < 0){
1775 return;
1776 }
1777 emit setCurrentIndex(vals.getSequenceNumber());
1778 fixedTimeMove(vals);
1779 m_runTimeTimer.start(vals.getTiming() * 1000);
1780 }else{
1782 }
1783}
1784
1785void PartItem::fixedTimeMove(SequenceItem sequence)
1786{
1787 int NUM_JOINTS;
1788 m_iPos->getAxes(&NUM_JOINTS);
1789 auto* cmdPositions = new double[NUM_JOINTS];
1790 auto* cmdVelocities = new double[NUM_JOINTS];
1791 auto* startPositions = new double[NUM_JOINTS];
1792 double cmdTime = sequence.getTiming();
1793
1794 while (!m_iencs->getEncoders(startPositions)){
1796 }
1797
1798
1799 for(int k=0; k<NUM_JOINTS; k++){
1800 cmdVelocities[k] = 0;
1801 cmdPositions[k] = sequence.getPositions().at(k);
1802
1803 if (fabs(startPositions[k] - cmdPositions[k]) > 0.01){
1805 } else {
1806 cmdVelocities[k] = 1.0;
1807 }
1808 }
1809
1810 m_iPos->setRefSpeeds(cmdVelocities);
1811 m_iPos->positionMove(cmdPositions);
1812
1813 m_sequence_port_stamp.update();
1814 m_sequence_port.setEnvelope(m_sequence_port_stamp);
1816 m_sequence_port.write(v);
1817 delete[] cmdVelocities;
1818 delete[] startPositions;
1819 delete[] cmdPositions;
1820 return;
1821}
1822
1823void PartItem::onGo(SequenceItem sequenceItem)
1824{
1825 if(sequenceItem.getPositions().isEmpty() || sequenceItem.getSpeeds().isEmpty())
1826 {
1827 QMessageBox::critical(this,"Error", "Select an entry in the table before performing a movement");
1828 return;
1829 }
1830
1831 int NUMBER_OF_JOINTS;
1832 m_iPos->getAxes(&NUMBER_OF_JOINTS);
1833
1834 for(int i=0;i<NUMBER_OF_JOINTS;i++)
1835 {
1836 m_iPos->setRefSpeed(i, sequenceItem.getSpeeds().at(i));
1837 m_iPos->positionMove(i, sequenceItem.getPositions().at(i));
1838 }
1839}
1840
1841void PartItem::onSequenceActivated()
1842{
1843 for (int i = 0; i<m_layout->count(); i++)
1844 {
1845 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1846 if(joint){
1847 joint->sequenceActivated();
1848 }
1849 }
1850
1852
1853}
1854
1855void PartItem::onSequenceStopped()
1856{
1857 for (int i = 0; i<m_layout->count(); i++)
1858 {
1859 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1860 if(joint){
1861 joint->sequenceStopped();
1862 }
1863 }
1865}
1866
1867void PartItem::onSequenceWindowDoubleClicked(int sequenceNum)
1868{
1870 QList<double>speeds;
1871 for (int i = 0; i<m_layout->count(); i++)
1872 {
1873 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1874 values.append(this->m_positions[i]);
1875 speeds.append(joint->getTrajectoryVelocityValue());
1876 }
1877
1879}
1880
1882{
1883 for (int i = 0; i<m_layout->count(); i++)
1884 {
1885 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1886 joint->enableControlVelocity(control);
1887 }
1888}
1889
1891{
1892 for (int i = 0; i<m_layout->count(); i++)
1893 {
1894 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1895 joint->enableControlMixed(control);
1896 }
1897}
1898
1900{
1901 for (int i = 0; i<m_layout->count(); i++)
1902 {
1903 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1904 joint->enableControlPositionDirect(control);
1905 }
1906}
1907
1909{
1910 for (int i = 0; i<m_layout->count(); i++)
1911 {
1912 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1913 joint->enableControlPWM(control);
1914 }
1915}
1916
1918{
1919 for (int i = 0; i<m_layout->count(); i++)
1920 {
1921 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1922 joint->enableControlCurrent(control);
1923 }
1924}
1925
1927{
1928 m_part_speedVisible = view;
1929 for (int i = 0; i<m_layout->count(); i++)
1930 {
1931 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1932 joint->setSpeedVisible(view);
1933 }
1934}
1935
1937{
1938 m_part_motorPositionVisible = view;
1939 for (int i = 0; i<m_layout->count(); i++)
1940 {
1941 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1942 joint->setMotorPositionVisible(view);
1943 }
1944}
1945
1947{
1948 m_part_dutyVisible = view;
1949 for (int i = 0; i<m_layout->count(); i++)
1950 {
1951 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1952 joint->setDutyVisible(view);
1953 }
1954}
1955
1957{
1958 m_part_currentVisible = view;
1959 for (int i = 0; i<m_layout->count(); i++)
1960 {
1961 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1962 joint->setCurrentsVisible(view);
1963 }
1964}
1965
1967{
1968 for (int i = 0; i<m_layout->count(); i++)
1969 {
1970 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1971 joint->viewPositionTargetBox(ena);
1972 }
1973}
1974
1976{
1977 for (int i = 0; i < m_layout->count(); i++)
1978 {
1979 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1980 joint->viewPositionTargetValue(ena);
1981 }
1982}
1983
1984void PartItem::onSetPosSliderOptionPI(int mode, double step, int numOfDec)
1985{
1986 for (int i = 0; i<m_layout->count(); i++)
1987 {
1988 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1989 if (mode==0)
1990 {
1991 joint->enablePositionSliderDoubleAuto();
1992 }
1993 else if(mode ==1)
1994 {
1995 joint->enablePositionSliderDoubleValue(step);
1996 }
1997 else if (mode == 2)
1998 {
1999 joint->enablePositionSliderDoubleValue(1.0);
2000 }
2001 else
2002 {
2003 joint->disablePositionSliderDouble();
2004 }
2005 joint->setNumberOfPositionSliderDecimals(numOfDec);
2006 }
2007}
2008void PartItem::onSetVelSliderOptionPI(int mode, double step)
2009{
2010 for (int i = 0; i<m_layout->count(); i++)
2011 {
2012 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
2013 if (mode == 0)
2014 {
2015 joint->enableVelocitySliderDoubleAuto();
2016 joint->enableTrajectoryVelocitySliderDoubleAuto();
2017 }
2018 else if (mode == 1)
2019 {
2020 joint->enableVelocitySliderDoubleValue(step);
2021 joint->enableTrajectoryVelocitySliderDoubleValue(step);
2022 }
2023 else if (mode == 2)
2024 {
2025 joint->enableVelocitySliderDoubleValue(1.0);
2026 joint->enableTrajectoryVelocitySliderDoubleValue(1.0);
2027 }
2028 else
2029 {
2030 joint->disableVelocitySliderDouble();
2031 joint->disableTrajectoryVelocitySliderDouble();
2032 }
2033 }
2034}
2035
2036void PartItem::onSetCurSliderOptionPI(int mode, double step)
2037{
2038 for (int i = 0; i<m_layout->count(); i++)
2039 {
2040 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
2041 if (mode == 0)
2042 {
2043 joint->enableCurrentSliderDoubleAuto();
2044 }
2045 else if (mode == 1)
2046 {
2047 joint->enableCurrentSliderDoubleValue(step);
2048 }
2049 else if (mode == 2)
2050 {
2051 joint->enableCurrentSliderDoubleValue(1.0);
2052 }
2053 else
2054 {
2055 joint->disableCurrentSliderDouble();
2056 }
2057 }
2058}
2059
2060void PartItem::onSetTrqSliderOptionPI(int mode, double step)
2061{
2062 for (int i = 0; i<m_layout->count(); i++)
2063 {
2064 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
2065 if (mode == 0)
2066 {
2067 joint->enableTorqueSliderDoubleAuto();
2068 }
2069 else if(mode == 1)
2070 {
2071 joint->enableTorqueSliderDoubleValue(step);
2072 }
2073 else if(mode == 2)
2074 {
2075 joint->enableTorqueSliderDoubleValue(1.0);
2076 }
2077 else
2078 {
2079 joint->disableTorqueSliderDouble();
2080 }
2081 }
2082}
2083
2085{
2086 return m_modesList;
2087}
2088
2090{
2091 bool ret = m_ictrlmode->getControlModes(m_controlModes.data());
2092
2093
2094 if(ret==false){
2095 LOG_ERROR("ictrl->getControlMode failed on %s\n", getPartName().toStdString().c_str());
2096 }
2097
2098 m_modesList.resize(m_layout->count());
2099 for (int k = 0; k < m_layout->count(); k++){
2100 switch (m_controlModes[k])
2101 {
2102 case VOCAB_CM_IDLE:
2103 m_modesList[k] = JointItem::Idle;
2104 break;
2105 case VOCAB_CM_POSITION:
2106 m_modesList[k] = JointItem::Position;
2107 break;
2109 m_modesList[k] = JointItem::PositionDirect;
2110 break;
2111 case VOCAB_CM_MIXED:
2112 m_modesList[k] = JointItem::Mixed;
2113 break;
2114 case VOCAB_CM_VELOCITY:
2115 m_modesList[k] = JointItem::Velocity;
2116 break;
2117 case VOCAB_CM_TORQUE:
2118 m_modesList[k] = JointItem::Torque;
2119 break;
2120 case VOCAB_CM_PWM:
2121 m_modesList[k] = JointItem::Pwm;
2122 break;
2123 case VOCAB_CM_CURRENT:
2124 m_modesList[k] = JointItem::Current;
2125 break;
2126 case VOCAB_CM_HW_FAULT:
2127 m_modesList[k] = JointItem::HwFault;
2128 break;
2130 m_modesList[k] = JointItem::Calibrating;
2131 break;
2133 m_modesList[k] = JointItem::CalibDone;
2134 break;
2136 m_modesList[k] = JointItem::NotConfigured;
2137 break;
2139 m_modesList[k] = JointItem::Configured;
2140 break;
2141 default:
2142 case VOCAB_CM_UNKNOWN:
2143 m_modesList[k] = JointItem::Unknown;
2144 break;
2145 }
2146 }
2147}
2148
2150{
2151 bool ret = false;
2152 int number_of_joints=0;
2153 m_iPos->getAxes(&number_of_joints);
2154 if (m_slow_k >= number_of_joints - 1) {
2155 m_slow_k = 0;
2156 } else {
2157 m_slow_k++;
2158 }
2159
2160 if (number_of_joints == 0)
2161 {
2162 LOG_ERROR("Lost connection with the robot. You should save and restart.\n" );
2164
2165 for (int i = 0; i<m_layout->count(); i++){
2166 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
2167 joint->setJointState(JointItem::Disconnected);
2168 }
2169 return false;
2170 }
2171
2172 // *** update measured encoders, velocity, torques ***
2173 bool b = true;
2174 if (true)
2175 {
2176 b = m_iencs->getEncoders(m_positions.data());
2177 if (!b) { yWarning("Unable to update encoders"); return false; }
2178 }
2179 if (true)
2180 {
2181 b = m_iTrq->getTorques(m_torques.data());
2182 if (!b) { yWarning("Unable to update torques"); }
2183 }
2184 if (this->m_part_currentVisible)
2185 {
2186 b = m_iCur->getCurrents(m_currents.data());
2187 if (!b) { yWarning("Unable to update currents"); }
2188 }
2189 if (this->m_part_speedVisible)
2190 {
2191 b = m_iencs->getEncoderSpeeds(m_speeds.data());
2192 if (!b) { yWarning("Unable to update speeds"); }
2193 }
2194 if (this->m_part_motorPositionVisible)
2195 {
2196 b = m_iMot->getMotorEncoders(m_motorPositions.data());
2197 if (!b) { yWarning("Unable to update motorPositions"); }
2198 }
2199 if (this->m_part_dutyVisible)
2200 {
2201 b = m_iPWM->getDutyCycles(m_dutyCycles.data());
2202 if (!b) { yWarning("Unable to update dutyCycles"); }
2203 }
2204
2205 // *** update checkMotionDone, refTorque, refTrajectorySpeed, refSpeed ***
2206 // (only one at a time in order to save bandwidth)
2207 bool boolval = true;
2208 bool b_motdone = m_iPos->checkMotionDone(m_slow_k, &boolval); //using k to save bandwidth
2209 m_done[m_slow_k] = boolval;
2210 bool b_refTrq = m_iTrq->getRefTorque(m_slow_k, &m_refTorques[m_slow_k]); //using k to save bandwidth
2211 bool b_refPosSpeed = m_iPos->getRefSpeed(m_slow_k, &m_refTrajectorySpeeds[m_slow_k]); //using k to save bandwidth
2212 bool b_refVel = m_iVel->getRefVelocity(m_slow_k, &m_refVelocitySpeeds[m_slow_k]); //this interface is missing!
2213 bool b_refPos = m_iPos->getTargetPosition(m_slow_k, &m_refTrajectoryPositions[m_slow_k]);
2214
2215 if (!b_refPos)
2216 {
2217 yError() << "Missing Implementation of getTargetPosition()";
2218 }
2219 if (!b_refVel)
2220 {
2221 yError() << "Missing Implementation of getRefVelocity()";
2222 }
2223 if (!b_refPosSpeed)
2224 {
2225 yError() << "Missing Implementation of getRefSpeed()";
2226 }
2227 if (!b_refTrq)
2228 {
2229 yError() << "Missing Implementation of getRefTorque()";
2230 }
2231 if (!b_motdone)
2232 {
2233 yError() << "Missing Implementation of checkMotionDone()";
2234 }
2235
2236 // *** update the widget every cycle ***
2237 for (int jk = 0; jk < number_of_joints; jk++)
2238 {
2239 auto* joint = (JointItem*)m_layout->itemAt(jk)->widget();
2240 if (true) { joint->setPosition(m_positions[jk]); }
2241 else {}
2242 if (true) { joint->setTorque(m_torques[jk]); }
2243 else {}
2244 if (true) { joint->setSpeed(m_speeds[jk]); }
2245 else {}
2246 if (true) { joint->setCurrent(m_currents[jk]); }
2247 else {}
2248 if (true) { joint->setMotorPosition(m_motorPositions[jk]); }
2249 else {}
2250 if (true) { joint->setDutyCycles(m_dutyCycles[jk]); }
2251 else {}
2252 }
2253
2254 // *** update the widget NOT every cycle ***
2255 {
2256 auto* joint_slow_k = (JointItem*)m_layout->itemAt(m_slow_k)->widget();
2257 if (b_refTrq) { joint_slow_k->setRefTorque(m_refTorques[m_slow_k]); }
2258 else {}
2259 if (b_refPosSpeed) { joint_slow_k->setRefTrajectorySpeed(m_refTrajectorySpeeds[m_slow_k]); }
2260 else {}
2261 if (b_refPos) { joint_slow_k->setRefTrajectoryPosition(m_refTrajectoryPositions[m_slow_k]); }
2262 else {}
2263 if (b_refVel) { joint_slow_k->setRefVelocitySpeed(m_refVelocitySpeeds[m_slow_k]); }
2264 else {}
2265 if (b_motdone) { joint_slow_k->updateMotionDone(m_done[m_slow_k]); }
2266 else {}
2267 }
2268
2269
2270 // *** update the controlMode, interactionMode ***
2271 // this is already done by updateControlMode() (because it also needs to update the tree, not only the single joint widget)
2272 // ret=ctrlmode2->getControlModes(controlModes);
2273 // if(ret==false){
2274 // LOG_ERROR("ictrl->getControlMode failed\n" );
2275 // }
2276 ret = m_iinteract->getInteractionModes(m_interactionModes.data());
2277 if(ret==false){
2278 LOG_ERROR("iint->getInteractionlMode failed\n" );
2279 }
2280
2281 //optional
2282 if (m_ijointfault)
2283 {
2284 for (int k = 0; k < number_of_joints; k++)
2285 {
2286 if (m_controlModes[k]==VOCAB_CM_HW_FAULT)
2287 {
2288 int fault;
2289 std::string message;
2290 if (m_ijointfault->getLastJointFault(k,fault,message))
2291 {
2292 auto* joint_slow_k = (JointItem*)m_layout->itemAt(m_slow_k)->widget();
2293 joint_slow_k->updateJointFault(fault, message);
2294 }
2295 else
2296 {
2297 LOG_ERROR("Unsuccessful call to getLastJointFault()\n");
2298 }
2299 }
2300 }
2301 }
2302
2303
2304 for (int k = 0; k < number_of_joints; k++)
2305 {
2306 auto* joint = (JointItem*)m_layout->itemAt(k)->widget();
2307 switch (m_controlModes[k])
2308 {
2309 case VOCAB_CM_IDLE:
2310 joint->setJointState(JointItem::Idle);
2311 break;
2312 case VOCAB_CM_POSITION:
2313 joint->setJointState(JointItem::Position);
2314 break;
2316 joint->setJointState(JointItem::PositionDirect);
2317 break;
2318 case VOCAB_CM_MIXED:
2319 joint->setJointState(JointItem::Mixed);
2320 break;
2321 case VOCAB_CM_VELOCITY:
2322 joint->setJointState(JointItem::Velocity);
2323 break;
2324 case VOCAB_CM_TORQUE:
2325 joint->setJointState(JointItem::Torque);
2326 break;
2327 case VOCAB_CM_CURRENT:
2328 {
2329 joint->setJointState(JointItem::Current);
2330 double ref_current = 0;
2331 m_iCur->getRefCurrent(k, &ref_current);
2332 joint->setRefCurrent(ref_current);
2333 break;
2334 }
2335 case VOCAB_CM_PWM:
2336 {
2337 joint->setJointState(JointItem::Pwm);
2338 double ref_duty = 0;
2339 m_iPWM->getRefDutyCycle(k, &ref_duty);
2340 joint->setRefPWM(ref_duty);
2341 break;
2342 }
2343 case VOCAB_CM_HW_FAULT:
2344 joint->setJointState(JointItem::HwFault);
2345 break;
2347 joint->setJointState(JointItem::Calibrating);
2348 break;
2350 joint->setJointState(JointItem::CalibDone);
2351 break;
2353 joint->setJointState(JointItem::NotConfigured);
2354 break;
2356 joint->setJointState(JointItem::Configured);
2357 break;
2358 default:
2359 case VOCAB_CM_UNKNOWN:
2360 joint->setJointState(JointItem::Unknown);
2361 break;
2362 }
2363 switch (m_interactionModes[k])
2364 {
2365 case VOCAB_IM_STIFF:
2366 joint->setJointInteraction(JointItem::Stiff);
2367 break;
2368 case VOCAB_IM_COMPLIANT:
2369 joint->setJointInteraction(JointItem::Compliant);
2370 break;
2371 default:
2372 case VOCAB_IM_UNKNOWN:
2373 //joint->setJointInteraction(JointItem::Stiff); TODO
2374 break;
2375 }
2376 }
2377 return true;
2378}
constexpr yarp::conf::vocab32_t VOCAB_CM_UNKNOWN
constexpr yarp::conf::vocab32_t VOCAB_CM_MIXED
constexpr yarp::conf::vocab32_t VOCAB_CM_TORQUE
constexpr yarp::conf::vocab32_t VOCAB_CM_PWM
constexpr yarp::conf::vocab32_t VOCAB_CM_HW_FAULT
constexpr yarp::conf::vocab32_t VOCAB_CM_IDLE
constexpr yarp::conf::vocab32_t VOCAB_CM_CALIB_DONE
constexpr yarp::conf::vocab32_t VOCAB_CM_NOT_CONFIGURED
constexpr yarp::conf::vocab32_t VOCAB_CM_POSITION
constexpr yarp::conf::vocab32_t VOCAB_CM_CONFIGURED
constexpr yarp::conf::vocab32_t VOCAB_CM_CURRENT
constexpr yarp::conf::vocab32_t VOCAB_CM_POSITION_DIRECT
constexpr yarp::conf::vocab32_t VOCAB_CM_VELOCITY
constexpr yarp::conf::vocab32_t VOCAB_CM_FORCE_IDLE
constexpr yarp::conf::vocab32_t VOCAB_CM_CALIBRATING
bool ret
#define yInfo(...)
Definition Log.h:319
#define yError(...)
Definition Log.h:361
#define yDebug(...)
Definition Log.h:275
#define yWarning(...)
Definition Log.h:340
int SIGNAL(int pid, int signum)
Original license follows:
Definition flowlayout.h:59
QLayoutItem * itemAt(int index) const override
int count() const override
@ PositionDirect
Definition jointitem.h:33
@ Disconnected
Definition jointitem.h:34
@ Calibrating
Definition jointitem.h:34
@ NotConfigured
Definition jointitem.h:34
void initInterfaces()
Definition partitem.cpp:353
bool openPolyDrivers()
Definition partitem.cpp:332
bool checkAndGo()
void onSetCurSliderOptionPI(int mode, double step)
void cycleTimeSequence()
bool homePart()
bool checkAndRunAllSeq()
void onViewDutyCycles(bool)
void resizeWidget(int w)
bool homeToCustomPosition(const yarp::os::Bottle &positionElement)
void setCurrentIndex(int)
void runTimeSequence()
void idlePart()
JointItem * getJointWidget(int jointIndex)
int getNumberOfJoints()
void onEnableControlCurrent(bool control)
bool getInterfaceError()
Definition partitem.cpp:481
void onViewMotorPositions(bool)
void onEnableControlPWM(bool control)
void runPart()
void onEnableControlVelocity(bool control)
QString getJointName(int joint)
QString getPartName()
Definition partitem.cpp:486
void onViewPositionTargetValue(bool)
void onViewPositionTargetBox(bool)
bool homeJoint(int joint)
void onViewCurrentValues(bool)
void runSequence()
void sendPartJointsValues(int, QList< double >, QList< double >)
bool checkAndCycleAllSeq()
void closeSequenceWindow()
bool updatePart()
void onViewSpeedValues(bool)
void openSequenceWindow()
void updateControlMode()
void stopSequence()
void stoppedSequence()
void onEnableControlPositionDirect(bool control)
void saveSequence(QString global_filename)
void resizeEvent(QResizeEvent *event) override
void changeEvent(QEvent *event) override
void loadSequence()
void sequenceStopped()
PartItem(std::string robotName, int partId, std::string partName, ResourceFinder &_finder, bool debug_param_enabled, bool speedview_param_enabled, bool enable_calib_all, QWidget *parent=0)
Definition partitem.cpp:25
const QVector< JointItem::JointState > & getPartModes()
void cycleSequence()
void onEnableControlMixed(bool control)
void onSetPosSliderOptionPI(int mode, double step, int numOfDec)
void sequenceActivated()
void onSetTrqSliderOptionPI(int mode, double step)
bool checkAndRunTimeAllSeq()
bool checkAndCycleTimeAllSeq()
void onSetVelSliderOptionPI(int mode, double step)
void calibratePart()
bool openInterfaces()
Definition partitem.cpp:376
void initVelocity(Pid myPid)
Definition piddlg.cpp:141
void initPosition(Pid myPid)
Definition piddlg.cpp:111
void initStiffness(double curStiffVal, double minStiff, double maxStiff, double curDampVal, double minDamp, double maxDamp, double curForceVal, double minForce, double maxForce)
Definition piddlg.cpp:317
void initTorque(Pid myPid, MotorTorqueParameters TorqueParam)
Definition piddlg.cpp:171
void initCurrent(Pid myPid)
Definition piddlg.cpp:346
void initRemoteVariables(IRemoteVariables *iVar)
Definition piddlg.cpp:251
void initPWM(double pwmVal, double pwm)
Definition piddlg.cpp:338
void save(QString global_filename)
void loadSequence(QList< SequenceItem >)
bool view(T *&x)
Get an interface to the device driver.
virtual bool getAxisName(int axis, std::string &name)=0
virtual bool getJointType(int axis, yarp::dev::JointTypeEnum &type)
Definition IAxisInfo.h:63
virtual bool getVelLimits(int axis, double *min, double *max)=0
Get the software speed limits for a particular axis.
virtual bool getLimits(int axis, double *min, double *max)=0
Get the software limits for a particular axis.
virtual bool setControlMode(const int j, const int mode)=0
Set the current control mode.
virtual bool getControlModes(int *modes)=0
Get the current control mode (multiple joints).
virtual bool getControlMode(int j, int *mode)=0
Get the current control mode.
virtual bool getCurrents(double *currs)=0
Get the instantaneous current measurement for all motors.
virtual bool setRefCurrent(int m, double curr)=0
Set the reference value of the current for a single motor.
virtual bool getCurrentRange(int m, double *min, double *max)=0
Get the full scale of the current measurement for a given motor (e.g.
virtual bool getRefCurrent(int m, double *curr)=0
Get the reference value of the current for a single motor.
virtual bool getEncoder(int j, double *v)=0
Read the value of an encoder.
virtual bool getEncoders(double *encs)=0
Read the position of all axes.
virtual bool getEncoderSpeeds(double *spds)=0
Read the instantaneous speed of all axes.
virtual bool setImpedance(int j, double stiffness, double damping)=0
Set current impedance gains (stiffness,damping) for a specific joint.
virtual bool getImpedanceOffset(int j, double *offset)=0
Get current force Offset for a specific joint.
virtual bool getImpedance(int j, double *stiffness, double *damping)=0
Get current impedance gains (stiffness,damping,offset) for a specific joint.
virtual bool getCurrentImpedanceLimit(int j, double *min_stiff, double *max_stiff, double *min_damp, double *max_damp)=0
Get the current impedandance limits for a specific joint.
virtual bool getInteractionModes(int n_joints, int *joints, yarp::dev::InteractionModeEnum *modes)=0
Get the current interaction mode of the robot for a set of joints, values can be stiff or compliant.
virtual bool setInteractionMode(int axis, yarp::dev::InteractionModeEnum mode)=0
Set the interaction mode of the robot, values can be stiff or compliant.
virtual bool getLastJointFault(int j, int &fault, std::string &message)=0
virtual bool getMotorEncoders(double *encs)=0
Read the position of all motor encoders.
virtual bool getDutyCycle(int m, double *val)=0
Gets the current dutycycle of the output of the amplifier (i.e.
virtual bool setRefDutyCycle(int m, double ref)=0
Sets the reference dutycycle to a single motor.
virtual bool getRefDutyCycle(int m, double *ref)=0
Gets the last reference sent using the setRefDutyCycle function.
virtual bool getDutyCycles(double *vals)=0
Gets the current dutycycle of the output of the amplifier (i.e.
virtual bool setPid(const PidControlTypeEnum &pidtype, int j, const Pid &pid)=0
Set new pid value for a joint axis.
virtual bool getPid(const PidControlTypeEnum &pidtype, int j, Pid *pid)=0
Get current pid value for a specific joint.
virtual bool getAxes(int *ax)=0
Get the number of controlled axes.
virtual bool setRefSpeed(int j, double sp)=0
Set reference speed for a joint, this is the speed used during the interpolation of the trajectory.
virtual bool getTargetPosition(const int joint, double *ref)
Get the last position reference for the specified axis.
virtual bool setRefSpeeds(const double *spds)=0
Set reference speed on all joints.
virtual bool checkMotionDone(int j, bool *flag)=0
Check if the current trajectory is terminated.
virtual bool getRefSpeed(int j, double *ref)=0
Get reference speed for a joint.
virtual bool positionMove(int j, double ref)=0
Set new reference point for a single axis.
virtual bool setPosition(int j, double ref)=0
Set new position for a single axis.
virtual bool homingSingleJoint(int j)=0
homingSingleJoint: call the homing procedure for a single joint
virtual bool isCalibratorDevicePresent(bool *isCalib)
isCalibratorDevicePresent: check if a calibrator device has been set
virtual bool homingWholePart()=0
homingWholePart: call the homing procedure for a the whole part/device
virtual bool calibrateSingleJoint(int j)=0
calibrateSingleJoint: call the calibration procedure for the single joint
virtual bool calibrateWholePart()=0
calibrateWholePart: call the procedure for calibrating the whole device
virtual bool setRemoteVariable(std::string key, const yarp::os::Bottle &val)=0
virtual bool getRemoteVariable(std::string key, yarp::os::Bottle &val)=0
virtual bool getRemoteVariablesList(yarp::os::Bottle *listOfKeys)=0
virtual bool setRefTorque(int j, double t)=0
Set the reference value of the torque for a given joint.
virtual bool setMotorTorqueParams(int j, const yarp::dev::MotorTorqueParameters params)
Set a subset of motor parameters (bemf, ktau etc) useful for torque control.
virtual bool getMotorTorqueParams(int j, yarp::dev::MotorTorqueParameters *params)
Get a subset of motor parameters (bemf, ktau etc) useful for torque control.
virtual bool getTorques(double *t)=0
Get the value of the torque for all joints (this is the feedback if you have torque sensors).
virtual bool getTorqueRange(int j, double *min, double *max)=0
Get the full scale of the torque sensor of a given joint.
virtual bool getRefTorque(int j, double *t)=0
Get the reference value of the torque for a given joint.
virtual bool setRefAcceleration(int j, double acc)=0
Set reference acceleration for a joint.
virtual bool getRefVelocity(const int joint, double *vel)
Get the last reference speed set by velocityMove for single joint.
virtual bool velocityMove(int j, double sp)=0
Start motion at a given speed, single joint.
Contains the parameters for a PID.
A container for a device driver.
Definition PolyDriver.h:23
bool close() override
Close the DeviceDriver.
bool isValid() const
Check if device is valid.
bool open(const std::string &txt)
Construct and configure a device by its common name.
A simple collection of objects that can be described and transmitted in a portable way.
Definition Bottle.h:64
size_type size() const
Gets the number of elements in the bottle.
Definition Bottle.cpp:251
Value & get(size_type index) const
Reads a Value v from a certain part of the list.
Definition Bottle.cpp:246
std::string toString() const override
Gives a human-readable textual representation of the bottle.
Definition Bottle.cpp:211
A mini-server for performing network communication in the background.
void close() override
Stop port activity.
bool open(const std::string &name) override
Start port operation, with a specific name, with automatically-chosen network parameters.
Represents how to reach a part of a YARP network.
Definition Contact.h:33
bool write(const PortWriter &writer, const PortWriter *callback=nullptr) const override
Write an object to the port.
Definition Port.cpp:436
bool setEnvelope(PortWriter &envelope) override
Set an envelope (e.g., a timestamp) to the next message which will be sent.
Definition Port.cpp:547
bool open(const std::string &name) override
Start port operation, with a specific name, with automatically-chosen network parameters.
Definition Port.cpp:79
void put(const std::string &key, const std::string &value)
Associate the given key with the given string.
Definition Property.cpp:987
Helper class for finding config files and other external resources.
bool isNull() const override
Checks if the object is invalid.
void update()
Set the timestamp to the current time, and increment the sequence number (wrapping to 0 if the sequen...
Definition Stamp.cpp:124
static void delaySystem(double seconds)
virtual bool isString() const
Checks if value is a string.
Definition Value.cpp:156
virtual std::string asString() const
Get string value.
Definition Value.cpp:234
bool speedview_param_enabled
Definition main.cpp:35
bool debug_param_enabled
Definition main.cpp:34
bool enable_calib_all
Definition main.cpp:36
#define LOG_INFO(...)
Definition log.h:25
#define LOG_ERROR(...)
Definition log.h:19
@ VOCAB_PIDTYPE_TORQUE
Definition PidEnums.h:18
@ VOCAB_PIDTYPE_VELOCITY
Definition PidEnums.h:17
@ VOCAB_PIDTYPE_POSITION
Definition PidEnums.h:16
@ VOCAB_PIDTYPE_CURRENT
Definition PidEnums.h:19
@ VOCAB_JOINTTYPE_REVOLUTE
Definition IAxisInfo.h:24
#define MAX_WIDTH_JOINT
Definition partitem.h:37