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::onSendForceOffset(int jointIdex,double force)
650{
651 double offset_val=0;
652
656
657 double off_max=0.0;
658 double off_min=0.0;
660
661 if (m_currentPidDlg)
662 {
663 m_currentPidDlg->initTorqueOffset(offset_val, off_min, off_max);
664 }
665}
666
667void PartItem::onSendStiffness(int jointIdex,double stiff,double damp)
668{
669 double stiff_val=0;
670 double damp_val=0;
671
672 m_iImp->setImpedance(jointIdex, stiff, damp);
675
676 //update the impedance limits
677 double stiff_max=0.0;
678 double stiff_min=0.0;
679 double damp_max=0.0;
680 double damp_min=0.0;
681
683
684 if (m_currentPidDlg)
685 {
686 m_currentPidDlg->initStiffness(stiff_val, stiff_min, stiff_max,
688 }
689
690
691}
692
693void PartItem::onSendTorquePid(int jointIndex,Pid newPid,MotorTorqueParameters newTrqParam)
694{
695 Pid myTrqPid(0,0,0,0,0,0);
697 m_iPid->setPid(VOCAB_PIDTYPE_TORQUE, jointIndex, newPid);
698
699 m_iTrq->setMotorTorqueParams(jointIndex, newTrqParam);
701 m_iPid->getPid(VOCAB_PIDTYPE_TORQUE,jointIndex, &myTrqPid);
702 m_iTrq->getMotorTorqueParams(jointIndex, &TrqParam);
703
704 if (m_currentPidDlg){
705 m_currentPidDlg->initTorque(myTrqPid, TrqParam);
706 }
707}
708
709void PartItem::onSendPositionPid(int jointIndex,Pid newPid)
710{
711 Pid myPosPid(0,0,0,0,0,0);
712 m_iPid->setPid(VOCAB_PIDTYPE_POSITION, jointIndex, newPid);
714 m_iPid->getPid(VOCAB_PIDTYPE_POSITION, jointIndex, &myPosPid);
715
716 if (m_currentPidDlg){
717 m_currentPidDlg->initPosition(myPosPid);
718 }
719}
720
721void PartItem::onSendVelocityPid(int jointIndex, Pid newPid)
722{
723 Pid myVelPid(0, 0, 0, 0, 0, 0);
724 m_iPid->setPid(VOCAB_PIDTYPE_VELOCITY, jointIndex, newPid);
726 m_iPid->getPid(VOCAB_PIDTYPE_VELOCITY, jointIndex, &myVelPid);
727
728 if (m_currentPidDlg){
729 m_currentPidDlg->initVelocity(myVelPid);
730 }
731}
732
733void PartItem::onRefreshPids(int jointIndex)
734{
735 Pid myPosPid(0, 0, 0, 0, 0, 0);
736 Pid myTrqPid(0, 0, 0, 0, 0, 0);
737 Pid myVelPid(0, 0, 0, 0, 0, 0);
738 Pid myCurPid(0, 0, 0, 0, 0, 0);
740 double stiff_val = 0;
741 double damp_val = 0;
742 double stiff_max = 0;
743 double damp_max = 0;
744 double off_max = 0;
745 double stiff_min = 0;
746 double damp_min = 0;
747 double off_min = 0;
748 double impedance_offset_val = 0;
749 double pwm_reference = 0;
750 double current_pwm = 0;
751
753 m_iTrq->getTorqueRange(jointIndex, &off_min, &off_max);
754
755 // Position
756 m_iPid->getPid(VOCAB_PIDTYPE_POSITION, jointIndex, &myPosPid);
758
759 // Velocity
760 m_iPid->getPid(VOCAB_PIDTYPE_VELOCITY, jointIndex, &myVelPid);
762
763 // Current
764 if (m_iCur)
765 {
766 m_iPid->getPid(VOCAB_PIDTYPE_CURRENT, jointIndex, &myCurPid);
768 }
769
770 // Torque
771 m_iPid->getPid(VOCAB_PIDTYPE_TORQUE, jointIndex, &myTrqPid);
772 m_iTrq->getMotorTorqueParams(jointIndex, &motorTorqueParams);
774
775 //Stiff
776 m_iImp->getImpedance(jointIndex, &stiff_val, &damp_val);
777 m_iImp->getImpedanceOffset(jointIndex, &impedance_offset_val);
779
780 // PWM
781 m_iPWM->getRefDutyCycle(jointIndex, &pwm_reference);
782 m_iPWM->getDutyCycle(jointIndex, &current_pwm);
783
784 if (m_currentPidDlg)
785 {
786 m_currentPidDlg->initPosition(myPosPid);
787 m_currentPidDlg->initTorque(myTrqPid, motorTorqueParams);
788 m_currentPidDlg->initVelocity(myVelPid);
789 m_currentPidDlg->initCurrent(myCurPid);
792 m_currentPidDlg->initPWM(pwm_reference, current_pwm);
793 m_currentPidDlg->initRemoteVariables(m_iVar);
794 }
795}
796
797void PartItem::onSendCurrentPid(int jointIndex, Pid newPid)
798{
799 if (m_iCur == nullptr)
800 {
801 yError() << "iCurrent interface not opened";
802 return;
803 }
804 Pid myCurPid(0, 0, 0, 0, 0, 0);
805 m_iPid->setPid(VOCAB_PIDTYPE_CURRENT, jointIndex, newPid);
807 m_iPid->getPid(VOCAB_PIDTYPE_CURRENT, jointIndex, &myCurPid);
808
809 if (m_currentPidDlg){
810 m_currentPidDlg->initCurrent(myCurPid);
811 }
812}
813
814void PartItem::onSendSingleRemoteVariable(std::string key, yarp::os::Bottle val)
815{
816 m_iVar->setRemoteVariable(key, val);
818}
819
820void PartItem::onUpdateAllRemoteVariables()
821{
822 if (m_currentPidDlg){
823 m_currentPidDlg->initRemoteVariables(m_iVar);
824 }
825}
826
827void PartItem::onCalibClicked(JointItem *joint)
828{
829 if (!m_iremCalib)
830 {
831 QMessageBox::critical(this,"Operation not supported", QString("The IRemoteCalibrator interface was not found on this application"));
832 return;
833 }
834
835 if(QMessageBox::question(this,"Question","Do you really want to recalibrate the joint?") != QMessageBox::Yes){
836 return;
837 }
838 if (!m_iremCalib->calibrateSingleJoint(joint->getJointIndex()))
839 {
840 // provide better feedback to user by verifying if the calibrator device was set or not
841 bool isCalib = false;
842 m_iremCalib->isCalibratorDevicePresent(&isCalib);
843 if (!isCalib) {
844 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"));
845 } else {
846 QMessageBox::critical(this, "Calibration failed", QString("The remote calibrator reported that something went wrong during the calibration procedure"));
847 }
848 }
849
850}
851
852void PartItem::onPidClicked(JointItem *joint)
853{
854 const int jointIndex = joint->getJointIndex();
855 QString jointName = joint->getJointName();
856 m_currentPidDlg = new PidDlg(m_partName.c_str(), jointIndex, jointName);
857 connect(m_currentPidDlg, SIGNAL(sendPositionPid(int, Pid)), this, SLOT(onSendPositionPid(int, Pid)));
858 connect(m_currentPidDlg, SIGNAL(sendVelocityPid(int, Pid)), this, SLOT(onSendVelocityPid(int, Pid)));
859 connect(m_currentPidDlg, SIGNAL(sendCurrentPid(int, Pid)), this, SLOT(onSendCurrentPid(int, Pid)));
860 connect(m_currentPidDlg, SIGNAL(sendSingleRemoteVariable(std::string, yarp::os::Bottle)), this, SLOT(onSendSingleRemoteVariable(std::string, yarp::os::Bottle)));
861 connect(m_currentPidDlg, SIGNAL(updateAllRemoteVariables()), this, SLOT(onUpdateAllRemoteVariables()));
862 connect(m_currentPidDlg, SIGNAL(sendTorquePid(int, Pid, MotorTorqueParameters)), this, SLOT(onSendTorquePid(int, Pid, MotorTorqueParameters)));
863 connect(m_currentPidDlg, SIGNAL(sendStiffness(int, double, double)), this, SLOT(onSendStiffness(int, double, double)));
864 connect(m_currentPidDlg, SIGNAL(sendForceOffset(int, double)), this, SLOT(onSendForceOffset(int, double)));
865 connect(m_currentPidDlg, SIGNAL(sendPWM(int, double)), this, SLOT(onSendPWM(int, double)));
866 connect(m_currentPidDlg, SIGNAL(refreshPids(int)), this, SLOT(onRefreshPids(int)));
867 connect(m_currentPidDlg, SIGNAL(dumpRemoteVariables()), this, SLOT(onDumpAllRemoteVariables()));
868
869 this->onRefreshPids(jointIndex);
870
871 m_currentPidDlg->exec();
872
873 delete m_currentPidDlg;
874 m_currentPidDlg = nullptr;
875}
876
877void PartItem::onRunClicked(JointItem *joint)
878{
879 const int jointIndex = joint->getJointIndex();
880 double posJoint;
881 while (!m_iencs->getEncoder(jointIndex, &posJoint)){
883 }
884
885 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_POSITION);
886}
887
888void PartItem::onIdleClicked(JointItem *joint)
889{
890 const int jointIndex = joint->getJointIndex();
891 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_FORCE_IDLE);
892}
893
894void PartItem::onHomeClicked(JointItem *joint)
895{
897 const int jointIndex = joint->getJointIndex();
898 m_iPos->getAxes(&NUMBER_OF_JOINTS);
899
900 this->homeJoint(jointIndex);
901}
902
903void PartItem::onJointChangeMode(int mode,JointItem *joint)
904{
905 const int jointIndex = joint->getJointIndex();
906 switch (mode) {
907 case JointItem::Idle:{
908 yInfo("joint: %d in IDLE mode", jointIndex);
909 if (m_ictrlmode){
910 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_IDLE);
911 } else {
912 yError("ERROR: cannot do!");
913 }
914 break;
915 }
917 yInfo("joint: %d in POSITION mode", jointIndex);
918 if (m_ictrlmode){
919 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_POSITION);
920 joint->resetTarget();
921 } else {
922 yError("ERROR: cannot do!");
923 }
924 break;
925 }
927 //if(positionDirectEnabled){
928 yInfo("joint: %d in POSITION DIRECT mode", jointIndex);
929 if (m_ictrlmode){
930 joint->resetTarget();
931 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_POSITION_DIRECT);
932 } else {
933 yError("ERROR: cannot do!");
934 }
935 break;
936 /*}else{
937 LOG_ERROR("joint: %d in MIXED mode", jointIndex);
938 if(ctrlmode2){
939 ctrlmode2->setControlMode(jointIndex, VOCAB_CM_MIXED);
940 } else {
941 yError("ERROR: cannot do!");
942 }
943 break;
944 }*/
945 }
946 case JointItem::Mixed:{
947 //if(positionDirectEnabled){
948 yInfo("joint: %d in MIXED mode", jointIndex);
949 if (m_ictrlmode){
950 joint->resetTarget();
951 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_MIXED);
952 } else {
953 yError("ERROR: cannot do!");
954 }
955 break;
956 /*}else{
957 LOG_ERROR("joint: %d in VELOCITY mode", jointIndex);
958 if(ctrlmode2){
959 ctrlmode2->setVelocityMode(jointIndex);
960 } else {
961 LOG_ERROR("ERROR: cannot do!");
962 }
963 break;
964 }*/
965
966 }
968 //if(positionDirectEnabled){
969 yInfo("joint: %d in VELOCITY mode", jointIndex);
970 if (m_ictrlmode)
971 {
972 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_VELOCITY);
973 yInfo() << "Changing reference acceleration of joint " << jointIndex << " to 100000";
974 m_iVel->setRefAcceleration(jointIndex, 100000);
975 } else {
976 yError("ERROR: cannot do!");
977 }
978 break;
979// } else {
980// LOG_ERROR("joint: %d in TORQUE mode", jointIndex);
981// if(ctrlmode2){
982// ctrlmode2->setTorqueMode(jointIndex);
983// } else {
984// LOG_ERROR("ERROR: cannot do!");
985// }
986// break;
987// }
988 }
989
990 case JointItem::Torque:{
991 //if(positionDirectEnabled){
992 yInfo("joint: %d in TORQUE mode", jointIndex);
993 if (m_ictrlmode){
994 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_TORQUE);
995 } else {
996 yError("ERROR: cannot do!");
997 }
998 break;
999// } else {
1000// LOG_ERROR("joint: %d in TORQUE mode", jointIndex);
1001// if(ctrlmode2){
1002// ctrlmode2->setTorqueMode(jointIndex);
1003// } else {
1004// LOG_ERROR("ERROR: cannot do!");
1005// }
1006// break;
1007// }
1008
1009 }
1010 case JointItem::Pwm:{
1011 yInfo("joint: %d in PWM mode", jointIndex);
1012 if (m_ictrlmode){
1013 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_PWM);
1014 } else {
1015 yError("ERROR: cannot do!");
1016 }
1017 break;
1018 }
1019 case JointItem::Current:{
1020 yInfo("joint: %d in CURRENT mode", jointIndex);
1021 if (m_ictrlmode){
1022 m_ictrlmode->setControlMode(jointIndex, VOCAB_CM_CURRENT);
1023 }
1024 else {
1025 yError("ERROR: cannot do!");
1026 }
1027 break;
1028 }
1029 default:
1030 break;
1031 }
1032}
1033
1035{
1036 int count = m_layout->count();
1037
1038
1039 int jointPerLineCount = (w - 20) / (MAX_WIDTH_JOINT + 10);
1040 if(jointPerLineCount > count){
1041 jointPerLineCount = count;
1042 }
1043 if(jointPerLineCount <= 0){
1044 return;
1045 }
1046
1047 int extraSpace = (w - 20) - jointPerLineCount * (MAX_WIDTH_JOINT + 10);
1048
1049
1050
1051 for(int i=0;i<count;i++){
1052 QWidget *widget = m_layout->itemAt(i)->widget();
1053 if(widget){
1054 widget->setMaximumWidth(MAX_WIDTH_JOINT + (extraSpace/jointPerLineCount));
1055 widget->setMinimumWidth(MAX_WIDTH_JOINT + (extraSpace/jointPerLineCount));
1056 }
1057
1058 }
1059}
1060
1062{
1063 return m_layout->count();
1064}
1065
1067{
1069 {
1070 return "";
1071 }
1072
1073 auto* jointWidget = (JointItem*)m_layout->itemAt(joint)->widget();
1074
1075 return jointWidget->getJointName();
1076}
1077
1079{
1080 return (JointItem*)m_layout->itemAt(jointIndex)->widget();
1081}
1082
1084{
1085 if(!isVisible()){
1086 return;
1087 }
1088
1089 resizeWidget(event->size().width());
1090}
1091
1093{
1094 if(event->type() == QEvent::WindowStateChange ){
1095 qDebug() << "State Changed " << width();
1096 int count = m_layout->count();
1097 int jointPerLineCount = (width() - 20) / (MAX_WIDTH_JOINT + 10);
1098
1099 if(jointPerLineCount > count){
1100 jointPerLineCount = count;
1101 }
1102 if(jointPerLineCount <= 0){
1103 return;
1104 }
1105 int extraSpace = (width() - 20) - jointPerLineCount * (MAX_WIDTH_JOINT + 10);
1106
1107
1109
1110 for(int i=0;i<count;i++){
1111 QWidget *widget = m_layout->itemAt(i)->widget();
1112 if(widget){
1113 widget->setMaximumWidth(MAX_WIDTH_JOINT + (extraSpace/jointPerLineCount));
1114 widget->setMinimumWidth(MAX_WIDTH_JOINT + (extraSpace/jointPerLineCount));
1115 }
1116 }
1117 }
1118
1119}
1120
1122{
1123 if (!m_iremCalib)
1124 {
1125 QMessageBox::critical(this,"Operation not supported", QString("The IRemoteCalibrator interface was not found on this application"));
1126 return;
1127 }
1128
1129 if (!m_iremCalib->calibrateWholePart())
1130 {
1131 // provide better feedback to user by verifying if the calibrator device was set or not
1132 bool isCalib = false;
1133 m_iremCalib->isCalibratorDevicePresent(&isCalib);
1134 if (!isCalib) {
1135 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()));
1136 } else {
1137 QMessageBox::critical(this, "Calibration failed", QString("The remote calibrator reported that something went wrong during the calibration procedure"));
1138 }
1139 }
1140}
1141
1142bool PartItem::homeJoint(int jointIndex)
1143{
1144 if (!m_iremCalib)
1145 {
1146 QMessageBox::critical(this, "Operation not supported", QString("The IRemoteCalibrator interface was not found on this application"));
1147 return false;
1148 }
1149
1150 if (!m_iremCalib->homingSingleJoint(jointIndex))
1151 {
1152 // provide better feedback to user by verifying if the calibrator device was set or not
1153 bool isCalib = false;
1154 m_iremCalib->isCalibratorDevicePresent(&isCalib);
1155 if (!isCalib)
1156 {
1157 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()));
1158 return false;
1159 }
1160 else
1161 {
1162 QMessageBox::critical(this, "Operation failed", QString("The remote calibrator reported that something went wrong during the calibration procedure"));
1163 return false;
1164 }
1165 }
1166 return true;
1167}
1168
1170{
1171 if (!m_iremCalib)
1172 {
1173 QMessageBox::critical(this, "Operation not supported", QString("The IRemoteCalibrator interface was not found on this application"));
1174 return false;
1175 }
1176
1177 if (!m_iremCalib->homingWholePart())
1178 {
1179 // provide better feedback to user by verifying if the calibrator device was set or not
1180 bool isCalib = false;
1181 m_iremCalib->isCalibratorDevicePresent(&isCalib);
1182 if (!isCalib)
1183 {
1184 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()));
1185 return false;
1186 }
1187 else
1188 {
1189 QMessageBox::critical(this, "Operation failed", QString("The remote calibrator reported that something went wrong during the calibration procedure"));
1190 return false;
1191 }
1192 }
1193 return true;
1194}
1195
1197{
1198 bool ok = true;
1199 int NUMBER_OF_JOINTS;
1200 m_iPos->getAxes(&NUMBER_OF_JOINTS);
1201
1202 if (positionElement.isNull()) {
1203 QMessageBox::critical(this, "Operation failed", QString("No custom position supplied in configuration file for part ") + QString(m_partName.c_str()));
1204 return false;
1205 }
1206
1207 //Look for group called m_robotPartPort_Position and m_robotPartPort_Velocity
1208 Bottle xtmp, ytmp;
1209 xtmp = positionElement.findGroup(m_robotPartPort + "_Position");
1210 ok = ok && (xtmp.size() == (size_t) NUMBER_OF_JOINTS + 1);
1211 ytmp = positionElement.findGroup(m_robotPartPort + "_Velocity");
1212 ok = ok && (ytmp.size() == (size_t) NUMBER_OF_JOINTS + 1);
1213
1214 if(ok)
1215 {
1216 for (int jointIndex = 0; jointIndex < NUMBER_OF_JOINTS; jointIndex++)
1217 {
1218 double position = xtmp.get(jointIndex+1).asFloat64();
1219 double velocity = ytmp.get(jointIndex + 1).asFloat64();
1220 m_iPos->setRefSpeed(jointIndex, velocity);
1221 m_iPos->positionMove(jointIndex, position);
1222 }
1223 }
1224 else
1225 {
1226 QMessageBox::critical(this, "Error", QString("Check the number of entries in the group %1").arg(m_robotPartPort.c_str()));
1227 ok = false;
1228 }
1229
1230 return ok;
1231}
1232
1234{
1235 int NUMBER_OF_JOINTS;
1236 m_iPos->getAxes(&NUMBER_OF_JOINTS);
1237
1238 for (int joint=0; joint < NUMBER_OF_JOINTS; joint++){
1239 m_ictrlmode->setControlMode(joint, VOCAB_CM_IDLE);
1240 }
1241}
1242
1244{
1245 if (!m_sequenceWindow){
1246 return false;
1247 }
1248
1249 return m_sequenceWindow->checkAndRun();
1250
1251
1252}
1253
1255{
1256 if (!m_sequenceWindow){
1257 return false;
1258 }
1259
1260 return m_sequenceWindow->checkAndRunTime();
1261
1262
1263}
1264
1266{
1267 if (!m_sequenceWindow){
1268 return false;
1269 }
1270
1271 return m_sequenceWindow->checkAndCycleTimeSeq();
1272}
1273
1275{
1276 if (!m_sequenceWindow){
1277 return false;
1278 }
1279
1280 return m_sequenceWindow->checkAndCycleSeq();
1281}
1282
1284{
1285 int NUMBER_OF_JOINTS;
1286 m_iPos->getAxes(&NUMBER_OF_JOINTS);
1287
1288 for (int joint=0; joint < NUMBER_OF_JOINTS; joint++){
1289 //iencs->getEncoder(joint, &posJoint);
1290 m_ictrlmode->setControlMode(joint, VOCAB_CM_POSITION);
1291 }
1292}
1293
1295{
1297 onOpenSequence();
1298}
1299
1305
1307{
1308 if (m_sequenceWindow)
1309 {
1310 m_sequenceWindow->close();
1311 }
1312}
1313
1315{
1316 if (!m_sequenceWindow){
1317 m_sequenceWindow = new SequenceWindow(m_partName.c_str(), m_layout->count());
1318 connect(m_sequenceWindow, SIGNAL(itemDoubleClicked(int)), this, SLOT(onSequenceWindowDoubleClicked(int)), Qt::DirectConnection);
1319 connect(this, SIGNAL(sendPartJointsValues(int, QList<double>, QList<double>)), m_sequenceWindow, SLOT(onReceiveValues(int, QList<double>, QList<double>)), Qt::DirectConnection);
1320 connect(m_sequenceWindow, SIGNAL(goToPosition(SequenceItem)), this, SLOT(onGo(SequenceItem)));
1321 connect(m_sequenceWindow, SIGNAL(runTime(QList<SequenceItem>)), this, SLOT(onSequenceRunTime(QList<SequenceItem>)), Qt::QueuedConnection);
1322 connect(m_sequenceWindow, SIGNAL(run(QList<SequenceItem>)), this, SLOT(onSequenceRun(QList<SequenceItem>)), Qt::QueuedConnection);
1323 connect(m_sequenceWindow, SIGNAL(saveSequence(QList<SequenceItem>, QString)), this, SLOT(onSaveSequence(QList<SequenceItem>, QString)), Qt::QueuedConnection);
1324 connect(m_sequenceWindow, SIGNAL(openSequence()), this, SLOT(onOpenSequence()));
1325 connect(m_sequenceWindow, SIGNAL(cycle(QList<SequenceItem>)), this, SLOT(onSequenceCycle(QList<SequenceItem>)), Qt::QueuedConnection);
1326 connect(m_sequenceWindow, SIGNAL(cycleTime(QList<SequenceItem>)), this, SLOT(onSequenceCycleTime(QList<SequenceItem>)), Qt::QueuedConnection);
1327 connect(m_sequenceWindow, SIGNAL(stopSequence()), this, SLOT(onStopSequence()), Qt::QueuedConnection);
1328
1329 connect(this, SIGNAL(runTimeSequence()), m_sequenceWindow, SLOT(onRunTimeSequence()));
1330 connect(this, SIGNAL(cycleTimeSequence()), m_sequenceWindow, SLOT(onCycleTimeSequence()));
1331 connect(this, SIGNAL(cycleSequence()), m_sequenceWindow, SLOT(onCycleSequence()));
1332 connect(this, SIGNAL(stoppedSequence()), m_sequenceWindow, SLOT(onStoppedSequence()));
1333 connect(this, SIGNAL(setCurrentIndex(int)), m_sequenceWindow, SLOT(onSetCurrentSequenceIndex(int)));
1334
1335 connect(this,SIGNAL(runTimeSequence()),this,SLOT(onSequenceActivated()));
1336 connect(this,SIGNAL(cycleTimeSequence()),this,SLOT(onSequenceActivated()));
1337 connect(this,SIGNAL(cycleSequence()),this,SLOT(onSequenceActivated()));
1338 connect(this,SIGNAL(stoppedSequence()),this,SLOT(onSequenceStopped()));
1339
1340
1341 }
1342
1343 if (!m_sequenceWindow->isVisible()){
1344 m_sequenceWindow->show();
1345 }else{
1346 m_sequenceWindow->setFocus();
1347 m_sequenceWindow->raise();
1348 m_sequenceWindow->setWindowState(Qt::WindowActive);
1349 }
1350
1351}
1352
1354{
1355 if (!m_sequenceWindow){
1356 return false;
1357 }
1358
1359 return m_sequenceWindow->checkAndGo();
1360}
1362{
1363 m_cycleTimer.stop();
1364 m_runTimer.stop();
1365 m_runTimeTimer.stop();
1366 m_cycleTimeTimer.stop();
1368}
1369
1370void PartItem::onStopSequence()
1371{
1372 stopSequence();
1373}
1374
1375void PartItem::onOpenSequence()
1376{
1377 QString fileName = QFileDialog::getOpenFileName(m_sequenceWindow, QString("Load Sequence for part %1 As").arg(m_partName.c_str()), QDir::homePath());
1378
1379 QFileInfo fInfo(fileName);
1380 if(!fInfo.exists()){
1381 return;
1382 }
1383
1384 QString desiredExtension = QString("pos%1").arg(m_partName.c_str());
1385 QString extension = fInfo.suffix();
1386
1388 QMessageBox::critical(this,"Error Loading The Sequence",
1389 QString("Wrong format (check extensions) of the file associated with: ").arg(m_partName.c_str()));
1390 return;
1391 }
1392
1393 QFile file(fileName);
1394 if (!file.open(QFile::ReadOnly | QFile::Text)){
1395 QString msg = QString("Error: Cannot read file %1: %2").arg(qPrintable(fileName))
1396 .arg(qPrintable(file.errorString()));
1397 QMessageBox::critical(this,"Error Loading The Sequence",msg);
1398 return;
1399 }
1400
1401 QXmlStreamReader reader(&file);
1402 reader.readNext();
1403
1405
1408 while(!reader.atEnd()){
1409 reader.readNext();
1410
1411 if(reader.isStartElement()){
1412 if(reader.name().contains("Sequence_")){ //Sequence_
1413 QXmlStreamAttributes attributes = reader.attributes();
1414 referencePart = attributes.value("ReferencePart").toString();
1415 }
1416
1417 if(reader.name() == "Position"){ //Position
1418 QXmlStreamAttributes attributes = reader.attributes();
1419 int index = attributes.value("Index").toInt();
1420 double timing = attributes.value("Timing").toDouble();
1421 item.setTiming(timing);
1422 item.setSequenceNumber(index);
1423 }
1424
1425 if(reader.name() == "JointPositions"){
1426 QXmlStreamAttributes attributes = reader.attributes();
1427 int count = attributes.value("Count").toInt();
1428
1429 reader.readNext();
1430 for(int i=0; i<count;i++){
1431 reader.readNext();
1432 if(reader.name() == "PosValue"){ //PosValue
1433 double pos = reader.readElementText().toDouble();
1434 item.addPositionValue(pos);
1435 }
1436 reader.readNext();
1437 }
1438
1439 }
1440
1441 if(reader.name() == "JointVelocities"){
1442 QXmlStreamAttributes attributes = reader.attributes();
1443 int count = attributes.value("Count").toInt();
1444
1445 reader.readNext();
1446 for(int i=0; i<count;i++){
1447 reader.readNext();
1448 if(reader.name() == "SpeedValue"){ //SpeedValue
1449 double speed = reader.readElementText().toDouble();
1450 item.addSpeedValue(speed);
1451 }
1452 reader.readNext();
1453 }
1454
1455 }
1456
1457 }
1458
1459 if(reader.isEndElement()){
1460 if(reader.name() == "Position"){
1461 sequenceItems.append(item);
1462 item = SequenceItem();
1463 }
1464 }
1465 }
1466
1467 file.close();
1468
1469 if (reader.hasError())
1470 {
1471 QString msg = QString("Error: Failed to parse file %1: %2").arg(qPrintable(fileName)).arg(qPrintable(reader.errorString()));
1472 QMessageBox::critical(this,"Error Loading The Sequence",msg);
1473 return;
1474 } else if (file.error() != QFile::NoError) {
1475 QString msg = QString("Error: Cannot read file %1: %2").arg(qPrintable(fileName)).arg(qPrintable(file.errorString()));
1476 QMessageBox::critical(this,"Error Loading The Sequence",msg);
1477 return;
1478 }
1479
1480 if (m_sequenceWindow){
1481 m_sequenceWindow->loadSequence(sequenceItems);
1482 }
1483
1484}
1485
1486void PartItem::onSaveSequence(QList<SequenceItem> values, QString fileName)
1487{
1488 if (fileName=="")
1489 {
1490 fileName = QFileDialog::getSaveFileName(this, QString("Save Sequence for part %1 As").arg(m_partName.c_str()), QDir::homePath());
1491 }
1492
1493 if(fileName.isEmpty()){
1494 return;
1495 }
1496
1497 QFileInfo fInfo(fileName);
1498 QString completeFileName = QString("%1/%2.pos%3").arg(fInfo.absolutePath()).arg(fInfo.baseName()).arg(m_partName.c_str());
1499 std::string completeFileName_s = completeFileName.toStdString();
1500
1501 //QFile file(completeFileName);
1502 yInfo("Saving file %s\n", completeFileName_s.c_str());
1503
1504 QFile file(completeFileName);
1505 if(!file.open(QIODevice::WriteOnly)){
1506 return;
1507 }
1508
1509 QXmlStreamWriter writer(&file);
1510 writer.setAutoFormatting(true);
1511 writer.writeStartDocument();
1512
1513 writer.writeStartElement(QString("Sequence_pos%1").arg(m_partName.c_str()));
1514
1515 writer.writeAttribute("TotPositions", QString("%1").arg(values.count()));
1516 writer.writeAttribute("ReferencePart", m_partName.c_str());
1517
1518 for(int i=0;i<values.count();i++){
1520 writer.writeStartElement("Position");
1521 writer.writeAttribute("Index",QString("%1").arg(sequenceItem.getSequenceNumber()));
1522 writer.writeAttribute("Timing",QString("%L1").arg(sequenceItem.getTiming(),0,'f',2));
1523
1524 writer.writeStartElement("JointPositions");
1525 writer.writeAttribute("Count",QString("%1").arg(sequenceItem.getPositions().count()));
1526 for(int j=0;j<sequenceItem.getPositions().count(); j++){
1527 QString s = QString("%L1").arg(sequenceItem.getPositions().at(j),0,'f',2);
1528 writer.writeTextElement("PosValue",s);
1529 }
1530 writer.writeEndElement();
1531
1532 writer.writeStartElement("JointVelocities");
1533 writer.writeAttribute("Count",QString("%1").arg(sequenceItem.getSpeeds().count()));
1534 for(int j=0;j<sequenceItem.getSpeeds().count(); j++){
1535 QString s = QString("%L1").arg(sequenceItem.getSpeeds().at(j),0,'f',2);
1536 writer.writeTextElement("SpeedValue",s);
1537 }
1538 writer.writeEndElement();
1539 writer.writeEndElement();
1540 }
1541 writer.writeEndElement();
1542 writer.writeEndDocument();
1543 file.close();
1544 LOG_INFO("File saved and closed\n");
1545
1546
1547// if(file.open(QIODevice::WriteOnly)){
1548// for(int i=0;i<values.count();i++){
1549// SequenceItem sequenceItem = values.at(i);
1550// QString s = QString("[POSITION%1] \n").arg(sequenceItem.getSequenceNumber());
1551// file.write(s.toLatin1().data(),s.length());
1552
1553// s = QString("jointPositions ");
1554// file.write(s.toLatin1().data(),s.length());
1555
1556// for(int j=0;j<sequenceItem.getPositions().count(); j++){
1557// s = QString("%L1 ").arg(sequenceItem.getPositions().at(j),0,'f',2);
1558// file.write(s.toLatin1().data(),s.length());
1559// }
1560
1561// s = QString("\njointVelocities ");
1562// file.write(s.toLatin1().data(),s.length());
1563// for(int j=0;j<sequenceItem.getSpeeds().count(); j++){
1564// s = QString("%L1 ").arg(sequenceItem.getSpeeds().at(j),0,'f',2);
1565// file.write(s.toLatin1().data(),s.length());
1566// }
1567
1568// s = QString("\ntiming ");
1569// file.write(s.toLatin1().data(),s.length());
1570// s = QString("%L1 \n").arg(sequenceItem.getTiming(),0,'f',2);
1571// file.write(s.toLatin1().data(),s.length());
1572// }
1573// file.flush();
1574// file.close();
1575
1576// LOG_ERROR("File saved and closed\n");
1577// }
1578
1579}
1580
1581void PartItem::onSequenceCycleTime(QList<SequenceItem> values)
1582{
1583 // Remove items after the first timing with value < 0
1584 if (m_cycleTimeTimer.isActive() || m_cycleTimer.isActive() || m_runTimeTimer.isActive() || m_runTimer.isActive()){
1585 return;
1586 }
1587
1588 m_cycleTimeValues.clear();
1589 for(int i=0;i<values.count();i++){
1590 SequenceItem it = values.at(i);
1591 if(it.getTiming() > 0){
1592 m_cycleTimeValues.append(it);
1593 }
1594 }
1595
1597 if (m_cycleTimeValues.count() > 0)
1598 {
1599 vals = m_cycleTimeValues.takeFirst();
1600 m_cycleTimeValues.append(vals);
1601 emit setCurrentIndex(vals.getSequenceNumber());
1602 fixedTimeMove(vals);
1603 m_cycleTimeTimer.start(vals.getTiming() * 1000);
1605 }
1606}
1607
1608void PartItem::onCycleTimeTimerTimeout()
1609{
1610 if (m_cycleTimeValues.count() > 0)
1611 {
1612 SequenceItem vals = m_cycleTimeValues.takeFirst();
1613 m_cycleTimeValues.append(vals);
1614 emit setCurrentIndex(vals.getSequenceNumber());
1615 fixedTimeMove(vals);
1616 m_cycleTimeTimer.start(vals.getTiming() * 1000);
1617 }
1618}
1619
1620void PartItem::onSequenceCycle(QList<SequenceItem> values)
1621{
1622 // Remove items after the first timing with value < 0
1623 if (m_cycleTimeTimer.isActive() || m_cycleTimer.isActive() || m_runTimeTimer.isActive() || m_runTimer.isActive()){
1624 return;
1625 }
1626
1627 m_cycleValues.clear();
1628 for(int i=0;i<values.count();i++){
1629 SequenceItem it = values.at(i);
1630 if(it.getTiming() > 0){
1631 m_cycleValues.append(it);
1632 }
1633 }
1634
1636 if (m_cycleValues.count() > 0){
1637 vals = m_cycleValues.takeFirst();
1638
1639 m_cycleValues.append(vals);
1640
1641 double *cmdPositions = new double[vals.getPositions().count()];
1642 double *cmdVelocities = new double[vals.getSpeeds().count()];
1643
1644 for(int i=0;i<vals.getPositions().count();i++){
1645 cmdPositions[i] = vals.getPositions().at(i);
1646 cmdVelocities[i] = vals.getSpeeds().at(i);
1647 //qDebug() << "vals.getSpeeds().at(i)" << vals.getSpeeds().at(i);
1648 }
1649
1650 emit setCurrentIndex(vals.getSequenceNumber());
1651 //fixedTimeMove(vals.getPositions());
1652 m_iPos->setRefSpeeds(cmdVelocities);
1653 m_iPos->positionMove(cmdPositions);
1654 m_cycleTimer.start(vals.getTiming() * 1000);
1655
1657 }
1658}
1659
1660void PartItem::onCycleTimerTimeout()
1661{
1662 if (m_cycleValues.count() > 0){
1663 SequenceItem vals = m_cycleValues.takeFirst();
1664
1665 m_cycleValues.append(vals);
1666
1667 double *cmdPositions = new double[vals.getPositions().count()];
1668 double *cmdVelocities = new double[vals.getSpeeds().count()];
1669
1670 for(int i=0;i<vals.getPositions().count();i++){
1671 cmdPositions[i] = vals.getPositions().at(i);
1672 cmdVelocities[i] = vals.getSpeeds().at(i);
1673 }
1674
1675 emit setCurrentIndex(vals.getSequenceNumber());
1676 //fixedTimeMove(vals.getPositions());
1677 m_iPos->setRefSpeeds(cmdVelocities);
1678 m_iPos->positionMove(cmdPositions);
1679
1680 m_cycleTimer.start(vals.getTiming() * 1000);
1681 }
1682}
1683
1684void PartItem::onSequenceRun(QList<SequenceItem> values)
1685{
1686 // Remove items after the first timing with value < 0
1687 if (m_cycleTimeTimer.isActive() || m_cycleTimer.isActive() || m_runTimeTimer.isActive() || m_runTimer.isActive()){
1688 return;
1689 }
1690
1691 m_runValues.clear();
1692 for(int i=0;i<values.count();i++){
1693 SequenceItem it = values.at(i);
1694 if(it.getTiming() > 0){
1695 m_runValues.append(it);
1696 }
1697 }
1698
1700 if (m_runValues.count() > 0){
1701 vals = m_runValues.takeFirst();
1702
1703 m_runValues.append(vals);
1704
1705 double *cmdPositions = new double[vals.getPositions().count()];
1706 double *cmdVelocities = new double[vals.getSpeeds().count()];
1707
1708 for(int i=0;i<vals.getPositions().count();i++){
1709 cmdPositions[i] = vals.getPositions().at(i);
1710 cmdVelocities[i] = vals.getSpeeds().at(i);
1711 //qDebug() << "vals.getSpeeds().at(i)" << vals.getSpeeds().at(i);
1712 }
1713
1714 emit setCurrentIndex(vals.getSequenceNumber());
1715 //fixedTimeMove(vals.getPositions());
1716 m_iPos->setRefSpeeds(cmdVelocities);
1717 m_iPos->positionMove(cmdPositions);
1718 m_runTimer.start(vals.getTiming() * 1000);
1719
1720 emit runSequence();
1721 }
1722}
1723void PartItem::onRunTimeout()
1724{
1725 if (m_runValues.count() > 0){
1726 SequenceItem vals = m_runValues.takeFirst();
1727 if(vals.getTiming() < 0){
1729 return;
1730 }
1731 double *cmdPositions = new double[vals.getPositions().count()];
1732 double *cmdVelocities = new double[vals.getSpeeds().count()];
1733
1734 for(int i=0;i<vals.getPositions().count();i++){
1735 cmdPositions[i] = vals.getPositions().at(i);
1736 cmdVelocities[i] = vals.getSpeeds().at(i);
1737 //qDebug() << "vals.getSpeeds().at(i)" << vals.getSpeeds().at(i);
1738 }
1739
1740 emit setCurrentIndex(vals.getSequenceNumber());
1741 //fixedTimeMove(vals.getPositions());
1742 m_iPos->setRefSpeeds(cmdVelocities);
1743 m_iPos->positionMove(cmdPositions);
1744
1745
1746 m_runTimer.start(vals.getTiming() * 1000);
1747 }else{
1749 }
1750}
1751
1752
1753
1754void PartItem::onSequenceRunTime(QList<SequenceItem> values)
1755{
1756 if (m_cycleTimeTimer.isActive() || m_cycleTimer.isActive() || m_runTimeTimer.isActive() || m_runTimer.isActive()){
1757 return;
1758 }
1759
1760 m_runTimeValues.clear();
1761
1762 for(int i=0;i<values.count();i++){
1763 SequenceItem it = values.at(i);
1764 if(it.getTiming() > 0){
1765 m_runTimeValues.append(it);
1766 }
1767 }
1768
1770 if (m_runTimeValues.count() > 0){
1771 vals = m_runTimeValues.takeFirst();
1772
1773 emit setCurrentIndex(vals.getSequenceNumber());
1774 fixedTimeMove(vals);
1775 m_runTimeTimer.start(vals.getTiming() * 1000);
1776
1778 }
1779
1780}
1781
1782void PartItem::onRunTimerTimeout()
1783{
1784 if (m_runTimeValues.count() > 0){
1785 SequenceItem vals = m_runTimeValues.takeFirst();
1786 if(vals.getTiming() < 0){
1788 return;
1789 }
1790 emit setCurrentIndex(vals.getSequenceNumber());
1791 fixedTimeMove(vals);
1792 m_runTimeTimer.start(vals.getTiming() * 1000);
1793 }else{
1795 }
1796}
1797
1798void PartItem::fixedTimeMove(SequenceItem sequence)
1799{
1800 int NUM_JOINTS;
1801 m_iPos->getAxes(&NUM_JOINTS);
1802 auto* cmdPositions = new double[NUM_JOINTS];
1803 auto* cmdVelocities = new double[NUM_JOINTS];
1804 auto* startPositions = new double[NUM_JOINTS];
1805 double cmdTime = sequence.getTiming();
1806
1807 while (!m_iencs->getEncoders(startPositions)){
1809 }
1810
1811
1812 for(int k=0; k<NUM_JOINTS; k++){
1813 cmdVelocities[k] = 0;
1814 cmdPositions[k] = sequence.getPositions().at(k);
1815
1816 if (fabs(startPositions[k] - cmdPositions[k]) > 0.01){
1818 } else {
1819 cmdVelocities[k] = 1.0;
1820 }
1821 }
1822
1823 m_iPos->setRefSpeeds(cmdVelocities);
1824 m_iPos->positionMove(cmdPositions);
1825
1826 m_sequence_port_stamp.update();
1827 m_sequence_port.setEnvelope(m_sequence_port_stamp);
1829 m_sequence_port.write(v);
1830 delete[] cmdVelocities;
1831 delete[] startPositions;
1832 delete[] cmdPositions;
1833 return;
1834}
1835
1836void PartItem::onGo(SequenceItem sequenceItem)
1837{
1838 if(sequenceItem.getPositions().isEmpty() || sequenceItem.getSpeeds().isEmpty())
1839 {
1840 QMessageBox::critical(this,"Error", "Select an entry in the table before performing a movement");
1841 return;
1842 }
1843
1844 int NUMBER_OF_JOINTS;
1845 m_iPos->getAxes(&NUMBER_OF_JOINTS);
1846
1847 for(int i=0;i<NUMBER_OF_JOINTS;i++)
1848 {
1849 m_iPos->setRefSpeed(i, sequenceItem.getSpeeds().at(i));
1850 m_iPos->positionMove(i, sequenceItem.getPositions().at(i));
1851 }
1852}
1853
1854void PartItem::onSequenceActivated()
1855{
1856 for (int i = 0; i<m_layout->count(); i++)
1857 {
1858 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1859 if(joint){
1860 joint->sequenceActivated();
1861 }
1862 }
1863
1865
1866}
1867
1868void PartItem::onSequenceStopped()
1869{
1870 for (int i = 0; i<m_layout->count(); i++)
1871 {
1872 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1873 if(joint){
1874 joint->sequenceStopped();
1875 }
1876 }
1878}
1879
1880void PartItem::onSequenceWindowDoubleClicked(int sequenceNum)
1881{
1883 QList<double>speeds;
1884 for (int i = 0; i<m_layout->count(); i++)
1885 {
1886 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1887 values.append(this->m_positions[i]);
1888 speeds.append(joint->getTrajectoryVelocityValue());
1889 }
1890
1892}
1893
1895{
1896 for (int i = 0; i<m_layout->count(); i++)
1897 {
1898 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1899 joint->enableControlVelocity(control);
1900 }
1901}
1902
1904{
1905 for (int i = 0; i<m_layout->count(); i++)
1906 {
1907 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1908 joint->enableControlMixed(control);
1909 }
1910}
1911
1913{
1914 for (int i = 0; i<m_layout->count(); i++)
1915 {
1916 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1917 joint->enableControlPositionDirect(control);
1918 }
1919}
1920
1922{
1923 for (int i = 0; i<m_layout->count(); i++)
1924 {
1925 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1926 joint->enableControlPWM(control);
1927 }
1928}
1929
1931{
1932 for (int i = 0; i<m_layout->count(); i++)
1933 {
1934 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1935 joint->enableControlCurrent(control);
1936 }
1937}
1938
1940{
1941 for (int i = 0; i<m_layout->count(); i++)
1942 {
1943 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1944 joint->enableControlTorque(control);
1945 }
1946}
1947
1949{
1950 m_part_speedVisible = view;
1951 for (int i = 0; i<m_layout->count(); i++)
1952 {
1953 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1954 joint->setSpeedVisible(view);
1955 }
1956}
1957
1959{
1960 m_part_motorPositionVisible = view;
1961 for (int i = 0; i<m_layout->count(); i++)
1962 {
1963 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1964 joint->setMotorPositionVisible(view);
1965 }
1966}
1967
1969{
1970 m_part_dutyVisible = view;
1971 for (int i = 0; i<m_layout->count(); i++)
1972 {
1973 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1974 joint->setDutyVisible(view);
1975 }
1976}
1977
1979{
1980 m_part_currentVisible = view;
1981 for (int i = 0; i<m_layout->count(); i++)
1982 {
1983 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1984 joint->setCurrentsVisible(view);
1985 }
1986}
1987
1989{
1990 for (int i = 0; i<m_layout->count(); i++)
1991 {
1992 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
1993 joint->viewPositionTargetBox(ena);
1994 }
1995}
1996
1998{
1999 for (int i = 0; i < m_layout->count(); i++)
2000 {
2001 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
2002 joint->viewPositionTargetValue(ena);
2003 }
2004}
2005
2006void PartItem::onSetPosSliderOptionPI(int mode, double step, int numOfDec)
2007{
2008 for (int i = 0; i<m_layout->count(); i++)
2009 {
2010 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
2011 if (mode==0)
2012 {
2013 joint->enablePositionSliderDoubleAuto();
2014 }
2015 else if(mode ==1)
2016 {
2017 joint->enablePositionSliderDoubleValue(step);
2018 }
2019 else if (mode == 2)
2020 {
2021 joint->enablePositionSliderDoubleValue(1.0);
2022 }
2023 else
2024 {
2025 joint->disablePositionSliderDouble();
2026 }
2027 joint->setNumberOfPositionSliderDecimals(numOfDec);
2028 }
2029}
2030void PartItem::onSetVelSliderOptionPI(int mode, double step)
2031{
2032 for (int i = 0; i<m_layout->count(); i++)
2033 {
2034 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
2035 if (mode == 0)
2036 {
2037 joint->enableVelocitySliderDoubleAuto();
2038 joint->enableTrajectoryVelocitySliderDoubleAuto();
2039 }
2040 else if (mode == 1)
2041 {
2042 joint->enableVelocitySliderDoubleValue(step);
2043 joint->enableTrajectoryVelocitySliderDoubleValue(step);
2044 }
2045 else if (mode == 2)
2046 {
2047 joint->enableVelocitySliderDoubleValue(1.0);
2048 joint->enableTrajectoryVelocitySliderDoubleValue(1.0);
2049 }
2050 else
2051 {
2052 joint->disableVelocitySliderDouble();
2053 joint->disableTrajectoryVelocitySliderDouble();
2054 }
2055 }
2056}
2057
2058void PartItem::onSetCurSliderOptionPI(int mode, double step)
2059{
2060 for (int i = 0; i<m_layout->count(); i++)
2061 {
2062 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
2063 if (mode == 0)
2064 {
2065 joint->enableCurrentSliderDoubleAuto();
2066 }
2067 else if (mode == 1)
2068 {
2069 joint->enableCurrentSliderDoubleValue(step);
2070 }
2071 else if (mode == 2)
2072 {
2073 joint->enableCurrentSliderDoubleValue(1.0);
2074 }
2075 else
2076 {
2077 joint->disableCurrentSliderDouble();
2078 }
2079 }
2080}
2081
2082void PartItem::onSetTrqSliderOptionPI(int mode, double step)
2083{
2084 for (int i = 0; i<m_layout->count(); i++)
2085 {
2086 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
2087 if (mode == 0)
2088 {
2089 joint->enableTorqueSliderDoubleAuto();
2090 }
2091 else if(mode == 1)
2092 {
2093 joint->enableTorqueSliderDoubleValue(step);
2094 }
2095 else if(mode == 2)
2096 {
2097 joint->enableTorqueSliderDoubleValue(1.0);
2098 }
2099 else
2100 {
2101 joint->disableTorqueSliderDouble();
2102 }
2103 }
2104}
2105
2107{
2108 return m_modesList;
2109}
2110
2112{
2113 bool ret = m_ictrlmode->getControlModes(m_controlModes.data());
2114
2115
2116 if(ret==false){
2117 LOG_ERROR("ictrl->getControlMode failed on %s\n", getPartName().toStdString().c_str());
2118 }
2119
2120 m_modesList.resize(m_layout->count());
2121 for (int k = 0; k < m_layout->count(); k++){
2122 switch (m_controlModes[k])
2123 {
2124 case VOCAB_CM_IDLE:
2125 m_modesList[k] = JointItem::Idle;
2126 break;
2127 case VOCAB_CM_POSITION:
2128 m_modesList[k] = JointItem::Position;
2129 break;
2131 m_modesList[k] = JointItem::PositionDirect;
2132 break;
2133 case VOCAB_CM_MIXED:
2134 m_modesList[k] = JointItem::Mixed;
2135 break;
2136 case VOCAB_CM_VELOCITY:
2137 m_modesList[k] = JointItem::Velocity;
2138 break;
2139 case VOCAB_CM_TORQUE:
2140 m_modesList[k] = JointItem::Torque;
2141 break;
2142 case VOCAB_CM_PWM:
2143 m_modesList[k] = JointItem::Pwm;
2144 break;
2145 case VOCAB_CM_CURRENT:
2146 m_modesList[k] = JointItem::Current;
2147 break;
2148 case VOCAB_CM_HW_FAULT:
2149 m_modesList[k] = JointItem::HwFault;
2150 break;
2152 m_modesList[k] = JointItem::Calibrating;
2153 break;
2155 m_modesList[k] = JointItem::CalibDone;
2156 break;
2158 m_modesList[k] = JointItem::NotConfigured;
2159 break;
2161 m_modesList[k] = JointItem::Configured;
2162 break;
2163 default:
2164 case VOCAB_CM_UNKNOWN:
2165 m_modesList[k] = JointItem::Unknown;
2166 break;
2167 }
2168 }
2169}
2170
2172{
2173 bool ret = false;
2174 int number_of_joints=0;
2175 m_iPos->getAxes(&number_of_joints);
2176 if (m_slow_k >= number_of_joints - 1) {
2177 m_slow_k = 0;
2178 } else {
2179 m_slow_k++;
2180 }
2181
2182 if (number_of_joints == 0)
2183 {
2184 LOG_ERROR("Lost connection with the robot. You should save and restart.\n" );
2186
2187 for (int i = 0; i<m_layout->count(); i++){
2188 auto* joint = (JointItem*)m_layout->itemAt(i)->widget();
2189 joint->setJointState(JointItem::Disconnected);
2190 }
2191 return false;
2192 }
2193
2194 // *** update measured encoders, velocity, torques ***
2195 bool b = true;
2196 if (true)
2197 {
2198 b = m_iencs->getEncoders(m_positions.data());
2199 if (!b) { yWarning("Unable to update encoders"); return false; }
2200 }
2201 if (true)
2202 {
2203 b = m_iTrq->getTorques(m_torques.data());
2204 if (!b) { yWarning("Unable to update torques"); }
2205 }
2206 if (this->m_part_currentVisible)
2207 {
2208 b = m_iCur->getCurrents(m_currents.data());
2209 if (!b) { yWarning("Unable to update currents"); }
2210 }
2211 if (this->m_part_speedVisible)
2212 {
2213 b = m_iencs->getEncoderSpeeds(m_speeds.data());
2214 if (!b) { yWarning("Unable to update speeds"); }
2215 }
2216 if (this->m_part_motorPositionVisible)
2217 {
2218 b = m_iMot->getMotorEncoders(m_motorPositions.data());
2219 if (!b) { yWarning("Unable to update motorPositions"); }
2220 }
2221 if (this->m_part_dutyVisible)
2222 {
2223 b = m_iPWM->getDutyCycles(m_dutyCycles.data());
2224 if (!b) { yWarning("Unable to update dutyCycles"); }
2225 }
2226
2227 // *** update checkMotionDone, refTorque, refTrajectorySpeed, refSpeed ***
2228 // (only one at a time in order to save bandwidth)
2229 bool boolval = true;
2230 bool b_motdone = m_iPos->checkMotionDone(m_slow_k, &boolval); //using k to save bandwidth
2231 m_done[m_slow_k] = boolval;
2232 bool b_refTrq = m_iTrq->getRefTorque(m_slow_k, &m_refTorques[m_slow_k]); //using k to save bandwidth
2233 bool b_refPosSpeed = m_iPos->getRefSpeed(m_slow_k, &m_refTrajectorySpeeds[m_slow_k]); //using k to save bandwidth
2234 bool b_refVel = m_iVel->getRefVelocity(m_slow_k, &m_refVelocitySpeeds[m_slow_k]); //this interface is missing!
2235 bool b_refPos = m_iPos->getTargetPosition(m_slow_k, &m_refTrajectoryPositions[m_slow_k]);
2236
2237 if (!b_refPos)
2238 {
2239 yError() << "Missing Implementation of getTargetPosition()";
2240 }
2241 if (!b_refVel)
2242 {
2243 yError() << "Missing Implementation of getRefVelocity()";
2244 }
2245 if (!b_refPosSpeed)
2246 {
2247 yError() << "Missing Implementation of getRefSpeed()";
2248 }
2249 if (!b_refTrq)
2250 {
2251 yError() << "Missing Implementation of getRefTorque()";
2252 }
2253 if (!b_motdone)
2254 {
2255 yError() << "Missing Implementation of checkMotionDone()";
2256 }
2257
2258 // *** update the widget every cycle ***
2259 for (int jk = 0; jk < number_of_joints; jk++)
2260 {
2261 auto* joint = (JointItem*)m_layout->itemAt(jk)->widget();
2262 if (true) { joint->setPosition(m_positions[jk]); }
2263 else {}
2264 if (true) { joint->setTorque(m_torques[jk]); }
2265 else {}
2266 if (true) { joint->setSpeed(m_speeds[jk]); }
2267 else {}
2268 if (true) { joint->setCurrent(m_currents[jk]); }
2269 else {}
2270 if (true) { joint->setMotorPosition(m_motorPositions[jk]); }
2271 else {}
2272 if (true) { joint->setDutyCycles(m_dutyCycles[jk]); }
2273 else {}
2274 }
2275
2276 // *** update the widget NOT every cycle ***
2277 {
2278 auto* joint_slow_k = (JointItem*)m_layout->itemAt(m_slow_k)->widget();
2279 if (b_refTrq) { joint_slow_k->setRefTorque(m_refTorques[m_slow_k]); }
2280 else {}
2281 if (b_refPosSpeed) { joint_slow_k->setRefTrajectorySpeed(m_refTrajectorySpeeds[m_slow_k]); }
2282 else {}
2283 if (b_refPos) { joint_slow_k->setRefTrajectoryPosition(m_refTrajectoryPositions[m_slow_k]); }
2284 else {}
2285 if (b_refVel) { joint_slow_k->setRefVelocitySpeed(m_refVelocitySpeeds[m_slow_k]); }
2286 else {}
2287 if (b_motdone) { joint_slow_k->updateMotionDone(m_done[m_slow_k]); }
2288 else {}
2289 }
2290
2291
2292 // *** update the controlMode, interactionMode ***
2293 // this is already done by updateControlMode() (because it also needs to update the tree, not only the single joint widget)
2294 // ret=ctrlmode2->getControlModes(controlModes);
2295 // if(ret==false){
2296 // LOG_ERROR("ictrl->getControlMode failed\n" );
2297 // }
2298 ret = m_iinteract->getInteractionModes(m_interactionModes.data());
2299 if(ret==false){
2300 LOG_ERROR("iint->getInteractionlMode failed\n" );
2301 }
2302
2303 //optional
2304 if (m_ijointfault)
2305 {
2306 for (int k = 0; k < number_of_joints; k++)
2307 {
2308 if (m_controlModes[k]==VOCAB_CM_HW_FAULT)
2309 {
2310 int fault;
2311 std::string message;
2312 if (m_ijointfault->getLastJointFault(k,fault,message))
2313 {
2314 auto* joint_slow_k = (JointItem*)m_layout->itemAt(m_slow_k)->widget();
2315 joint_slow_k->updateJointFault(fault, message);
2316 }
2317 else
2318 {
2319 LOG_ERROR("Unsuccessful call to getLastJointFault()\n");
2320 }
2321 }
2322 }
2323 }
2324
2325
2326 for (int k = 0; k < number_of_joints; k++)
2327 {
2328 auto* joint = (JointItem*)m_layout->itemAt(k)->widget();
2329 switch (m_controlModes[k])
2330 {
2331 case VOCAB_CM_IDLE:
2332 joint->setJointState(JointItem::Idle);
2333 break;
2334 case VOCAB_CM_POSITION:
2335 joint->setJointState(JointItem::Position);
2336 break;
2338 joint->setJointState(JointItem::PositionDirect);
2339 break;
2340 case VOCAB_CM_MIXED:
2341 joint->setJointState(JointItem::Mixed);
2342 break;
2343 case VOCAB_CM_VELOCITY:
2344 joint->setJointState(JointItem::Velocity);
2345 break;
2346 case VOCAB_CM_TORQUE:
2347 joint->setJointState(JointItem::Torque);
2348 break;
2349 case VOCAB_CM_CURRENT:
2350 {
2351 joint->setJointState(JointItem::Current);
2352 double ref_current = 0;
2353 m_iCur->getRefCurrent(k, &ref_current);
2354 joint->setRefCurrent(ref_current);
2355 break;
2356 }
2357 case VOCAB_CM_PWM:
2358 {
2359 joint->setJointState(JointItem::Pwm);
2360 double ref_duty = 0;
2361 m_iPWM->getRefDutyCycle(k, &ref_duty);
2362 joint->setRefPWM(ref_duty);
2363 break;
2364 }
2365 case VOCAB_CM_HW_FAULT:
2366 joint->setJointState(JointItem::HwFault);
2367 break;
2369 joint->setJointState(JointItem::Calibrating);
2370 break;
2372 joint->setJointState(JointItem::CalibDone);
2373 break;
2375 joint->setJointState(JointItem::NotConfigured);
2376 break;
2378 joint->setJointState(JointItem::Configured);
2379 break;
2380 default:
2381 case VOCAB_CM_UNKNOWN:
2382 joint->setJointState(JointItem::Unknown);
2383 break;
2384 }
2385 switch (m_interactionModes[k])
2386 {
2387 case VOCAB_IM_STIFF:
2388 joint->setJointInteraction(JointItem::Stiff);
2389 break;
2390 case VOCAB_IM_COMPLIANT:
2391 joint->setJointInteraction(JointItem::Compliant);
2392 break;
2393 default:
2394 case VOCAB_IM_UNKNOWN:
2395 //joint->setJointInteraction(JointItem::Stiff); TODO
2396 break;
2397 }
2398 }
2399 return true;
2400}
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 onEnableControlTorque(bool control)
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:154
void initPosition(Pid myPid)
Definition piddlg.cpp:124
void initTorque(Pid myPid, MotorTorqueParameters TorqueParam)
Definition piddlg.cpp:184
void initTorqueOffset(double curForceVal, double minForce, double maxForce)
Definition piddlg.cpp:344
void initCurrent(Pid myPid)
Definition piddlg.cpp:362
void initStiffness(double curStiffVal, double minStiff, double maxStiff, double curDampVal, double minDamp, double maxDamp)
Definition piddlg.cpp:330
void initRemoteVariables(IRemoteVariables *iVar)
Definition piddlg.cpp:264
void initPWM(double pwmVal, double pwm)
Definition piddlg.cpp:354
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 setImpedanceOffset(int j, double offset)=0
Set 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