iCub-main
Loading...
Searching...
No Matches
embObjMotionControl.cpp
Go to the documentation of this file.
1// -*- Mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
2
3/*
4* Copyright (C) 2012 iCub Facility, Istituto Italiano di Tecnologia
5* Authors: Alberto Cardellino, Valentina Gaggero
6* CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
7*
8*/
9
10// system std include
11#include <string.h>
12#include <iostream>
13#include <cmath>
14#include <algorithm>
15
16// yarp include
17#include <yarp/os/Bottle.h>
18#include <yarp/os/Time.h>
19#include <yarp/conf/environment.h>
20#include <yarp/os/LogStream.h>
21#include <yarp/os/NetType.h>
22#include <yarp/os/Vocab32.h>
23#include <yarp/dev/ControlBoardHelper.h>
24#include <yarp/dev/ReturnValue.h>
25
26// local include
27#include "EoCommon.h"
28#include "EOarray.h"
29#include "EoProtocol.h"
30#include "EoProtocolMN.h"
31#include "EoProtocolMC.h"
32#include "EoProtocolAS.h"
33#include "embObjMotionControlDefaults.h" // include the header with default values
34#include "eomcUtils.h"
35#include "embObjMotionControl.h"
36#include "FeatureInterface.h"
37
38using namespace yarp::dev;
39using namespace yarp::os;
40using namespace yarp::os::impl;
41using namespace yarp::dev::eomc;
42
43
44// macros
45#define ASK_REFERENCE_TO_FIRMWARE 1
47
48static bool isUnsupportedPidAlias(PidControlTypeEnum pidtype)
49{
50 switch (pidtype)
51 {
52 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION_2:
53 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION_3:
54 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY_2:
55 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY_3:
56 case PidControlTypeEnum::VOCAB_PIDTYPE_TORQUE_2:
57 case PidControlTypeEnum::VOCAB_PIDTYPE_TORQUE_3:
58 case PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT_2:
59 case PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT_3:
60 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION_DIRECT_2:
61 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION_DIRECT_3:
62 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY_DIRECT_2:
63 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY_DIRECT_3:
64 case PidControlTypeEnum::VOCAB_PIDTYPE_MIXED_2:
65 case PidControlTypeEnum::VOCAB_PIDTYPE_MIXED_3:
66 return true;
67 default:
68 return false;
69 }
70}
71
72std::string embObjMotionControl::getBoardInfo(void) const
73{
74 if(nullptr == _ethRes)
75 {
76 return " BOARD name_unknown (IP unknown) ";
77 }
78 else
79 {
80 return ("BOARD " + _ethRes->getProperties().boardnameString + " (IP " + _ethRes->getProperties().ipv4addrString + ") ");
81 }
82}
83
84
85bool embObjMotionControl::alloc(int nj)
86{
87 _encodersStamp.resize(nj, 0);
88
89 _parsedCfgData.resize(nj);
90
91 _last_position_move_time.resize(nj, 0);
92
93 // Reserve space for data stored locally. values are initialize to 0
94 _ref_command_positions.resize(nj, 0);
95 _ref_positions.resize(nj, 0);
96 _ref_command_speeds.resize(nj, 0);
97 _ref_speeds.resize(nj, 0);
98 _ref_accs.resize(nj, 0);
99
100 _cacheImpedance.resize(nj, {});
101
102 _parsedCfgData.rotorsLimits.resize(nj);
103 _parsedCfgData.jointsLimits.resize(nj);
104 _parsedCfgData.currentLimits.resize(nj);
105 _parsedCfgData.temperatureLimits.resize(nj);
106 _parsedCfgData.jsets.resize(nj);
107 _parsedCfgData.joint2set.resize(nj);
108 _parsedCfgData.timeouts.resize(nj);
109 _parsedCfgData.impedance_params.resize(nj);
110 _parsedCfgData.lugre_params.resize(nj);
111 _parsedCfgData.axesInfo.resize(nj);
112 _parsedCfgData.jointEncs.resize(nj);
113 _parsedCfgData.motorEncs.resize(nj);
114 _parsedCfgData.kalman_params.resize(nj);
115 _parsedCfgData.temperatureSensorsVector.resize(nj);
116 _temperatureExceededLimitWatchdog.resize(nj);
117 _temperatureSensorErrorWatchdog.resize(nj);
118 _temperatureSpikesFilter.resize(nj);
119
120 // update threshold for watchdog parametrized on the ROP transmission rate (by default is 2ms)
121 uint8_t txrate = _ethRes->getProperties().txROPratedivider;
122 for(int i = 0; i < nj; ++i)
123 {
124 _temperatureExceededLimitWatchdog.at(i).setThreshold(txrate);
125 _temperatureSensorErrorWatchdog.at(i).setThreshold(txrate);
126 }
127
128 return true;
129}
130
131
133 ImplementControlCalibration(this),
134 ImplementAmplifierControl(this),
135 ImplementPidControl(this),
136 ImplementEncodersTimed(this),
137 ImplementPositionControl(this),
138 ImplementVelocityControl(this),
139 ImplementVelocityDirect(this),
140 ImplementControlMode(this),
141 ImplementImpedanceControl(this),
142 ImplementMotorEncoders(this),
143#ifdef IMPLEMENT_DEBUG_INTERFACE
145#endif
146 ImplementTorqueControl(this),
147 ImplementControlLimits(this),
148 ImplementPositionDirect(this),
149 ImplementInteractionMode(this),
150 ImplementMotor(this),
151 ImplementRemoteVariables(this),
152 ImplementAxisInfo(this),
153 ImplementPWMControl(this),
154 ImplementCurrentControl(this),
155 ImplementJointFault(this),
156 ImplementJointBrake(this),
157 _temperatureExceededLimitWatchdog(0),
158 _temperatureSensorErrorWatchdog(0),
159 _temperatureSpikesFilter(0),
160 _rawDataAuxVector(0),
161 _rawValuesMetadataMap({})
162{
163 _opened = 0;
164 _ethRes = NULL;
165 _njoints = 0;
166 _measureConverter = NULL;
167
168
169 // debug connection
170 //tot_packet_recv = 0;
171 //errors = 0;
172 //start = 0;
173 //end = 0;
174
175 // Check status of joints
176
177 _parsedCfgData.behFlags.useRawEncoderData = false;
178 _parsedCfgData.behFlags.pwmIsLimited = false;
179
180 _parsedCfgData.maintenanceModeCfg.enableSkipRecalibration = false;
181
182 std::string tmp = yarp::conf::environment::get_string("ETH_VERBOSEWHENOK");
183 if (tmp != "")
184 {
185 _parsedCfgData.behFlags.verbosewhenok = (bool)yarp::conf::numeric::from_string(tmp, 0U);
186 }
187 else
188 {
189 _parsedCfgData.behFlags.verbosewhenok = false;
190 }
191 _srvParser = NULL;
192 _mcparser = NULL;
193
194#ifdef NETWORK_PERFORMANCE_BENCHMARK
195 /* We would like to verify if the round trimp of request and answer from embedded board is about 3 milliseconds, with a tollerance 0f 0.250 milliseconds.
196 The _responseTimingVerifier object, after 3 seconds, prints an istogram with values from 1 to 10 millisec with a step of 0.5 millisec
197 */
198 _responseTimingVerifier.init(0.003, 0.00025, 0.001, 0.01, 0.0005, 30);
199#endif
200
201}
202
203
205{
206 yTrace() << "embObjMotionControl::~embObjMotionControl()";
207
208 if(NULL != _srvParser)
209 {
210 delete _srvParser;
211 _srvParser = NULL;
212 }
213
214 if(NULL != _mcparser)
215 {
216 delete _mcparser;
217 _mcparser = NULL;
218 }
219}
220
221
223{
224 return _opened;
225}
226
227bool embObjMotionControl::initializeInterfaces(measureConvFactors &f)
228{
229
230 ImplementControlCalibration::initialize(_njoints, _parsedCfgData.axisMap.data(), f.angleToEncoder.data(), NULL);
231 ImplementAmplifierControl::initialize(_njoints, _parsedCfgData.axisMap.data(), f.angleToEncoder.data(), NULL, f.ampsToSensor.data());
232 ImplementEncodersTimed::initialize(_njoints, _parsedCfgData.axisMap.data(), f.angleToEncoder.data(), NULL);
233 ImplementMotorEncoders::initialize(_njoints, _parsedCfgData.axisMap.data(), f.angleToEncoder.data(), NULL);
234 ImplementPositionControl::initialize(_njoints, _parsedCfgData.axisMap.data(), f.angleToEncoder.data(), NULL);
235 ImplementPidControl::initialize(_njoints, _parsedCfgData.axisMap.data(), f.angleToEncoder.data(), NULL, f.newtonsToSensor.data(), f.ampsToSensor.data(), f.dutycycleToPWM.data());
236 ImplementControlMode::initialize(_njoints, _parsedCfgData.axisMap.data());
237 ImplementVelocityControl::initialize(_njoints, _parsedCfgData.axisMap.data(), f.angleToEncoder.data(), NULL);
238 ImplementVelocityDirect::initialize(_njoints, _parsedCfgData.axisMap.data(), f.angleToEncoder.data(), NULL);
239 ImplementControlLimits::initialize(_njoints, _parsedCfgData.axisMap.data(), f.angleToEncoder.data(), NULL);
240 ImplementImpedanceControl::initialize(_njoints, _parsedCfgData.axisMap.data(), f.angleToEncoder.data(), NULL, f.newtonsToSensor.data());
241 ImplementTorqueControl::initialize(_njoints, _parsedCfgData.axisMap.data(), f.angleToEncoder.data(), NULL, f.newtonsToSensor.data(), f.ampsToSensor.data(), f.dutycycleToPWM.data(), f.bemf2raw.data(), f.ktau2raw.data());
242 ImplementPositionDirect::initialize(_njoints, _parsedCfgData.axisMap.data(), f.angleToEncoder.data(), NULL);
243 ImplementInteractionMode::initialize(_njoints, _parsedCfgData.axisMap.data(), f.angleToEncoder.data(), NULL);
244 ImplementMotor::initialize(_njoints, _parsedCfgData.axisMap.data());
245 ImplementRemoteVariables::initialize(_njoints, _parsedCfgData.axisMap.data());
246 ImplementAxisInfo::initialize(_njoints, _parsedCfgData.axisMap.data());
247 ImplementCurrentControl::initialize(_njoints, _parsedCfgData.axisMap.data(), f.ampsToSensor.data());
248 ImplementPWMControl::initialize(_njoints, _parsedCfgData.axisMap.data(), f.dutycycleToPWM.data());
249 ImplementJointFault::initialize(_njoints, _parsedCfgData.axisMap.data());
250 ImplementJointBrake::initialize(_njoints, _parsedCfgData.axisMap.data());
251 return true;
252
253}
254
255bool embObjMotionControl::open(yarp::os::Searchable &config)
256{
257 // - first thing to do is verify if the eth manager is available. then i parse info about the eth board.
258
259 _ethManager = eth::TheEthManager::instance();
260 if(NULL == _ethManager)
261 {
262 yFatal() << "embObjMotionControl::open() fails to instantiate _ethManager";
263 return false;
264 }
265
266 eOipv4addr_t ipv4addr;
267 string boardIPstring;
268 string boardName;
269 if(false == _ethManager->verifyEthBoardInfo(config, ipv4addr, boardIPstring, boardName))
270 {
271 yError() << "embObjMotionControl::open(): object TheEthManager fails in parsing ETH propertiex from xml file";
272 return false;
273 }
274 // add specific info about this device ...
275
276 if(false == eth::parser::read(config, _bdata))
277 {
278 yError() << getBoardInfo() << "embObjMotionControl::open(): eth::parser fails to read board configuration data from xml file";
279 return false;
280 }
281
282 if(NULL == _srvParser)
283 {
284 _srvParser = new ServiceParser;
285 }
286
287
288 // - now all other things
289
290 // -- instantiate EthResource etc.
291
292 _ethRes = _ethManager->requestResource2(this, config);
293 if(NULL == _ethRes)
294 {
295 yError() << "embObjMotionControl::open() fails because could not instantiate the ethResource for " << getBoardInfo() << " ... unable to continue";
296 return false;
297 }
298 // READ CONFIGURATION
299 if(!fromConfig(config))
300 {
301 yError() << getBoardInfo() << "Missing motion control parameters in config file";
302 return false;
303 }
304
305 if(!_ethRes->verifyEPprotocol(eoprot_endpoint_motioncontrol))
306 {
307 yError() << "embObjMotionControl: failed verifyEPprotocol. Cannot continue!";
308 cleanup();
309 return false;
310 }
311
312
313 const eOmn_serv_parameter_t* servparam = &_parsedCfgData.serviceConfig.ethservice;
314 if(eomn_serv_MC_generic == _parsedCfgData.serviceConfig.ethservice.configuration.type)
315 {
316 servparam = NULL;
317 }
318
319 // in here ...we open ports where to print AMO data
320 _mcdiagnostics.config.mode = _parsedCfgData.serviceConfig.ethservice.configuration.diagnosticsmode;
321 _mcdiagnostics.config.par16 = _parsedCfgData.serviceConfig.ethservice.configuration.diagnosticsparam;
322 if(eomn_serv_diagn_mode_MC_AMOyarp == _mcdiagnostics.config.mode)
323 {
324 // prepare the ports
325 _mcdiagnostics.ports.resize(2);
326 for(size_t i=0; i<_mcdiagnostics.ports.size(); i++)
327 {
328 _mcdiagnostics.ports[i] = new BufferedPort<Bottle>;
329 _mcdiagnostics.ports[i]->open("/amo/" + _ethRes->getProperties().boardnameString + "/j" + std::to_string(i));
330 }
331 }
332
333 // Initialize the downsampler timer
334
335 _event_downsampler = new mced::mcEventDownsampler();
336 _event_downsampler->config.period = 0.01;
337 _event_downsampler->config.threshold = 5;
338 _event_downsampler->config.subcomponent = "[mc.skipped-cmd-wrong-mode]";
339 _event_downsampler->config.info = getBoardInfo();
340 _event_downsampler->start();
341
342 if(false == _ethRes->serviceVerifyActivate(eomn_serv_category_mc, servparam))
343 {
344 yError() << "embObjMotionControl::open() has an error in call of ethResources::serviceVerifyActivate() for" << getBoardInfo();
345 cleanup();
346 return false;
347 }
348
349 yDebug() << "embObjMotionControl:serviceVerifyActivate OK!";
350
351
352 if(!init() )
353 {
354 yError() << "embObjMotionControl::open() has an error in call of embObjMotionControl::init() for" << getBoardInfo();
355 return false;
356 }
357 else
358 {
359 if(_parsedCfgData.behFlags.verbosewhenok)
360 {
361 yDebug() << "embObjMotionControl::init() has succesfully initted" << getBoardInfo();
362 }
363 }
364
365
366 if(false == _ethRes->serviceStart(eomn_serv_category_mc))
367 {
368 yError() << "embObjMotionControl::open() fails to start mc service for" << getBoardInfo() << ": cannot continue";
369 cleanup();
370 return false;
371 }
372 else
373 {
374 if(_parsedCfgData.behFlags.verbosewhenok)
375 {
376 yDebug() << "embObjMotionControl::open() correctly starts mc service of" << getBoardInfo();
377 }
378 }
379
380
381 _opened = true;
382
383
384 if(eomn_serv_diagn_mode_MC_AMOyarp == _mcdiagnostics.config.mode)
385 {
386 // marco.accame on 10 june 2011.
387 // in here we wait some time so that yarprobotinterface may receive amo streaming before any
388 // further module (e.g., the calibrator) sends an active control mode and starts moving the motor.
389 //
390 // how does it work?
391 //
392 // when the ETH board receives command from _ethRes->serviceStart() it enters the control loop and it
393 // waits for a non IDLE control mode etc. but it also starts streaming AMO data. It is the thread
394 // inside EthReceiver whuch process UDP pckets, so a wait inside this current thread will do the job.
395 //
396 // moreover, if _mcdiagnostics.config.par16 is > 0, then we also have a mechanism such that the AMO
397 // are streamed in a conditio of the motor not initiaized yet. in such way we can observe what is
398 // the effect of the configuration of the motor on the AMO reading.
399 //
400 // how does it work?
401 //
402 // it is the function embObjMotionControl::init() which configures the motors by sending messages
403 // with tag eoprot_tag_mc_joint_config.
404 // the ETH board, if it sees eomn_serv_diagn_mode_MC_AMOyarp and par16 > 0, it applies the config of
405 // the motor with a delay of _mcdiagnostics.config.par16 milliseconds. so, in here if we wait
406 // the same amount of time, we:
407 // - can read amo values with the motors off,
408 // - we are sure that no other module (e.g., the calibrator) will attempt to move a motor which is
409 // not yet configured.
410 // I KNOW: IT WOULD BE MUCH BETTER to wait in here until the ETH board tells us that it has configured
411 // the motor (rather then just applying a delay and hoping the ETH boards works fine). but that would
412 // require some effort which for now i prefer to postpone because "l'ottimo e' il nemico del bene"
413 // and we need a quick solution to test icub3.
414
415 SystemClock::delaySystem(0.001*_mcdiagnostics.config.par16);
416 }
417
418 return true;
419}
420
421
422int embObjMotionControl::fromConfig_NumOfJoints(yarp::os::Searchable &config)
423{
424 //
425 // Read Configuration params from file
426 //
427 int jn = config.findGroup("GENERAL").check("Joints", Value(1), "Number of degrees of freedom").asInt32();
428
429 return(jn);
430}
431
432
433
434void embObjMotionControl::debugUtil_printJointsetInfo(void)
435{
436
437 yError() << "****** DEBUG PRINTS **********";
438 yError() << "joint to set:";
439 for(int x=0; x< _njoints; x++)
440 yError() << " /t j " << x << ": set " <<_parsedCfgData.joint2set[x];
441 yError() << "jointmap:";
442
443 yError() << " number of sets" << _parsedCfgData.jsets.size();
444 for(size_t x=0; x< _parsedCfgData.jsets.size(); x++)
445 {
446 yError() << "set " << x<< "has size " <<_parsedCfgData.jsets[x].getNumberofJoints();
447 for(int y=0; y<_parsedCfgData.jsets[x].getNumberofJoints(); y++)
448 yError() << "set " << x << ": " << _parsedCfgData.jsets[x].joints[y];
449 }
450 yError() << "********* END ****************";
451
452}
453
454void embObjMotionControl::debugUtil_printPidInfoByJointSet(void)
455{
456 auto outTypeToString = [](eOmc_ctrl_out_type_t e) -> std::string
457 {
458 switch(e)
459 {
460 case eomc_ctrl_out_type_n_a: return "n_a";
461 case eomc_ctrl_out_type_pwm: return "pwm";
462 case eomc_ctrl_out_type_cur: return "current";
463 case eomc_ctrl_out_type_vel_cur: return "vel_cur";
464 case eomc_ctrl_out_type_vel_pwm: return "vel_pwm";
465 default: return "unknown";
466 }
467 };
468
469 auto printPidBase = [&](const std::string& tag, int joint, const eomc::PidInfo& p)
470 {
471 yInfo() << "embObjMC" << getBoardInfo() << "[PID DEBUG]" << tag.c_str()
472 << "joint" << joint
473 << "enabled" << p.enabled
474 << "group" << p.usernamePidSelected.c_str()
475 << "controlLaw" << p.controlLaw.c_str()
476 << "outType" << outTypeToString(p.out_type).c_str()
477 << "kp" << p.pid.kp
478 << "ki" << p.pid.ki
479 << "kd" << p.pid.kd
480 << "kff" << p.pid.kff
481 << "maxOut" << p.pid.max_output
482 << "maxInt" << p.pid.max_int
483 << "scale" << p.pid.scale;
484 };
485
486 auto printPidTorque = [&](int joint, const eomc::TrqPidInfo& p)
487 {
488 printPidBase("trq", joint, p);
489 yInfo() << "embObjMC" << getBoardInfo() << "[PID DEBUG]"
490 << "trq-extra"
491 << "joint" << joint
492 << "ktau" << p.ktau
493 << "viscousPos" << p.viscousPos
494 << "viscousNeg" << p.viscousNeg
495 << "coulombPos" << p.coulombPos
496 << "coulombNeg" << p.coulombNeg
497 << "velThres" << p.velocityThres
498 << "filterType" << p.filterType;
499 };
500
501 yInfo() << "embObjMC" << getBoardInfo() << "[PID DEBUG] begin dump by jointset";
502 for(size_t s = 0; s < _parsedCfgData.jsets.size(); s++)
503 {
504 const int numofjoints = _parsedCfgData.jsets[s].getNumberofJoints();
505 yInfo() << "embObjMC" << getBoardInfo() << "[PID DEBUG] set" << s << "jointsInSet" << numofjoints;
506
507 for(int k = 0; k < numofjoints; k++)
508 {
509 const int joint = _parsedCfgData.jsets[s].joints[k];
510 if((joint < 0) || (joint >= _njoints))
511 {
512 yWarning() << "embObjMC" << getBoardInfo() << "[PID DEBUG] invalid joint index" << joint << "in set" << s;
513 continue;
514 }
515
516 printPidBase("trj", joint, _parsedCfgData.pidControllers.trj[joint]);
517 printPidBase("vel", joint, _parsedCfgData.pidControllers.vel[joint]);
518 printPidBase("mix", joint, _parsedCfgData.pidControllers.mix[joint]);
519 printPidBase("dir_pos", joint, _parsedCfgData.pidControllers.dir_pos[joint]);
520 printPidBase("dir_vel", joint, _parsedCfgData.pidControllers.dir_vel[joint]);
521 printPidBase("cur", joint, _parsedCfgData.pidControllers.cur[joint]);
522 printPidTorque(joint, _parsedCfgData.pidControllers.trq[joint]);
523 }
524 }
525 yInfo() << "embObjMC" << getBoardInfo() << "[PID DEBUG] end dump by jointset";
526}
527
528
529
530//TODO: shell we remove this function and the one below and put the verification of the consistency of the control law in the configuration phase, i.e. in fromConfig()?
531bool embObjMotionControl::verifyUserControlLawConsistencyInJointSet(eomc::PidInfo *pidInfo)
532{
533
534 for(size_t s=0; s<_parsedCfgData.jsets.size(); s++)
535 {
536 int numofjoints = _parsedCfgData.jsets[s].getNumberofJoints();
537
538 if(numofjoints== 0 )
539 {
540 yError() << "embObjMC" << getBoardInfo() << "Jointsset " << s << "hasn't joints!!! I should be never stay here!!!";
541 return false;
542 }
543 int firstjoint = _parsedCfgData.jsets[s].joints[0];//get firts joint of set s
544
545 for(int k=1; k<numofjoints; k++)
546 {
547 int otherjoint = _parsedCfgData.jsets[s].joints[k];
548
549 if(pidInfo[firstjoint].usernamePidSelected != pidInfo[otherjoint].usernamePidSelected)
550 {
551 yError() << "embObjMC "<< getBoardInfo() << "Joints beloning to same set must be have same control law. Joint " << otherjoint << " differs from " << firstjoint << "Set num " << s ;
552 yError() << pidInfo[firstjoint].usernamePidSelected << "***" << pidInfo[otherjoint].usernamePidSelected;
553 return false;
554 }
555 }
556 }
557 return true;
558}
559
560
561bool embObjMotionControl::verifyUserControlLawConsistencyInJointSet(eomc::TrqPidInfo *pidInfo)
562{
563 for(size_t s=0; s<_parsedCfgData.jsets.size(); s++)
564 {
565 int numofjoints = _parsedCfgData.jsets[s].getNumberofJoints();
566
567 if(numofjoints == 0 )
568 {
569 yError() << "embObjMC "<< getBoardInfo() << "Jointsset " << s << "hasn't joints!!! I should be never stay here!!!";
570 return false;
571 }
572 int firstjoint = _parsedCfgData.jsets[s].joints[0];//get firts joint of set s
573
574 for(int k=1; k<numofjoints; k++)
575 {
576 int otherjoint = _parsedCfgData.jsets[s].joints[k];
577
578 if(pidInfo[firstjoint].usernamePidSelected != pidInfo[otherjoint].usernamePidSelected)
579 {
580 yError() << "embObjMC"<< getBoardInfo() << "Joints beloning to same set must be have same control law. Joint " << otherjoint << " differs from " << firstjoint << "Set num " << s ;
581 yError() << pidInfo[firstjoint].usernamePidSelected << "***" << pidInfo[otherjoint].usernamePidSelected;
582 return false;
583 }
584 }
585 }
586 return true;
587}
588
589
590bool embObjMotionControl::updatedJointsetsCfgWithControlInfo()
591{
592
593 for(size_t s=0; s<_parsedCfgData.jsets.size(); s++)
594 {
595 if(_parsedCfgData.jsets[s].getNumberofJoints() == 0)
596 {
597 yError() << "embObjMC"<< getBoardInfo() << "Jointsset " << s << "hasn't joints!!! Error in configuration!!!";
598 return false;
599 }
600
601 int joint = _parsedCfgData.jsets[s].joints[0];
602 //eOmc_pidoutputtype_t pid_out_type = pidOutputTypeConver_eomc2fw(_trj_pids[joint].controlLaw);
603 //if(eomc_pidoutputtype_unknown == pid_out_type)
604 //{
605 // yError() << "embObjMC"<< getBoardInfo() << "pid output type is unknown for joint " << joint;
606 // return false;
607 //}
608 //_parsedCfgData.jsets[s].setPidOutputType(pid_out_type);
609 //_parsedCfgData.jsets[s].setCanDoTorqueControl(isTorqueControlEnabled(joint));
610
611 _parsedCfgData.jsets[s].cfg.pid_output_types.postrj_ctrl_out_type = _parsedCfgData.pidControllers.trj[joint].out_type;
612 _parsedCfgData.jsets[s].cfg.pid_output_types.veltrj_ctrl_out_type = _parsedCfgData.pidControllers.trj[joint].out_type;
613 _parsedCfgData.jsets[s].cfg.pid_output_types.mixtrj_ctrl_out_type = _parsedCfgData.pidControllers.trj[joint].out_type;
614 _parsedCfgData.jsets[s].cfg.pid_output_types.posdir_ctrl_out_type = _parsedCfgData.pidControllers.dir_pos[joint].out_type;
615 _parsedCfgData.jsets[s].cfg.pid_output_types.veldir_ctrl_out_type = _parsedCfgData.pidControllers.dir_vel[joint].out_type;
616 _parsedCfgData.jsets[s].cfg.pid_output_types.torque_ctrl_out_type = _parsedCfgData.pidControllers.trq[joint].out_type;
617 _parsedCfgData.jsets[s].cfg.pid_output_types.pwm_ctrl_out_type = eomc_ctrl_out_type_pwm;
618 //TODO: check if ems/2foc support the ouitctrtype on fly.
619 if (_parsedCfgData.pidControllers.cur[joint].enabled)
620 {
621 _parsedCfgData.jsets[s].cfg.pid_output_types.cur_ctrl_out_type = eomc_ctrl_out_type_cur;
622 }
623 else
624 {
625 _parsedCfgData.jsets[s].cfg.pid_output_types.cur_ctrl_out_type = eomc_ctrl_out_type_n_a;
626 }
627 }
628 return true;
629}
630
631
632
633
634bool embObjMotionControl::saveCouplingsData(void)
635{
636 eOmc_4jomo_coupling_t *jc_dest;
637
638 static eOmc_4jomo_coupling_t dummyjomocoupling = {};
639
640 switch(_parsedCfgData.serviceConfig.ethservice.configuration.type)
641 {
642 case eomn_serv_MC_foc:
643 {
644 jc_dest = &(_parsedCfgData.serviceConfig.ethservice.configuration.data.mc.foc_based.jomocoupling);
645 } break;
646
647 case eomn_serv_MC_mc4plus:
648 {
649 jc_dest = &(_parsedCfgData.serviceConfig.ethservice.configuration.data.mc.mc4plus_based.jomocoupling);
650 } break;
651
652 case eomn_serv_MC_mc4plusmais:
653 {
654 jc_dest = &(_parsedCfgData.serviceConfig.ethservice.configuration.data.mc.mc4plusmais_based.jomocoupling);
655
656 } break;
657
658 case eomn_serv_MC_mc2pluspsc:
659 {
660 jc_dest = &(_parsedCfgData.serviceConfig.ethservice.configuration.data.mc.mc2pluspsc.jomocoupling);
661
662 } break;
663
664 case eomn_serv_MC_mc4plusfaps:
665 {
666 jc_dest = &(_parsedCfgData.serviceConfig.ethservice.configuration.data.mc.mc4plusfaps.jomocoupling);
667
668 } break;
669
670 case eomn_serv_MC_advfoc:
671 {
672 jc_dest = &dummyjomocoupling;
673 } break;
674
675 case eomn_serv_MC_mc4:
676 {
677 return true;
678 } break;
679
680 case eomn_serv_MC_generic:
681 {
682 return true;
683 } break;
684
685 default:
686 {
687 return false;
688 }
689 }
690
691
692 memset(jc_dest, 0, sizeof(eOmc_4jomo_coupling_t));
693
694 //I need to initialize all elements of joint2set with "eomc_jointSetNum_none": it is used by fw to get num of setBemfParamRaw
695 //4 is teh satic dimension of joint2set. see definition of type eOmc_4jomo_coupling_t
696 for(int i=0; i<4; i++)
697 {
698 jc_dest->joint2set[i] = eomc_jointSetNum_none;
699 }
700
701 if(_parsedCfgData.joint2set.size() > 4 )
702 {
703 yError() << "embObjMC "<< getBoardInfo() << "Jointsset size is bigger than 4. I can't send jointset information to fw.";
704 return false;
705 }
706
707 for(size_t i=0; i<_parsedCfgData.joint2set.size(); i++)
708 {
709 jc_dest->joint2set[i] = _parsedCfgData.joint2set[i];
710 }
711
712 for(int i=0; i<4; i++)
713 {
714 for(int j=0; j<4; j++)
715 {
716 jc_dest->joint2motor[i][j] = eo_common_float_to_Q17_14((float)_parsedCfgData.couplingInfo.matrixJ2M[4*i+j]);
717 jc_dest->motor2joint[i][j] = eo_common_float_to_Q17_14((float)_parsedCfgData.couplingInfo.matrixM2J[4*i+j]);
718 }
719 }
720
721
722 for(int r=0; r<4; r++)
723 {
724 for(int c=0; c<6; c++)
725 {
726 jc_dest->encoder2joint[r][c] = eo_common_float_to_Q17_14((float)_parsedCfgData.couplingInfo.matrixE2J[6*r+c]);
727 }
728 }
729
730 for(size_t s=0; s< _parsedCfgData.jsets.size(); s++)
731 {
732 eOmc_jointset_configuration_t* cfg_ptr = _parsedCfgData.jsets[s].getConfiguration();
733 memcpy(&(jc_dest->jsetcfg[s]), cfg_ptr, sizeof(eOmc_jointset_configuration_t));
734 }
735
736
737 if(eomn_serv_MC_advfoc == _parsedCfgData.serviceConfig.ethservice.configuration.type)
738 {
739 // i will copy data from jc_dest to the effective destination
740 eOmc_adv4jomo_coupling_t *ajc = &_parsedCfgData.serviceConfig.ethservice.configuration.data.mc.advfoc.adv4jomocoupling;
741 ajc->type = eommccoupling_traditional4x4;
742 // i copy some fields as they are
743 std::memmove(&ajc->data.coupling4x4.joint2set[0], &jc_dest->joint2set[0], 4*sizeof(uint8_t));
744 std::memmove(&ajc->data.coupling4x4.jsetcfg[0], &jc_dest->jsetcfg[0], 4*sizeof(eOmc_jointset_configuration_t));
745 std::memmove(&ajc->data.coupling4x4.joint2motor, &jc_dest->joint2motor, sizeof(eOmc_4x4_matrix_t));
746 std::memmove(&ajc->data.coupling4x4.motor2joint, &jc_dest->motor2joint, sizeof(eOmc_4x4_matrix_t));
747 // and i will copy only 4x4 from one field
748 for(uint8_t r=0; r<4; r++)
749 {
750 for(uint8_t c=0; c<4; c++)
751 {
752 ajc->data.coupling4x4.encoder2joint4x4[r][c] = jc_dest->encoder2joint[r][c];
753 }
754 }
755 }
756
757 return true;
758
759}
760
761
762bool embObjMotionControl::fromConfig_Step2(yarp::os::Searchable &config)
763{
764 Bottle xtmp;
765 int i,j;
766
767 measureConvFactors measConvFactors (_njoints);
768
769 if(iNeedCouplingsInfo())
770 {
771
773 if(!_mcparser->parseCouplingInfo(config, _parsedCfgData.couplingInfo))
774 return false;
775
776
778 if(!_mcparser->parseJointsetCfgGroup(config, _parsedCfgData.jsets, _parsedCfgData.joint2set))
779 return false;
780
781 //debugUtil_printJointsetInfo();
782 }
783
784
786
787
788 {
789 if(!_mcparser->parseAxisInfo(config, _parsedCfgData.axisMap.data(), _parsedCfgData.axesInfo))
790 return false;
791
793 if(_parsedCfgData.behFlags.useRawEncoderData)
794 {
795 for (i = 0; i < _njoints; i++)
796 {
797 measConvFactors.angleToEncoder[i] = 1;
798 }
799 }
800 else
801 {
802 if(!_mcparser->parseEncoderFactor(config, measConvFactors.angleToEncoder.data()))
803 return false;
804 }
805
806 if (!_mcparser->parsefullscalePWM(config, measConvFactors.dutycycleToPWM.data()))
807 return false;
808
809 if (!_mcparser->parseAmpsToSensor(config, measConvFactors.ampsToSensor.data()))
810 return false;
811
812 //VALE: i have to parse GeneralMecGroup after parsing jointsetcfg, because inside generalmec group there is useMotorSpeedFbk that needs jointset info.
813
814 if(!_mcparser->parseGearboxValues(config, _parsedCfgData.gearbox_M2J.data(), _parsedCfgData.gearbox_E2J.data()))
815 return false;
816
817 // useMotorSpeedFbk
818 if(eomn_serv_MC_mc4 != (eOmn_serv_type_t)_parsedCfgData.serviceConfig.ethservice.configuration.type)
819 {
820 int* useMotorSpeedFbk = 0;
821 useMotorSpeedFbk = new int[_njoints];
822 if (!_mcparser->parseUseMotorSpeedFbkFlags(config, useMotorSpeedFbk))
823 {
824 delete[] useMotorSpeedFbk;
825 return false;
826 }
827 //Note: currently in eth protocol this parameter belongs to jointset configuration. So
828 // i need to check that every joint belong to same set has the same value
829 if (!verifyUseMotorSpeedFbkInJointSet(useMotorSpeedFbk))
830 {
831 delete[] useMotorSpeedFbk;
832 return false;
833 }
834 delete[] useMotorSpeedFbk;
835 }
836 bool deadzoneIsAvailable;
837 if(!_mcparser->parseDeadzoneValue(config, _parsedCfgData.deadzone.data(), &deadzoneIsAvailable))
838 return false;
839 if(!deadzoneIsAvailable) // if parameter is not written in configuration files then use default values
840 {
841 updateDeadZoneWithDefaultValues();
842 }
843
844 if(!_mcparser->parseKalmanFilterParams(config, _parsedCfgData.kalman_params))
845 {
846 return false;
847 }
848 }
849
850
852 {
853 bool lowLevPidisMandatory = false;
854
855 if((_parsedCfgData.serviceConfig.ethservice.configuration.type == eomn_serv_MC_foc) || (_parsedCfgData.serviceConfig.ethservice.configuration.type == eomn_serv_MC_advfoc))
856 {
857 lowLevPidisMandatory = true;
858 }
859
860 if(!_mcparser->parsePids(config, _parsedCfgData.pidControllers, lowLevPidisMandatory))
861 return false;
862
863 debugUtil_printPidInfoByJointSet();
864
865 //2) since some joint sets configuration info is in control and ids group, get that info and save them in jointset data struct.
866 updatedJointsetsCfgWithControlInfo();
867 }
868
869 for (i = 0; i < _njoints; i++)
870 {
871 measConvFactors.newtonsToSensor[i] = 1000000.0f; // conversion from Nm into microNm
872
873 measConvFactors.bemf2raw[i] = measConvFactors.newtonsToSensor[i] / measConvFactors.angleToEncoder[i];
874 if (_parsedCfgData.pidControllers.trq[0].out_PidUnits == yarp::dev::PidOutputUnitsEnum::DUTYCYCLE_PWM_PERCENT)
875 {
876 measConvFactors.ktau2raw[i] = measConvFactors.dutycycleToPWM[i] / measConvFactors.newtonsToSensor[i];
877 }
878 else if (_parsedCfgData.pidControllers.trq[0].out_PidUnits == yarp::dev::PidOutputUnitsEnum::RAW_MACHINE_UNITS)
879 {
880 measConvFactors.ktau2raw[i] = 1.0 / measConvFactors.newtonsToSensor[i];
881 }
882 else
883 {
884 yError() << getBoardInfo() << "Invalid ktau units"; return false;
885 }
886 }
887
889 // Important Note. The feedback and control units must be the same for all joints of this board.
890 _measureConverter = new ControlBoardHelper(_njoints, _parsedCfgData.axisMap.data(), measConvFactors.angleToEncoder.data(), NULL, measConvFactors.newtonsToSensor.data(), measConvFactors.ampsToSensor.data(), nullptr, measConvFactors.dutycycleToPWM.data(), measConvFactors.bemf2raw.data(), measConvFactors.ktau2raw.data());
891 _measureConverter->set_pid_conversion_units(PidControlTypeEnum::VOCAB_PIDTYPE_POSITION, _parsedCfgData.pidControllers.trj[0].fbk_PidUnits, _parsedCfgData.pidControllers.trj[0].out_PidUnits);
892 _measureConverter->set_pid_conversion_units(PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY_DIRECT, _parsedCfgData.pidControllers.dir_vel[0].fbk_PidUnits, _parsedCfgData.pidControllers.dir_vel[0].out_PidUnits);
893 _measureConverter->set_pid_conversion_units(PidControlTypeEnum::VOCAB_PIDTYPE_MIXED, _parsedCfgData.pidControllers.mix[0].fbk_PidUnits, _parsedCfgData.pidControllers.mix[0].out_PidUnits);
894 _measureConverter->set_pid_conversion_units(PidControlTypeEnum::VOCAB_PIDTYPE_TORQUE, _parsedCfgData.pidControllers.trq[0].fbk_PidUnits, _parsedCfgData.pidControllers.trq[0].out_PidUnits);
895 _measureConverter->set_pid_conversion_units(PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT, _parsedCfgData.pidControllers.cur[0].fbk_PidUnits, _parsedCfgData.pidControllers.cur[0].out_PidUnits);
896 _measureConverter->set_pid_conversion_units(PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY, _parsedCfgData.pidControllers.vel[0].fbk_PidUnits, _parsedCfgData.pidControllers.vel[0].out_PidUnits);
897 _measureConverter->set_pid_conversion_units(PidControlTypeEnum::VOCAB_PIDTYPE_POSITION_DIRECT, _parsedCfgData.pidControllers.dir_pos[0].fbk_PidUnits, _parsedCfgData.pidControllers.dir_pos[0].out_PidUnits);
898
899 // Keep interface helpers in sync with parsed conversion factors before setting PID units.
900 initializeInterfaces(measConvFactors);
901
902 ImplementPidControl::setConversionUnits(PidControlTypeEnum::VOCAB_PIDTYPE_POSITION, _parsedCfgData.pidControllers.trj[0].fbk_PidUnits, _parsedCfgData.pidControllers.trj[0].out_PidUnits);
903 ImplementPidControl::setConversionUnits(PidControlTypeEnum::VOCAB_PIDTYPE_POSITION_DIRECT, _parsedCfgData.pidControllers.dir_pos[0].fbk_PidUnits, _parsedCfgData.pidControllers.dir_pos[0].out_PidUnits);
904 ImplementPidControl::setConversionUnits(PidControlTypeEnum::VOCAB_PIDTYPE_MIXED, _parsedCfgData.pidControllers.mix[0].fbk_PidUnits, _parsedCfgData.pidControllers.mix[0].out_PidUnits);
905 ImplementPidControl::setConversionUnits(PidControlTypeEnum::VOCAB_PIDTYPE_TORQUE, _parsedCfgData.pidControllers.trq[0].fbk_PidUnits, _parsedCfgData.pidControllers.trq[0].out_PidUnits);
906 ImplementPidControl::setConversionUnits(PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT, _parsedCfgData.pidControllers.cur[0].fbk_PidUnits, _parsedCfgData.pidControllers.cur[0].out_PidUnits);
907 ImplementPidControl::setConversionUnits(PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY, _parsedCfgData.pidControllers.vel[0].fbk_PidUnits, _parsedCfgData.pidControllers.vel[0].out_PidUnits);
908 ImplementPidControl::setConversionUnits(PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY_DIRECT, _parsedCfgData.pidControllers.dir_vel[0].fbk_PidUnits, _parsedCfgData.pidControllers.dir_vel[0].out_PidUnits);
909
910 //Now save in data in structures EmbObj protocol compatible
911 if(!saveCouplingsData())
912 return false;
913
914
916 if(! _mcparser->parseImpedanceGroup(config,_parsedCfgData.impedance_params)) return false;
917
918
920 _mcparser->parseLugreGroup(config,_parsedCfgData.lugre_params);
921
922
924 for(j=0; j<_njoints; j++)
925 {
926 // these values have been taken from canBusMotionControl, ask to Randazzo Marco
927 _parsedCfgData.impedance_limits[j].min_damp= 0.001;
928 _parsedCfgData.impedance_limits[j].max_damp= 9.888;
929 _parsedCfgData.impedance_limits[j].min_stiff= 0.002;
930 _parsedCfgData.impedance_limits[j].max_stiff= 9.889;
931 _parsedCfgData.impedance_limits[j].param_a= 0.011;
932 _parsedCfgData.impedance_limits[j].param_b= 0.012;
933 _parsedCfgData.impedance_limits[j].param_c= 0.013;
934 }
935 //TODO
936
937
938
940 {
941 if(!_mcparser->parseCurrentLimits(config, _parsedCfgData.currentLimits))
942 return false;
943
944 if(!_mcparser->parseTemperatureLimits(config, _parsedCfgData.temperatureLimits))
945 return false;
946
947 if(!_mcparser->parseJointsLimits(config, _parsedCfgData.jointsLimits))
948 return false;
949
950 if(!_mcparser->parseRotorsLimits(config, _parsedCfgData.rotorsLimits))
951 return false;
952 }
953
955 eOmn_serv_type_t servtype = static_cast<eOmn_serv_type_t>(_parsedCfgData.serviceConfig.ethservice.configuration.type);
956
957 if((eomn_serv_MC_foc == servtype) || (eomn_serv_MC_advfoc == servtype))
958 {
959 std::string groupName = {};
960
961 if(eomn_serv_MC_foc == servtype)
962 {
963 // in here the name of the group depends on the configured board
964 eObrd_type_t brd = static_cast<eObrd_type_t>(_parsedCfgData.serviceConfig.ethservice.configuration.data.mc.foc_based.type);
965 groupName = (eobrd_foc == brd) ? "2FOC" : "AMCBLDC";
966 }
967 else if(eomn_serv_MC_advfoc == servtype)
968 {
969 // but in here we may have multiple boards, so ... it is better to use a generic name
970 // ADVFOC with multiple columns, one for each motor
971 groupName = "ADVFOC";
972 }
973
974 if(!_mcparser->parseFocGroup(config, _parsedCfgData.foc_based_info, groupName, _parsedCfgData.temperatureSensorsVector))
975 return false;
976
977 for (j = 0; j < _njoints; j++)
978 {
979 //TODO: add a function in defaults to check the consistency of the configuration of the temperature sensor and limits. For now i just put this check here.
980 if (((_parsedCfgData.temperatureSensorsVector.at(j)->getType() != motor_temperature_sensor_none )) && ((_parsedCfgData.temperatureLimits[j].hardware == 0) || (_parsedCfgData.temperatureLimits[j].warning == 0)))
981 {
982 yError() << "In" << getBoardInfo() << "joint" << j << ": inconsistent configuration, please update it. If Temperature limits are not set then TemperatureSensorType must be NONE or not set and/or HasTempSensor must be zero. Aborting...";
983 return false;
984 }
985
986 if (_parsedCfgData.temperatureSensorsVector.at(j)->getType() == motor_temperature_sensor_none)
987 {
988 yInfo() << "embObjMC " << getBoardInfo() << "joint " << j << " has motor not provided with any available type of temperature sensor. If needed update the configurations file accordingly";
989 }
990 }
991 }
992 else
993 {
994 for (j = 0; j < _njoints; j++)
995 {
996 _parsedCfgData.temperatureSensorsVector.at(j) = std::make_unique<eomc::TemperatureSensorNONE>();
997 }
998 }
999
1000
1001
1003 if(! _mcparser->parseTimeoutsGroup(config, _parsedCfgData.timeouts))
1004 return false;
1005
1006 /*****************************************
1007 * IMPORTANT: temporary workaround
1008 * we need to be sure that the configured timeout aren't less of 300 ms
1009 * (default values), otherwise the amcfoc doesn't work because there is some lag in AMC
1010 * *********************************************/
1011 if(this->_parsedCfgData.serviceConfig.ethservice.configuration.type == eomn_serv_MC_advfoc)
1012 {
1013 // Get default timeout from the defaults structure
1014 defaults::DefaultsFactory& factory = defaults::DefaultsFactory::getInstance();
1015 const auto& defaults = factory.getDefaults();
1016 const auto& timeoutsDefaults_amcFoc = defaults.timeoutsDefaults_amcFoc;
1017 for(int i=0; i<_njoints; i++)
1018 {
1019 _parsedCfgData.timeouts[i].velocity_ref = (_parsedCfgData.timeouts[i].velocity_ref < timeoutsDefaults_amcFoc.velocity_ref) ? timeoutsDefaults_amcFoc.velocity_ref : _parsedCfgData.timeouts[i].velocity_ref;
1020 _parsedCfgData.timeouts[i].current_ref = (_parsedCfgData.timeouts[i].current_ref < timeoutsDefaults_amcFoc.current_ref) ? timeoutsDefaults_amcFoc.current_ref : _parsedCfgData.timeouts[i].current_ref;
1021 _parsedCfgData.timeouts[i].pwm_ref = (_parsedCfgData.timeouts[i].pwm_ref < timeoutsDefaults_amcFoc.pwm_ref) ? timeoutsDefaults_amcFoc.pwm_ref : _parsedCfgData.timeouts[i].pwm_ref;
1022 _parsedCfgData.timeouts[i].torque_ref = (_parsedCfgData.timeouts[i].torque_ref < timeoutsDefaults_amcFoc.torque_ref) ? timeoutsDefaults_amcFoc.torque_ref : _parsedCfgData.timeouts[i].torque_ref;
1023 _parsedCfgData.timeouts[i].torque_fbk = (_parsedCfgData.timeouts[i].torque_fbk < timeoutsDefaults_amcFoc.torque_fbk) ? timeoutsDefaults_amcFoc.torque_fbk : _parsedCfgData.timeouts[i].torque_fbk;
1024 }
1025 }
1026
1027
1028 _mcparser->printOptionalParametersTable();
1029 return true;
1030}
1031
1032
1033
1034bool embObjMotionControl::verifyUseMotorSpeedFbkInJointSet(int useMotorSpeedFbk [])
1035{
1036 for(size_t s=0; s< _parsedCfgData.jsets.size(); s++)
1037 {
1038 int numofjointsinset = _parsedCfgData.jsets[s].getNumberofJoints();
1039 if(numofjointsinset == 0 )
1040 {
1041 yError() << "embObjMC " << getBoardInfo() << "Jointsset " << s << "hasn't joints!!! Error in configuration!!!";
1042 return false;
1043 }
1044
1045 int firstjointofset = _parsedCfgData.jsets[s].joints[0];
1046 for(int j=1; j<numofjointsinset; j++)
1047 {
1048 int joint = _parsedCfgData.jsets[s].joints[j];
1049 if(useMotorSpeedFbk[firstjointofset] != useMotorSpeedFbk[joint])
1050 {
1051 yError() << "embObjMC " << getBoardInfo() << ". Param useMotorSpeedFbk should have same value for joints belong same set. See joint " << firstjointofset << " and " << joint;
1052 return false;
1053 }
1054 }
1055
1056 _parsedCfgData.jsets[s].setUseSpeedFeedbackFromMotors(useMotorSpeedFbk[firstjointofset]);
1057 }
1058
1059 return true;
1060
1061}
1062
1063bool embObjMotionControl::verifyTorquePidshasSameUnitTypes(yarp::dev::PidFeedbackUnitsEnum &fbk_pidunits, yarp::dev::PidOutputUnitsEnum& out_pidunits)
1064{
1065 fbk_pidunits = yarp::dev::PidFeedbackUnitsEnum::RAW_MACHINE_UNITS;
1066 out_pidunits = yarp::dev::PidOutputUnitsEnum::RAW_MACHINE_UNITS;
1067 //get first joint with enabled torque
1068 int firstjoint = -1;
1069 for(int i=0; i<_njoints; i++)
1070 {
1071 if(_parsedCfgData.pidControllers.trq[i].enabled)
1072 {
1073 firstjoint = i;
1074 break;
1075 }
1076 }
1077
1078 // if no joint has torque enabled return true
1079 if(firstjoint==-1) return true;
1080
1081
1082 for(int i=firstjoint+1; i<_njoints; i++)
1083 {
1084 if(_parsedCfgData.pidControllers.trq[i].enabled)
1085 {
1086 if(_parsedCfgData.pidControllers.trq[firstjoint].fbk_PidUnits != _parsedCfgData.pidControllers.trq[i].fbk_PidUnits ||
1087 _parsedCfgData.pidControllers.trq[firstjoint].out_PidUnits != _parsedCfgData.pidControllers.trq[i].out_PidUnits)
1088 {
1089 yError() << "embObjMC " << getBoardInfo() << "all joints with torque enabled should have same controlunits type. Joint " << firstjoint << " differs from joint " << i;
1090 return false;
1091 }
1092 }
1093 }
1094
1095 fbk_pidunits = _parsedCfgData.pidControllers.trq[firstjoint].fbk_PidUnits;
1096 out_pidunits = _parsedCfgData.pidControllers.trq[firstjoint].out_PidUnits;
1097 return true;
1098}
1099
1100void embObjMotionControl::updateDeadZoneWithDefaultValues(void)
1101{
1102 // Get the default values structure from singleton
1103 defaults::DefaultsFactory& factory = defaults::DefaultsFactory::getInstance();
1104 const auto& defaults = factory.getDefaults();
1105
1106
1107 for(int i=0; i<_njoints; i++)
1108 {
1109 switch(_parsedCfgData.jointEncs[i].type)
1110 {
1111 case eomc_enc_aea:
1112 _parsedCfgData.deadzone[i] = defaults.controlParametersDefaults.deadzone.jointWithAEA;
1113 _mcparser->registerOptionalParameter("deadzone_AEA", std::to_string(defaults.controlParametersDefaults.deadzone.jointWithAEA), true);
1114 break;
1115 case eomc_enc_aea3:
1116 _parsedCfgData.deadzone[i] = defaults.controlParametersDefaults.deadzone.jointWithAEA3;
1117 _mcparser->registerOptionalParameter("deadzone_AEA3", std::to_string(defaults.controlParametersDefaults.deadzone.jointWithAEA3), true);
1118 break;
1119 case eomc_enc_aksim2:
1120 _parsedCfgData.deadzone[i] = defaults.controlParametersDefaults.deadzone.jointWithAKSIM2;
1121 _mcparser->registerOptionalParameter("deadzone_AKSIM2", std::to_string(defaults.controlParametersDefaults.deadzone.jointWithAKSIM2), true);
1122 break;
1123 case eomc_enc_amo:
1124 _parsedCfgData.deadzone[i] = defaults.controlParametersDefaults.deadzone.jointWithAMO;
1125 _mcparser->registerOptionalParameter("deadzone_AMO", std::to_string(defaults.controlParametersDefaults.deadzone.jointWithAMO), true);
1126 break;
1127 case eomc_enc_roie:
1128 case eomc_enc_absanalog:
1129 case eomc_enc_mais:
1130 case eomc_enc_qenc:
1131 case eomc_enc_hallmotor:
1132 case eomc_enc_spichainof2:
1133 case eomc_enc_spichainof3:
1134 case eomc_enc_mrie:
1135 default:
1136 _parsedCfgData.deadzone[i] = defaults.controlParametersDefaults.deadzone.otherEncoder;
1137 _mcparser->registerOptionalParameter("deadzone_other", std::to_string(defaults.controlParametersDefaults.deadzone.otherEncoder), true);
1138 }
1139 }
1140}
1141
1142
1143
1144// use this one for ... service configuration
1145bool embObjMotionControl::fromConfig_readServiceCfg(yarp::os::Searchable &config)
1146{
1147
1148 if(false == _srvParser->parseService(config, _parsedCfgData.serviceConfig))
1149 {
1150 yError() << "embObjMC " << getBoardInfo() << "cannot parse service" ;
1151 return false;
1152 }
1153
1154 if(eomn_serv_MC_generic == _parsedCfgData.serviceConfig.ethservice.configuration.type)
1155 {
1156 yError() << "embObjMC " << getBoardInfo() << "it is no longer possible use eomn_serv_MC_generic, because firmware cannot configure itself!" ;
1157 return false;
1158 }
1159
1160 //now _srvParser read encoders' resolutions also.
1161 //so here I save in embObMotioncontrol memory encoders's resolution
1162 servMC_encoder_t * jointEncoder_ptr = NULL;
1163 servMC_encoder_t * motorEncoder_ptr = NULL;
1164 for(int i=0; i<_njoints; i++)
1165 {
1166 jointEncoder_ptr = _srvParser->getEncoderAtJoint(i);
1167 motorEncoder_ptr = _srvParser->getEncoderAtMotor(i);
1168
1169 if(NULL == jointEncoder_ptr)
1170 {
1171 _parsedCfgData.jointEncs[i].resolution = 1;
1172 _parsedCfgData.jointEncs[i].type = eomc_enc_none;
1173 _parsedCfgData.jointEncs[i].tolerance = 0;
1174 }
1175 else
1176 {
1177 _parsedCfgData.jointEncs[i].resolution = jointEncoder_ptr->resolution;
1178 _parsedCfgData.jointEncs[i].type = (eOmc_encoder_t)jointEncoder_ptr->desc.type; //Here I'm sure that type belong to eOmc_encoder_t enum.It is filled by eomc_string2encoder function
1179 _parsedCfgData.jointEncs[i].tolerance = jointEncoder_ptr->tolerance;
1180 }
1181
1182
1183 if(NULL == motorEncoder_ptr)
1184 {
1185 _parsedCfgData.motorEncs[i].resolution = 1;
1186 _parsedCfgData.motorEncs[i].type = eomc_enc_none;
1187 _parsedCfgData.motorEncs[i].tolerance = 0;
1188 }
1189 else
1190 {
1191 _parsedCfgData.motorEncs[i].resolution = motorEncoder_ptr->resolution;
1192 _parsedCfgData.motorEncs[i].type = (eOmc_encoder_t)motorEncoder_ptr->desc.type; //Here I'm sure that type belong to eOmc_encoder_t enum.It is filled by eomc_string2encoder function
1193 _parsedCfgData.motorEncs[i].tolerance = motorEncoder_ptr->tolerance;
1194 }
1195
1196
1197 }
1198
1199
1200 return true;
1201}
1202
1203
1204
1205bool embObjMotionControl::fromConfig(yarp::os::Searchable &config)
1206{
1207
1208 _njoints = fromConfig_NumOfJoints(config);
1209
1210 if(0 == _njoints)
1211 {
1212 yError() << "embObjMC"<< getBoardInfo() << "fromConfig(): detected _njoints = " << _njoints;
1213 return false;
1214 }
1215
1216 // we have number of joints inside _njoints. we allocate all required buffers
1217 if(!alloc(_njoints))
1218 {
1219 yError() << "embObjMC"<< getBoardInfo() << "fromConfig(): alloc() failed for _njoints = " << _njoints;
1220 return false;
1221 }
1222
1223
1224 _mcparser = new eomc::Parser(_njoints, string(_ethRes->getProperties().boardnameString));
1225
1227 int currentMCversion =0;
1228 if(!_mcparser->parseMotioncontrolVersion(config, currentMCversion))
1229 return false;
1230
1231 if (currentMCversion != PARSER_MOTION_CONTROL_VERSION)
1232 {
1233 yError() << "embObjMC" << getBoardInfo() << "------ ATTENTION!!!! Wrong value of <MotioncontrolVersion> parameter !!!! ---------------------------------------------------------------------------------------";
1234 yError() << "embObjMC" << getBoardInfo() << "------ This means that the configuration files of this device are not compatible with my parser, so I cannot start. ";
1235 yError() << "embObjMC" << getBoardInfo() << "------ I need version " << PARSER_MOTION_CONTROL_VERSION << ", but in configuration files have version " << currentMCversion << ".";
1236 yError() << "embObjMC" << getBoardInfo() << "------ Please update configuration files in robots-configuration repository. (see https://icub-tech-iit.github.io/documentation/icub_robot_configuration/icub_robot_configuration_index/ for more information). ";
1237 yError() << "embObjMC" << getBoardInfo() << "------ If the problem persists contact icub-support@iit.it DO NOT DO IT BY YOURSELF.";
1238 yError() << "embObjMC" << getBoardInfo() << "----------------------------------------------------------------------------------------------------------------------------------------------------------------";
1239 return false;
1240 }
1241
1242 //print verbose info
1243 if(_mcparser->isVerboseEnabled(config))
1244 yTrace() << config.toString().c_str();
1245
1246
1247
1248 // first step of configuration
1249 if(false == fromConfig_readServiceCfg(config))
1250 {
1251 return false;
1252 }
1253
1254 if(!_mcparser->parseBehaviourFalgs(config, _parsedCfgData.behFlags.useRawEncoderData, _parsedCfgData.behFlags.pwmIsLimited ))//in general info group
1255 {
1256 return false;
1257 }
1258
1259 if (!_mcparser->parseMaintenanceModeGroup(config, _parsedCfgData.maintenanceModeCfg.enableSkipRecalibration))// in general maintenance group
1260 {
1261 return false;
1262 }
1263
1264 // second step of configuration
1265 if(false == fromConfig_Step2(config))
1266 {
1267 return false;
1268 }
1269
1270 // third step of configuration
1271
1272
1273 return true;
1274}
1275
1276
1277bool embObjMotionControl::init()
1278{
1279 eOprotID32_t protid = 0;
1280
1282 //SEND DISABLE TO ALL JOINTS
1284
1285 for(int logico=0; logico< _njoints; logico++)
1286 {
1287 int fisico = _parsedCfgData.axisMap[logico];
1288 protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, fisico, eoprot_tag_mc_joint_cmmnds_controlmode);
1289 eOenum08_t controlMode = eomc_controlmode_cmd_idle;
1290
1291 if(false == _ethRes->setRemoteValue(protid, &controlMode))
1292 {
1293 yError() << "embObjMotionControl::init() had an error while setting eomc_controlmode_cmd_idle in "<< getBoardInfo();
1294 // return(false); i dont return false. because even if a failure, that is not a severe error.
1295 // MOREOVER: to verify we must read the status of the joint and NOT the command ... THINK OF IT
1296 }
1297 }
1298
1299 SystemClock::delaySystem(0.010);
1300
1301
1303 // configure the regular rops
1305
1306 vector<eOprotID32_t> id32v(0);
1307 for(int n=0; n<_njoints; n++)
1308 {
1309 protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, n, eoprot_tag_mc_joint_status_core);
1310 id32v.push_back(protid);
1311 protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, n, eoprot_tag_mc_joint_status_addinfo_multienc);
1312 id32v.push_back(protid);
1313 protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, n, eoprot_tag_mc_motor_status);
1314 id32v.push_back(protid);
1315 }
1316
1317 if(eomn_serv_diagn_mode_MC_AMOyarp == _mcdiagnostics.config.mode)
1318 {
1319 protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, 0, eoprot_tag_mc_joint_status_debug);
1320 id32v.push_back(protid);
1321 protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, 1, eoprot_tag_mc_joint_status_debug);
1322 id32v.push_back(protid);
1323 }
1324
1325
1326 if(false == _ethRes->serviceSetRegulars(eomn_serv_category_mc, id32v))
1327 {
1328 yError() << "embObjMotionControl::init() fails to add its variables to regulars in "<< getBoardInfo() << ": cannot proceed any further";
1329 return false;
1330 }
1331 else
1332 {
1333 if(_parsedCfgData.behFlags.verbosewhenok)
1334 {
1335 yDebug() << "embObjMotionControl::init() added" << id32v.size() << "regular rops to "<< getBoardInfo();
1336 char nvinfo[128];
1337 for(unsigned int r=0; r<id32v.size(); r++)
1338 {
1339 uint32_t id32 = id32v.at(r);
1340 eoprot_ID2information(id32, nvinfo, sizeof(nvinfo));
1341 yDebug() << "\t it added regular rop for" << nvinfo;
1342 }
1343 }
1344 }
1345
1346 SystemClock::delaySystem(0.005);
1347
1348
1350 // sending configuration to the JOINTS //
1352 for(int logico=0; logico< _njoints; logico++)
1353 {
1354 int fisico = _parsedCfgData.axisMap[logico];
1355 protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, fisico, eoprot_tag_mc_joint_config);
1356
1357 eOmc_joint_config_t jconfig = {0};
1358
1359 yarp::dev::Pid tmp;
1360 tmp = _measureConverter->convert_pid_to_machine(yarp::dev::PidControlTypeEnum::VOCAB_PIDTYPE_POSITION,_parsedCfgData.pidControllers.trj[logico].pid, fisico);
1361 copyPid_iCub2eo(&tmp, &jconfig.pidtrajectory);
1362 tmp = _measureConverter->convert_pid_to_machine(yarp::dev::PidControlTypeEnum::VOCAB_PIDTYPE_POSITION_DIRECT, _parsedCfgData.pidControllers.dir_pos[logico].pid, fisico);
1363 copyPid_iCub2eo(&tmp, &jconfig.piddirect);
1364 tmp = _measureConverter->convert_pid_to_machine(yarp::dev::PidControlTypeEnum::VOCAB_PIDTYPE_TORQUE, _parsedCfgData.pidControllers.trq[logico].pid, fisico);
1365 copyPid_iCub2eo(&tmp, &jconfig.pidtorque);
1366 //Note: The mixed control and velocity control use the position pid. The velocity direct and current PID are sent in motor configuration.
1367
1368 //stiffness and damping read in xml file are in Nm/deg and Nm/(Deg/sec), so we need to convert before send to fw.
1369 jconfig.impedance.damping = (eOmeas_damping_t) _measureConverter->impN2S(_parsedCfgData.impedance_params[logico].damping, fisico);
1370 jconfig.impedance.stiffness = (eOmeas_stiffness_t) _measureConverter->impN2S(_parsedCfgData.impedance_params[logico].stiffness, fisico);
1371 jconfig.impedance.offset = 0;
1372
1373 _cacheImpedance[logico].stiffness = jconfig.impedance.stiffness;
1374 _cacheImpedance[logico].damping = jconfig.impedance.damping;
1375 _cacheImpedance[logico].offset = jconfig.impedance.offset;
1376
1377 jconfig.userlimits.max = (eOmeas_position_t) S_32(_measureConverter->posA2E(_parsedCfgData.jointsLimits[logico].posMax, fisico));
1378 jconfig.userlimits.min = (eOmeas_position_t) S_32(_measureConverter->posA2E(_parsedCfgData.jointsLimits[logico].posMin, fisico));
1379
1380 jconfig.hardwarelimits.max = (eOmeas_position_t) S_32(_measureConverter->posA2E(_parsedCfgData.jointsLimits[logico].posHwMax, fisico));
1381 jconfig.hardwarelimits.min = (eOmeas_position_t) S_32(_measureConverter->posA2E(_parsedCfgData.jointsLimits[logico].posHwMin, fisico));
1382
1383
1384 jconfig.maxvelocityofjoint = S_32(_measureConverter->posA2E(_parsedCfgData.jointsLimits[logico].velMax, fisico)); //icubdeg/s
1385 jconfig.velocitysetpointtimeout = (eOmeas_time_t) U_16(_parsedCfgData.timeouts[logico].velocity_ref);
1386 jconfig.currentsetpointtimeout = (eOmeas_time_t) U_16(_parsedCfgData.timeouts[logico].current_ref);
1387 jconfig.openloopsetpointtimeout = (eOmeas_time_t) U_16(_parsedCfgData.timeouts[logico].pwm_ref);
1388 jconfig.torquesetpointtimeout = (eOmeas_time_t) U_16(_parsedCfgData.timeouts[logico].torque_ref);
1389 jconfig.torquefeedbacktimeout = (eOmeas_time_t) U_16(_parsedCfgData.timeouts[logico].torque_fbk);
1390
1391 jconfig.jntEncoderResolution = _parsedCfgData.jointEncs[logico].resolution;
1392 jconfig.jntEncoderType = _parsedCfgData.jointEncs[logico].type;
1393 jconfig.jntEncTolerance = _parsedCfgData.jointEncs[logico].tolerance;
1394
1395 jconfig.motor_params.bemf_scale = 0;
1396 jconfig.motor_params.ktau_value = _measureConverter->ktau_user2raw(_parsedCfgData.pidControllers.trq[logico].ktau, fisico);
1397 jconfig.motor_params.ktau_scale = 0;
1398 jconfig.motor_params.friction.viscous_pos_val = _measureConverter->viscousPos_user2raw(_parsedCfgData.pidControllers.trq[logico].viscousPos, fisico);
1399 jconfig.motor_params.friction.viscous_neg_val = _measureConverter->viscousNeg_user2raw(_parsedCfgData.pidControllers.trq[logico].viscousNeg, fisico);
1400 jconfig.motor_params.friction.coulomb_pos_val = _measureConverter->coulombPos_user2raw(_parsedCfgData.pidControllers.trq[logico].coulombPos, fisico);
1401 jconfig.motor_params.friction.coulomb_neg_val = _measureConverter->coulombNeg_user2raw(_parsedCfgData.pidControllers.trq[logico].coulombNeg, fisico);
1402 jconfig.motor_params.friction.velocityThres_val = _measureConverter->velocityThres_user2raw(_parsedCfgData.pidControllers.trq[logico].velocityThres, fisico);
1403
1404 jconfig.gearbox_E2J = _parsedCfgData.gearbox_E2J[logico];
1405
1406 jconfig.deadzone = _measureConverter->posA2E(_parsedCfgData.deadzone[logico], fisico);
1407
1408 jconfig.tcfiltertype=_parsedCfgData.pidControllers.trq[logico].filterType;
1409
1410 jconfig.kalman_params.enabled = _parsedCfgData.kalman_params[logico].enabled;
1411 for(int i=0; i<_parsedCfgData.kalman_params[logico].x0.size(); i++) jconfig.kalman_params.x0[i] = _parsedCfgData.kalman_params[logico].x0.at(i);
1412 for(int i=0; i<_parsedCfgData.kalman_params[logico].Q.size(); i++) jconfig.kalman_params.Q[i] = _parsedCfgData.kalman_params[logico].Q.at(i);
1413 jconfig.kalman_params.R = _parsedCfgData.kalman_params[logico].R;
1414 jconfig.kalman_params.P0 = _parsedCfgData.kalman_params[logico].P0;
1415
1416 if(false == _ethRes->setcheckRemoteValue(protid, &jconfig, 10, 0.010, 0.050))
1417 {
1418 yError() << "FATAL: embObjMotionControl::init() had an error while calling setcheckRemoteValue() for joint config fisico #" << fisico << "in "<< getBoardInfo();
1419 return false;
1420 }
1421 else
1422 {
1423 if(_parsedCfgData.behFlags.verbosewhenok)
1424 {
1425 yDebug() << "embObjMotionControl::init() correctly configured joint config fisico #" << fisico << "in "<< getBoardInfo();
1426 }
1427 }
1428 }
1429
1430
1432 // sending configuration to the MOTORS //
1434
1435
1436 for(int logico=0; logico<_njoints; logico++)
1437 {
1438 int fisico = _parsedCfgData.axisMap[logico];
1439
1440 protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, fisico, eoprot_tag_mc_motor_config);
1441 eOmc_motor_config_t motor_cfg = {0};
1442 motor_cfg.maxvelocityofmotor = 0;//_maxMotorVelocity[logico]; //unused yet!
1443 motor_cfg.currentLimits.nominalCurrent = _parsedCfgData.currentLimits[logico].nominalCurrent;
1444 motor_cfg.currentLimits.overloadCurrent = _parsedCfgData.currentLimits[logico].overloadCurrent;
1445 motor_cfg.currentLimits.peakCurrent = _parsedCfgData.currentLimits[logico].peakCurrent;
1446 motor_cfg.gearbox_M2J = _parsedCfgData.gearbox_M2J[logico];
1447 motor_cfg.rotorEncoderResolution = _parsedCfgData.motorEncs[logico].resolution;
1448 motor_cfg.rotEncTolerance = _parsedCfgData.motorEncs[logico].tolerance;
1449 motor_cfg.hasHallSensor = _parsedCfgData.foc_based_info[logico].hasHallSensor;
1450 motor_cfg.hasRotorEncoder = _parsedCfgData.foc_based_info[logico].hasRotorEncoder;
1451 motor_cfg.hasTempSensor = _parsedCfgData.foc_based_info[logico].hasTempSensor;
1452 motor_cfg.hasRotorEncoderIndex = _parsedCfgData.foc_based_info[logico].hasRotorEncoderIndex;
1453 motor_cfg.hasSpeedEncoder = _parsedCfgData.foc_based_info[logico].hasSpeedEncoder;
1454 motor_cfg.verbose = _parsedCfgData.foc_based_info[logico].verbose;
1455 motor_cfg.motorPoles = _parsedCfgData.foc_based_info[logico].motorPoles;
1456 motor_cfg.rotorIndexOffset = _parsedCfgData.foc_based_info[logico].rotorIndexOffset;
1457 motor_cfg.Kbemf = _parsedCfgData.foc_based_info[logico].kbemf;
1458 motor_cfg.rotorEncoderType = _parsedCfgData.motorEncs[logico].type;
1459 motor_cfg.pwmLimit =_parsedCfgData.rotorsLimits[logico].pwmMax;
1460 motor_cfg.temperatureLimit = (eOmeas_temperature_t) S_16(_parsedCfgData.temperatureSensorsVector.at(logico)->convertTempCelsiusToRaw(_parsedCfgData.temperatureLimits.at(logico).hardware)); //passing raw value not in degree
1461 motor_cfg.limitsofrotor.max = (eOmeas_position_t) S_32(_measureConverter->posA2E(_parsedCfgData.rotorsLimits[logico].posMax, fisico ));
1462 motor_cfg.limitsofrotor.min = (eOmeas_position_t) S_32(_measureConverter->posA2E(_parsedCfgData.rotorsLimits[logico].posMin, fisico ));
1463
1464 motor_cfg.LuGre_params.Km = _parsedCfgData.lugre_params[logico].Km;
1465 motor_cfg.LuGre_params.Kw = _parsedCfgData.lugre_params[logico].Kw;
1466 motor_cfg.LuGre_params.S0 = _parsedCfgData.lugre_params[logico].S0;
1467 motor_cfg.LuGre_params.S1 = _parsedCfgData.lugre_params[logico].S1;
1468 motor_cfg.LuGre_params.Vth = _parsedCfgData.lugre_params[logico].Vth;
1469 motor_cfg.LuGre_params.Fc_pos = _parsedCfgData.lugre_params[logico].Fc_pos;
1470 motor_cfg.LuGre_params.Fc_neg = _parsedCfgData.lugre_params[logico].Fc_neg;
1471 motor_cfg.LuGre_params.Fs_pos = _parsedCfgData.lugre_params[logico].Fs_pos;
1472 motor_cfg.LuGre_params.Fs_neg = _parsedCfgData.lugre_params[logico].Fs_neg;
1473
1474 yarp::dev::Pid tmp;
1475
1476 //current pid
1477 tmp = _measureConverter->convert_pid_to_machine(yarp::dev::PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT, _parsedCfgData.pidControllers.cur[logico].pid, fisico);
1478 copyPid_iCub2eo(&tmp, &motor_cfg.pidcurrent);
1479 //TODO: ceck if current is a optional parameter. if not here i need to check if it is anabled before convert and copy. if it is optional, then I need to set also the enable flag in motor_cfg.pidcurrent
1480
1481 //velocity pid
1482 memset(&motor_cfg.pidvelcur, 0, sizeof(eOmc_PID_t));
1483 memset(&motor_cfg.pidvelpwm, 0, sizeof(eOmc_PID_t));
1484
1485 if(_parsedCfgData.pidControllers.dir_vel[logico].enabled)
1486 {
1487 tmp = _measureConverter->convert_pid_to_machine(yarp::dev::PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY_DIRECT, _parsedCfgData.pidControllers.dir_vel[logico].pid, fisico);
1488
1489
1490 if(eomc_ctrl_out_type_vel_pwm == _parsedCfgData.pidControllers.dir_vel[logico].out_type)
1491 {
1492 copyPid_iCub2eo(&tmp, &motor_cfg.pidvelpwm);
1493 }
1494 else if (eomc_ctrl_out_type_vel_cur == _parsedCfgData.pidControllers.dir_vel[logico].out_type)
1495 {
1496 copyPid_iCub2eo(&tmp, &motor_cfg.pidvelcur);
1497 }
1498 else
1499 {
1500
1501 yError() << "embObjMC " << getBoardInfo() << " joint " << logico << " velocity direct pid has unsupported output type " << _parsedCfgData.pidControllers.dir_vel[logico].out_type;
1502 return false;
1503 }
1504 }
1505
1506
1507 if (false == _ethRes->setcheckRemoteValue(protid, &motor_cfg, 10, 0.010, 0.050))
1508 {
1509 yError() << "FATAL: embObjMotionControl::init() had an error while calling setcheckRemoteValue() for motor config fisico #" << fisico << "in "<< getBoardInfo();
1510 return false;
1511 }
1512 else
1513 {
1514 if (_parsedCfgData.behFlags.verbosewhenok)
1515 {
1516 yDebug() << "embObjMotionControl::init() correctly configured motor config fisico #" << fisico << "in "<< getBoardInfo();
1517 }
1518 }
1519 }
1520
1522 // sending configuration to the CONTROLLER //
1524
1525 protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_controller, 0, eoprot_tag_mc_controller_config);
1526
1527 eOmc_controller_config_t controller_cfg = {0};
1528 memset(&controller_cfg, 0, sizeof(eOmc_controller_config_t));
1529 controller_cfg.durationofctrlloop = (uint32_t)_bdata.settings.txconfig.cycletime;
1530 controller_cfg.enableskiprecalibration = _parsedCfgData.maintenanceModeCfg.enableSkipRecalibration;
1531
1532 if(false == _ethRes->setcheckRemoteValue(protid, &controller_cfg, 10, 0.010, 0.050))
1533 {
1534 yError() << "FATAL: embObjMotionControl::init() had an error while calling setcheckRemoteValue() for the controller " << "in "<< getBoardInfo();
1535 return false;
1536 }
1537 else
1538 {
1539 if(_parsedCfgData.behFlags.verbosewhenok)
1540 {
1541 yDebug() << "embObjMotionControl::init() correctly configured controller config " << "in "<< getBoardInfo();
1542 }
1543 }
1544
1546 // intialize the map of the rawValuesVectors //
1548 const char* tag = eoprot_TAG2string(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, eoprot_tag_mc_joint_status_addinfo_multienc);
1549
1550 _rawValuesMetadataMap.insert({{tag, rawValuesKeyMetadata({}, {}, _njoints * eOmc_joint_multienc_maxnum)}});
1551 for (auto &[k, v] : _rawValuesMetadataMap)
1552 {
1553 std::string auxstring = "";
1554
1555 for (int i = 0; i < _njoints; i++)
1556 {
1557 getEntityName(i, auxstring);
1558 if (k == tag)
1559 {
1560 v.axesNames.push_back(auxstring);
1561 v.rawValueNames.insert(v.rawValueNames.end(),
1562 {auxstring+"_primary_encoder_raw_value",
1563 auxstring+"_secondary_encoder_raw_value",
1564 auxstring+"_primary_encoder_diagnostic"}
1565 );
1566 }
1567 auxstring.clear();
1568 }
1569 }
1570 if(_parsedCfgData.behFlags.verbosewhenok)
1571 yDebug() << "_rawValuesMetadataMap initialized for " << getBoardInfo();
1572
1573 return true;
1574}
1575
1576
1577
1579{
1580 yTrace() << " embObjMotionControl::close()";
1581
1582 ImplementControlMode::uninitialize();
1583 ImplementEncodersTimed::uninitialize();
1584 ImplementMotorEncoders::uninitialize();
1585 ImplementPositionControl::uninitialize();
1586 ImplementVelocityControl::uninitialize();
1587 ImplementPidControl::uninitialize();
1588 ImplementControlCalibration::uninitialize();
1589 ImplementAmplifierControl::uninitialize();
1590 ImplementImpedanceControl::uninitialize();
1591 ImplementControlLimits::uninitialize();
1592 ImplementTorqueControl::uninitialize();
1593 ImplementPositionDirect::uninitialize();
1594 ImplementInteractionMode::uninitialize();
1595 ImplementRemoteVariables::uninitialize();
1596 ImplementAxisInfo::uninitialize();
1597 ImplementCurrentControl::uninitialize();
1598 ImplementPWMControl::uninitialize();
1599 ImplementJointFault::uninitialize();
1600 ImplementJointBrake::uninitialize();
1601
1602 if (_measureConverter) {delete _measureConverter; _measureConverter=0;}
1603
1604
1605 if(eomn_serv_diagn_mode_MC_AMOyarp == _mcdiagnostics.config.mode)
1606 {
1607 // close the ports
1608 for(size_t i=0; i<_mcdiagnostics.ports.size(); i++)
1609 {
1610 _mcdiagnostics.ports[i]->close();
1611 delete _mcdiagnostics.ports[i];
1612 }
1613 _mcdiagnostics.ports.clear();
1614
1615 _mcdiagnostics.config.mode = eomn_serv_diagn_mode_NONE;
1616 _mcdiagnostics.config.par16 = 0;
1617 }
1618
1619 delete _event_downsampler;
1620 // in cleanup, at date of 23feb2016 there is a call to _ethManager->releaseResource() which ...
1621 // send to config all the boards and stops tx and rx treads.
1622 // thus, in here we cannot call serviceStop(mc) because there will be tx/rx activity only for the first call of ::close().
1623 // i termporarily put serviceStop(eomn_serv_category_all) inside releaseResource()
1624 // todo: later on: clear regulars of mc, stop(mc), inside releaseresource() DO NOT stop tx/rx activity and DO NOT stop all services
1625 // _ethRes->serviceStop(eomn_serv_category_mc);
1626 // #warning TODO: clear the regulars imposed by motion-control.
1627
1628 cleanup();
1629
1630 return true;
1631}
1632
1633void embObjMotionControl::cleanup(void)
1634{
1635 if(_ethManager == NULL) return;
1636
1637 int ret = _ethManager->releaseResource2(_ethRes, this);
1638 _ethRes = NULL;
1639 if(ret == -1)
1640 _ethManager->killYourself();
1641}
1642
1643
1649
1650bool embObjMotionControl::update(eOprotID32_t id32, double timestamp, void *rxdata)
1651{
1652 // use this function to update the values cached in the class using data received by the remote boards via the network callbacks
1653 // in embObjMotionControl it is updated only the timestamp of the encoders, thuus i dont used rxdata
1654 size_t joint = eoprot_ID2index(id32);
1655 eOprotEntity_t ent = eoprot_ID2entity(id32);
1656 eOprotTag_t tag = eoprot_ID2tag(id32);
1657
1658 // rxdata = rxdata;
1659
1660 // marco.accame: pay attention using rxdata. the rxdata depends on the id32.
1661 // now the function update() is called with rxdata of different types.
1662 // if the tag is eoprot_tag_mc_joint_status, then rxdata is of type eOmc_joint_status_t*
1663 // if the tag is eoprot_tag_mc_joint_status_basic, then rxdata is of type eOmc_joint_status_basic_t*
1664
1665
1666 // for the case of id32 which contains an encoder value .... we refresh the timestamp of that encoder
1667
1668 if(true == initialised())
1669 { // do it only if we already have opened the device
1670 std::lock_guard<std::mutex> lck(_mutex);
1671 _encodersStamp[joint] = timestamp;
1672 }
1673
1674
1675 if(eomn_serv_diagn_mode_MC_AMOyarp == _mcdiagnostics.config.mode)
1676 {
1677 char str[128] = "boh";
1678
1679 eoprot_ID2information(id32, str, sizeof(str));
1680
1681 if((eoprot_entity_mc_joint == ent) && (eoprot_tag_mc_joint_status_debug == tag) && (joint < _mcdiagnostics.ports.size()))
1682 {
1683
1684 eOprotID32_t id32sc = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, joint, eoprot_tag_mc_joint_status_core);
1685 eOmc_joint_status_core_t jcore = {};
1686
1687 _ethRes->getLocalValue(id32sc, &jcore);
1688
1689 int32_t *debug32 = reinterpret_cast<int32_t*>(rxdata);
1690 // write into relevant port
1691
1692 Bottle& output = _mcdiagnostics.ports[joint]->prepare();
1693 output.clear();
1694 //output.addString("[yt, amo, reg, pos]"); // but we must get the joint and the motor as well
1695 output.addString("[yt, amo, reg, pos]");
1696 output.addFloat64(timestamp);
1697 output.addInt32(debug32[0]);
1698 output.addInt32(debug32[1]);
1699 output.addInt32(jcore.measures.meas_position);
1700 _mcdiagnostics.ports[joint]->write();
1701 }
1702 }
1703
1704 if((eoprot_entity_mc_motor == ent) && (eoprot_tag_mc_motor_status == tag))
1705 {
1706 if(false == initialised())
1707 return true;
1708
1709 uint8_t motor = eoprot_ID2index(id32);
1710 if((_parsedCfgData.temperatureSensorsVector.at(motor)->getType() == motor_temperature_sensor_none))
1711 return true;
1712
1713 eOmc_motor_status_t *mc_motor_status = reinterpret_cast<eOmc_motor_status_t*>(rxdata);
1714
1715 if((double)mc_motor_status->basic.mot_temperature < 0 ) //I get a invalid value
1716 {
1717 if(! _temperatureSensorErrorWatchdog.at(motor).isStarted())
1718 {
1719 yWarning() << getBoardInfo() << "At time" << (yarp::os::Time::now() - _temperatureSensorErrorWatchdog.at(motor).getAbsoluteTime()) << "In motor" << motor << "cannot read Temperature from I2C. There might be cabling problems, TDB cable might be broken or sensor unreachable";
1720 _temperatureSensorErrorWatchdog.at(motor).start();
1721 }
1722 else
1723 {
1724 _temperatureSensorErrorWatchdog.at(motor).increment();
1725 if( _temperatureSensorErrorWatchdog.at(motor).isExpired())
1726 {
1727 yWarning()<< getBoardInfo() << "Motor" << motor << "failed to read" << _temperatureSensorErrorWatchdog.at(motor).getCount() << "temperature readings for" << yarp::os::Time::now() - _temperatureSensorErrorWatchdog.at(motor).getStartTime() << "seconds";
1728 _temperatureSensorErrorWatchdog.at(motor).start();
1729 }
1730 }
1731 return true;
1732 }
1733
1734 //if I'm here I have a valid value
1735 double delta_tmp = 0;
1736 double tmp = _parsedCfgData.temperatureSensorsVector.at(motor)->convertRawToTempCelsius((double)mc_motor_status->basic.mot_temperature);
1737
1738 // check if this is a spike or not
1739 // evaluate difference between current and previous temperature
1740 if(!_temperatureSpikesFilter.at(motor).isStarted()) //Pre-set of the filter buffer is ready
1741 {
1742 _temperatureSpikesFilter.at(motor).start(tmp);
1743 return true;
1744 }
1745
1746 // when i'm here the filter is ready.
1747 delta_tmp = std::abs(tmp - _temperatureSpikesFilter.at(motor).getPrevTemperature());
1748
1749 //1. check if I have a good value (not a spike)
1750 if(delta_tmp > _temperatureSpikesFilter.at(motor).getTemperatureThreshold())
1751 {
1752 //it is a spike
1753 return true;
1754 }
1755 // this is a not spike --> can update prev temperature
1756 _temperatureSpikesFilter.at(motor).updatePrevTemperature(tmp);
1757
1758 //2. tmp is good and check the limits
1759 if(tmp > _parsedCfgData.temperatureLimits[motor].warning)
1760 {
1761 if(! _temperatureExceededLimitWatchdog.at(motor).isStarted())
1762 {
1763 yWarning() << getBoardInfo() << "Motor" << motor << "The temperature (" << tmp << "[ ℃ ] ) exceeds the warning limit (" << _parsedCfgData.temperatureLimits[motor].warning << "[ ℃ ] ). Processes not stopped but it is strongly recommended decreasing motor usage or reducing currents and PWMs to not risk motor damaging";
1764 _temperatureExceededLimitWatchdog.at(motor).start();
1765 }
1766 else
1767 {
1768 if(_temperatureExceededLimitWatchdog.at(motor).isExpired())
1769 {
1770 yWarning() << getBoardInfo() << "Motor" << motor << "The temperature (" << tmp << "[ ℃ ] ) exceeds the warning limit (" << _parsedCfgData.temperatureLimits[motor].warning << "[ ℃ ] ) again!. Processes not stopped but it is strongly recommended decreasing motor usage or reducing currents and PWMs to not risk motor damaging";
1771 _temperatureExceededLimitWatchdog.at(motor).start();
1772 }
1773 _temperatureExceededLimitWatchdog.at(motor).increment();
1774 }
1775 }
1776 else
1777 {
1778 _temperatureExceededLimitWatchdog.at(motor).clear();
1779 }
1780 }
1781 return true;
1782}
1783
1784
1785bool embObjMotionControl::getEntityName(uint32_t entityId, std::string &entityName)
1786{
1787 bool ret = getAxisNameRaw(entityId, entityName);
1788
1789 //since getAxisNameRaw set "ERROR" in entityName when an error occurred,
1790 //while this function has to return an empty string, I reset the entityName string
1791 if(!ret)
1792 {
1793 entityName.clear();
1794 }
1795 return ret;
1796
1797}
1798
1799
1800bool embObjMotionControl::getEncoderTypeName(uint32_t jomoId, eOmc_position_t pos, std::string &encoderTypeName)
1801{
1802 encoderTypeName.clear();
1803
1804 if ((jomoId >= 0) && (jomoId < _njoints))
1805 {
1806 switch (pos)
1807 {
1808 case eomc_pos_atjoint:
1809 encoderTypeName = eomc_encoder2string(_parsedCfgData.jointEncs[jomoId].type, eobool_true);
1810 break;
1811 case eomc_pos_atmotor:
1812 encoderTypeName = eomc_encoder2string(_parsedCfgData.motorEncs[jomoId].type, eobool_true);
1813 break;
1814 case eomc_pos_unknown:
1815 encoderTypeName = "UNKNOWN";
1816 break;
1817 case eomc_pos_none:
1818 default:
1819 encoderTypeName = "NONE";
1820 break;
1821 }
1822 return true;
1823 }
1824 else
1825 {
1826 encoderTypeName = "ERROR";
1827 return false;
1828 }
1829}
1830
1831bool embObjMotionControl::getEntityControlModeName(uint32_t entityId, eOenum08_t control_mode, std::string &controlModeName, eObool_t compact_string)
1832{
1833 controlModeName.clear();
1834
1835 if ((entityId>= 0) && (entityId< _njoints))
1836 {
1837 controlModeName = eomc_controlmode2string(control_mode, compact_string);
1838 return true;
1839 }
1840 else
1841 {
1842 controlModeName = eomc_controlmode2string(eomc_ctrlmval_unknownError, compact_string);
1843 return false;
1844 }
1845}
1846
1848
1849ReturnValue embObjMotionControl::getAvailablePidsRaw(int j, std::vector<PidControlTypeEnum>& avail)
1850{
1851 avail.clear();
1852 avail.push_back(PidControlTypeEnum::VOCAB_PIDTYPE_POSITION);
1853 avail.push_back(PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY);
1854 avail.push_back(PidControlTypeEnum::VOCAB_PIDTYPE_MIXED);
1855 avail.push_back(PidControlTypeEnum::VOCAB_PIDTYPE_POSITION_DIRECT);
1856 avail.push_back(PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY_DIRECT);
1857 avail.push_back(PidControlTypeEnum::VOCAB_PIDTYPE_TORQUE);
1858 avail.push_back(PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT);
1859 return ReturnValue_ok;
1860}
1861
1862ReturnValue embObjMotionControl::setPidRaw(const PidControlTypeEnum& pidtype, int j, const Pid &pid)
1863{
1864 if (isUnsupportedPidAlias(pidtype))
1865 {
1866 return ReturnValue_ok;
1867 }
1868
1869 eOprotTag_t tag;
1870 eOprot_entity_t ent = eoprot_entity_mc_joint; //by default I set the entity to joint, but for current pid it will be set to motor. I need to set the entity because in fw the pid parameters for joint and motor are stored in different structures and with different tags, thus I need to specify the correct entity and tag when I want to send the pid parameters to fw.
1871
1872 switch (pidtype)
1873 {
1874 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION:
1875 tag = eoprot_tag_mc_joint_config_pidtrajectory;
1876 break;
1877 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY:
1878 tag = eoprot_tag_mc_joint_config_pidtrajectory;
1879 break;
1880 case PidControlTypeEnum::VOCAB_PIDTYPE_TORQUE:
1881 tag = eoprot_tag_mc_joint_config_pidtorque;
1882 break;
1883 case PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT:
1884 ent = eoprot_entity_mc_motor;
1885 tag = eoprot_tag_mc_motor_config_pidcurrent;
1886 break;
1887 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION_DIRECT:
1888 tag = eoprot_tag_mc_joint_config_piddirect;
1889 break;
1890 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY_DIRECT:
1891 // IMPORTANT NOTE: We need to manage the velocity direct pid in a different way because in fw the velocity direct pid
1892 // can be configured to output either pwm or current, thus we need to check the output type before
1893 // send the pid parameters to fw, and set the correct tag and entity.
1894 return helper_setVelDirPidRaw(j, pid);
1895 break;
1896 case PidControlTypeEnum::VOCAB_PIDTYPE_MIXED:
1897 tag = eoprot_tag_mc_joint_config_pidtrajectory;
1898 break;
1899 default:
1900 const auto pidtypeVocab = static_cast<yarp::conf::vocab32_t>(pidtype);
1901 yError() << getBoardInfo() << "Invalid pidtype:"<< yarp::os::Vocab32::decode(pidtypeVocab) << "in "<< __YFUNCTION__;
1902 return ReturnValue_error_method_failed;
1903 }
1904
1905 eOprotID32_t protoId = eoprot_ID_get(eoprot_endpoint_motioncontrol, ent, j, tag);
1906 eOmc_PID_t outPid;
1907 Pid hwPid = pid;
1908
1909 copyPid_iCub2eo(&hwPid, &outPid);
1910
1911 if(false == _ethRes->setRemoteValue(protoId, &outPid))
1912 {
1913 yError() << "while setting position PIDs for " << getBoardInfo() << " joint " << j;
1914 return ReturnValue_error_method_failed;
1915 }
1916
1917 return ReturnValue_ok;
1918}
1919
1920ReturnValue embObjMotionControl::getPidRaw(const PidControlTypeEnum& pidtype, int axis, Pid *pid)
1921{
1922 if (isUnsupportedPidAlias(pidtype))
1923 {
1924 *pid = Pid();
1925 return ReturnValue_ok;
1926 }
1927
1928 eOprotTag_t tag;
1929 eOprot_entity_t ent = eoprot_entity_mc_joint; //by default I set the entity to joint, but for current pid it will be set to motor. I need to set the entity because in fw the pid parameters for joint and motor are stored in different structures and with different tags, thus I need to specify the correct entity and tag when I want to send the pid parameters to fw.
1930
1931 switch (pidtype)
1932 {
1933 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION:
1934 tag = eoprot_tag_mc_joint_config_pidtrajectory;
1935 break;
1936 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY:
1937 tag = eoprot_tag_mc_joint_config_pidtrajectory;
1938 break;
1939 case PidControlTypeEnum::VOCAB_PIDTYPE_TORQUE:
1940 tag = eoprot_tag_mc_joint_config_pidtorque;
1941 break;
1942 case PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT:
1943 ent = eoprot_entity_mc_motor;
1944 tag = eoprot_tag_mc_motor_config_pidcurrent;
1945 break;
1946 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION_DIRECT:
1947 tag = eoprot_tag_mc_joint_config_piddirect;
1948 break;
1949 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY_DIRECT:
1950 {
1951 return helper_getVelDirPidRaw(axis, pid);
1952 };
1953 break;
1954 case PidControlTypeEnum::VOCAB_PIDTYPE_MIXED:
1955 tag = eoprot_tag_mc_joint_config_pidtrajectory;
1956 break;
1957 default:
1958 const auto pidtypeVocab = static_cast<yarp::conf::vocab32_t>(pidtype);
1959 yError() << getBoardInfo() << "Invalid pidtype:"<< yarp::os::Vocab32::decode(pidtypeVocab) << "in "<< __YFUNCTION__;
1960 return ReturnValue_error_method_failed;
1961 }
1962
1963
1964
1965 eOprotID32_t protoId = eoprot_ID_get(eoprot_endpoint_motioncontrol, ent, axis, tag);
1966 uint16_t size;
1967 eOmc_PID_t eoPID = {0};
1968#ifdef NETWORK_PERFORMANCE_BENCHMARK
1969 double start = yarp::os::Time::now();
1970#endif
1971
1972 bool ret = askRemoteValue(protoId, &eoPID, size);
1973
1974#ifdef NETWORK_PERFORMANCE_BENCHMARK
1975 double end = yarp::os::Time::now();
1976 _responseTimingVerifier.tick(end-start, start);
1977#endif
1978
1979 if(!ret)
1980 {
1981 yError() << getBoardInfo() << __YFUNCTION__ << "failed for joint " << axis ;
1982 return ReturnValue_error_method_failed;
1983 }
1984
1985 copyPid_eo2iCub(&eoPID, pid);
1986
1987 return ReturnValue_ok;
1988}
1989
1990ReturnValue embObjMotionControl::setPidsRaw(const PidControlTypeEnum& pidtype, const Pid *pids)
1991{
1992 if (isUnsupportedPidAlias(pidtype))
1993 {
1994 return ReturnValue_ok;
1995 }
1996
1997 ReturnValue ret = ReturnValue_ok;
1998 for(int j=0; j< _njoints; j++)
1999 {
2000 ret &= setPidRaw(pidtype, j, pids[j]);
2001 }
2002 return ret;
2003}
2004
2005ReturnValue embObjMotionControl::setPidReferenceRaw(const PidControlTypeEnum& pidtype, int j, double ref)
2006{
2007 if (isUnsupportedPidAlias(pidtype))
2008 {
2009 return ReturnValue_ok;
2010 }
2011
2012 return YARP_METHOD_NOT_YET_IMPLEMENTED();
2013}
2014
2015ReturnValue embObjMotionControl::setPidReferencesRaw(const PidControlTypeEnum& pidtype, const double *refs)
2016{
2017 if (isUnsupportedPidAlias(pidtype))
2018 {
2019 return ReturnValue_ok;
2020 }
2021
2022 ReturnValue ret = ReturnValue_ok;
2023 for(int j=0, index=0; j< _njoints; j++, index++)
2024 {
2025 ret &= setPidReferenceRaw(pidtype, j, refs[index]);
2026 }
2027 return ret;
2028}
2029
2030ReturnValue embObjMotionControl::setPidErrorLimitRaw(const PidControlTypeEnum& pidtype, int j, double limit)
2031{
2032 if (isUnsupportedPidAlias(pidtype))
2033 {
2034 return ReturnValue_ok;
2035 }
2036
2037 return YARP_METHOD_NOT_YET_IMPLEMENTED();
2038}
2039
2040ReturnValue embObjMotionControl::setPidErrorLimitsRaw(const PidControlTypeEnum& pidtype, const double *limits)
2041{
2042 if (isUnsupportedPidAlias(pidtype))
2043 {
2044 return ReturnValue_ok;
2045 }
2046
2047 return YARP_METHOD_NOT_YET_IMPLEMENTED();
2048}
2049
2050ReturnValue embObjMotionControl::getPidErrorRaw(const PidControlTypeEnum& pidtype, int j, double *err)
2051{
2052 *err = 0;
2053 if (isUnsupportedPidAlias(pidtype))
2054 {
2055 return ReturnValue_ok;
2056 }
2057
2058 uint16_t size = 0;
2059 eOprotID32_t id32 = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_core);
2060 eOmc_joint_status_core_t jcore = {0};
2061 if(!_ethRes->getLocalValue(id32, &jcore))
2062 return ReturnValue_error_method_failed;
2063
2064 switch(pidtype)
2065 {
2066 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION:
2067 {
2068 if((eomc_controlmode_torque == jcore.modes.controlmodestatus) ||
2069 (eomc_controlmode_openloop == jcore.modes.controlmodestatus) ||
2070 (eomc_controlmode_current == jcore.modes.controlmodestatus))
2071 return ReturnValue_ok;
2072 else
2073 *err = (double) jcore.ofpid.generic.error1;
2074 }
2075 break;
2076
2077 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION_DIRECT:
2078 {
2079 *err=0; //not yet implemented
2080 YARP_METHOD_NOT_YET_IMPLEMENTED();
2081 }
2082 break;
2083
2084 case PidControlTypeEnum::VOCAB_PIDTYPE_TORQUE:
2085 {
2086 if ((eOmc_interactionmode_compliant == jcore.modes.interactionmodestatus) &&
2087 (eomc_controlmode_position == jcore.modes.controlmodestatus))
2088 {
2089 *err = (double) jcore.ofpid.complpos.errtrq;
2090 }
2091
2092 if(eomc_controlmode_torque == jcore.modes.controlmodestatus)
2093 {
2094 *err = (double) jcore.ofpid.torque.errtrq;
2095 }
2096 }
2097 break;
2098 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY:
2099 {
2100 *err = 0; //not yet implemented
2101 YARP_METHOD_NOT_YET_IMPLEMENTED();
2102 }
2103 break;
2104 case PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT:
2105 {
2106 *err = 0; //not yet implemented
2107 YARP_METHOD_NOT_YET_IMPLEMENTED();
2108 }
2109 break;
2110
2111 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY_DIRECT:
2112 {
2113 *err=0; //not yet implemented
2114 YARP_METHOD_NOT_YET_IMPLEMENTED();
2115 }
2116 break;
2117
2118 default:
2119 {
2120 const auto pidtypeVocab = static_cast<yarp::conf::vocab32_t>(pidtype);
2121 yError() << getBoardInfo() << "Invalid pidtype:"<< yarp::os::Vocab32::decode(pidtypeVocab) << "in "<< __YFUNCTION__;
2122 }
2123 break;
2124 }
2125 return ReturnValue_ok;
2126}
2127
2128ReturnValue embObjMotionControl::getPidErrorsRaw(const PidControlTypeEnum& pidtype, double *errs)
2129{
2130 if (isUnsupportedPidAlias(pidtype))
2131 {
2132 std::fill_n(errs, _njoints, 0.0);
2133 return ReturnValue_ok;
2134 }
2135
2136 ReturnValue ret = ReturnValue_ok;
2137 for(int j=0; j< _njoints; j++)
2138 {
2139 ret &= getPidErrorRaw(pidtype, j, &errs[j]);
2140 }
2141 return ret;
2142}
2143
2144ReturnValue embObjMotionControl::getPidsRaw(const PidControlTypeEnum& pidtype, Pid *pids)
2145{
2146 if (isUnsupportedPidAlias(pidtype))
2147 {
2148 std::fill_n(pids, _njoints, Pid());
2149 return ReturnValue_ok;
2150 }
2151
2152 eOprotTag_t tag;
2153 eOprot_entity_t ent = eoprot_entity_mc_joint; //by default I set the entity to joint, but for current pid it will be set to motor. I need to set the entity because in fw the pid parameters for joint and motor are stored in different structures and with different tags, thus I need to specify the correct entity and tag when I want to send the pid parameters to fw.
2154
2155 switch (pidtype)
2156 {
2157 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION:
2158 tag = eoprot_tag_mc_joint_config_pidtrajectory;
2159 break;
2160 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY:
2161 tag = eoprot_tag_mc_joint_config_pidtrajectory;
2162 break;
2163 case PidControlTypeEnum::VOCAB_PIDTYPE_TORQUE:
2164 tag = eoprot_tag_mc_joint_config_pidtorque;
2165 break;
2166 case PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT:
2167 ent = eoprot_entity_mc_motor;
2168 tag = eoprot_tag_mc_motor_config_pidcurrent;
2169 break;
2170 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION_DIRECT:
2171 tag = eoprot_tag_mc_joint_config_piddirect;
2172 break;
2173 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY_DIRECT:
2174 {
2175 return helper_getVelDirPidsRaw(pids);
2176 };
2177 break;
2178 case PidControlTypeEnum::VOCAB_PIDTYPE_MIXED:
2179 tag = eoprot_tag_mc_joint_config_pidtrajectory;
2180 break;
2181 default:
2182 const auto pidtypeVocab = static_cast<yarp::conf::vocab32_t>(pidtype);
2183 yError() << getBoardInfo() << "Invalid pidtype:"<< yarp::os::Vocab32::decode(pidtypeVocab) << "in "<< __YFUNCTION__;
2184 return ReturnValue_error_method_failed;
2185 }
2186
2187 std::vector<eOmc_PID_t> eoPIDList(_njoints);
2188 bool ret = askRemoteValues(eoprot_endpoint_motioncontrol, ent, tag, eoPIDList);
2189 if(!ret)
2190 {
2191 yError() << getBoardInfo() << __YFUNCTION__ << "failed " ;
2192 return ReturnValue_error_method_failed;
2193 }
2194
2195 for(int j=0; j<_njoints; j++)
2196 copyPid_eo2iCub(&eoPIDList[j], &pids[j]);
2197
2198 return ReturnValue_ok;
2199}
2200
2201ReturnValue embObjMotionControl::getPidReferenceRaw(const PidControlTypeEnum& pidtype, int j, double *ref)
2202{
2203 *ref = 0;
2204 if (isUnsupportedPidAlias(pidtype))
2205 {
2206 return ReturnValue_ok;
2207 }
2208
2209 eOprotID32_t id32 = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_core);
2210 eOmc_joint_status_core_t jcore = {0};
2211 if(!_ethRes->getLocalValue(id32, &jcore))
2212 return ReturnValue_error_method_failed;
2213
2214 switch (pidtype)
2215 {
2216 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION:
2217 {
2218 if((eomc_controlmode_torque == jcore.modes.controlmodestatus) ||
2219 (eomc_controlmode_openloop == jcore.modes.controlmodestatus) ||
2220 (eomc_controlmode_current == jcore.modes.controlmodestatus))
2221 { *ref = 0; yError() << getBoardInfo() << "Invalid getPidReferenceRaw() request for current control mode"; return ReturnValue_ok; }
2222 *ref = (double) jcore.ofpid.generic.reference1;
2223 }
2224 break;
2225 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION_DIRECT:
2226 {
2227 *ref=0;
2228 YARP_METHOD_NOT_YET_IMPLEMENTED();
2229 }
2230 break;
2231 case PidControlTypeEnum::VOCAB_PIDTYPE_TORQUE:
2232 {
2233 *ref = 0;
2234 YARP_METHOD_NOT_YET_IMPLEMENTED();
2235 }
2236 break;
2237 case PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT:
2238 {
2239 *ref=0;
2240 YARP_METHOD_NOT_YET_IMPLEMENTED();
2241 }
2242 break;
2243 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY:
2244 {
2245 *ref = 0;
2246 YARP_METHOD_NOT_YET_IMPLEMENTED();
2247 }
2248 break;
2249 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY_DIRECT:
2250 {
2251 *ref=0;
2252 YARP_METHOD_NOT_YET_IMPLEMENTED();
2253 }
2254 break;
2255 default:
2256 {
2257 *ref=0;
2258 const auto pidtypeVocab = static_cast<yarp::conf::vocab32_t>(pidtype);
2259 yError() << getBoardInfo() << "Invalid pidtype:"<< yarp::os::Vocab32::decode(pidtypeVocab) << "in "<< __YFUNCTION__;
2260 return ReturnValue_error_generic;
2261 }
2262 break;
2263 }
2264 return ReturnValue_ok;
2265}
2266
2267ReturnValue embObjMotionControl::getPidReferencesRaw(const PidControlTypeEnum& pidtype, double *refs)
2268{
2269 if (isUnsupportedPidAlias(pidtype))
2270 {
2271 std::fill_n(refs, _njoints, 0.0);
2272 return ReturnValue_ok;
2273 }
2274
2275 ReturnValue ret = ReturnValue_ok;
2276
2277 // just one joint at time, wait answer before getting to the next.
2278 // This is because otherwise too many msg will be placed into can queue
2279 for(int j=0; j< _njoints; j++)
2280 {
2281 ret &= getPidReferenceRaw(pidtype, j, &refs[j]);
2282 }
2283 return ret;
2284}
2285
2286ReturnValue embObjMotionControl::getPidErrorLimitRaw(const PidControlTypeEnum& pidtype, int j, double *limit)
2287{
2288 *limit = 0;
2289 if (isUnsupportedPidAlias(pidtype))
2290 {
2291 return ReturnValue_ok;
2292 }
2293
2294 return YARP_METHOD_NOT_YET_IMPLEMENTED();
2295}
2296
2297ReturnValue embObjMotionControl::getPidErrorLimitsRaw(const PidControlTypeEnum& pidtype, double *limits)
2298{
2299 if (isUnsupportedPidAlias(pidtype))
2300 {
2301 std::fill_n(limits, _njoints, 0.0);
2302 return ReturnValue_ok;
2303 }
2304
2305 return YARP_METHOD_NOT_YET_IMPLEMENTED();
2306}
2307
2308ReturnValue embObjMotionControl::resetPidRaw(const PidControlTypeEnum& pidtype, int j)
2309{
2310 if (isUnsupportedPidAlias(pidtype))
2311 {
2312 return ReturnValue_ok;
2313 }
2314
2315 return YARP_METHOD_NOT_YET_IMPLEMENTED();
2316}
2317
2318ReturnValue embObjMotionControl::disablePidRaw(const PidControlTypeEnum& pidtype, int j)
2319{
2320 if (isUnsupportedPidAlias(pidtype))
2321 {
2322 return ReturnValue_ok;
2323 }
2324
2325 return YARP_METHOD_DEPRECATED();
2326}
2327
2328ReturnValue embObjMotionControl::enablePidRaw(const PidControlTypeEnum& pidtype, int j)
2329{
2330 if (isUnsupportedPidAlias(pidtype))
2331 {
2332 return ReturnValue_ok;
2333 }
2334
2335 return YARP_METHOD_DEPRECATED();
2336}
2337
2338ReturnValue embObjMotionControl::setPidOffsetRaw(const PidControlTypeEnum& pidtype, int j, double v)
2339{
2340 if (isUnsupportedPidAlias(pidtype))
2341 {
2342 return ReturnValue_ok;
2343 }
2344
2345 return YARP_METHOD_NOT_YET_IMPLEMENTED();
2346}
2347
2349// Velocity control interface raw //
2351
2352ReturnValue embObjMotionControl::velocityMoveRaw(int j, double sp)
2353{
2354 yarp::dev::ControlModeEnum mode{};
2355 getControlModeRaw(j, mode);
2356 if( (mode != yarp::dev::ControlModeEnum::VOCAB_CM_VELOCITY) &&
2357 (mode != yarp::dev::ControlModeEnum::VOCAB_CM_MIXED) &&
2358 (mode != yarp::dev::ControlModeEnum::VOCAB_CM_IMPEDANCE_VEL) &&
2359 (mode != yarp::dev::ControlModeEnum::VOCAB_CM_IDLE))
2360 {
2361 if(_event_downsampler->canprint())
2362 {
2363 yError() << "velocityMoveRaw: skipping command because " << getBoardInfo() << " joint " << j << " is not in VOCAB_CM_VELOCITY mode";
2364 }
2365 return ReturnValue_ok;
2366 }
2367
2368 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_cmmnds_setpoint);
2369
2370 _ref_command_speeds[j] = sp ; // save internally the new value of speed.
2371
2372 eOmc_setpoint_t setpoint;
2373 setpoint.type = eomc_setpoint_velocity;
2374 setpoint.to.velocity.value = (eOmeas_velocity_t) S_32(_ref_command_speeds[j]);
2375 setpoint.to.velocity.withacceleration = (eOmeas_acceleration_t) S_32(_ref_accs[j]);
2376
2377
2378 if(false == _ethRes->setRemoteValue(protid, &setpoint))
2379 {
2380 yError()<< getBoardInfo() << "while setting velocity mode";
2381 return ReturnValue_error_method_failed;
2382 }
2383 return ReturnValue_ok;
2384}
2385
2386ReturnValue embObjMotionControl::velocityMoveRaw(const double *sp)
2387{
2388 ReturnValue ret = ReturnValue_ok;
2389
2390 for(int j=0; j<_njoints; j++)
2391 {
2392 ret &= velocityMoveRaw(j, sp[j]);
2393 }
2394
2395 return ret;
2396}
2397
2398
2400// Calibration control interface //
2402
2403ReturnValue embObjMotionControl::setCalibrationParametersRaw(int j, const CalibrationParameters& params)
2404{
2405 yTrace() << "setCalibrationParametersRaw for " << getBoardInfo() << "joint" << j;
2406
2407 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_cmmnds_calibration);
2408 eOmc_calibrator_t calib;
2409 memset(&calib, 0x00, sizeof(calib));
2410 calib.type = params.type;
2411
2412 switch (calib.type)
2413 {
2414 // muove -> amp+pid, poi calib
2415 case eomc_calibration_type0_hard_stops:
2416 calib.params.type0.pwmlimit = (int16_t)S_16(params.param1);
2417 calib.params.type0.velocity = (eOmeas_velocity_t)S_32(params.param2);
2418 calib.params.type0.calibrationZero = (int32_t)S_32(_measureConverter->posA2E(params.paramZero, j));
2419 break;
2420
2421 // fermo
2422 case eomc_calibration_type1_abs_sens_analog:
2423 calib.params.type1.position = (int16_t)S_16(params.param1);
2424 calib.params.type1.velocity = (eOmeas_velocity_t)S_32(params.param2);
2425 calib.params.type1.calibrationZero = (int32_t)S_32(_measureConverter->posA2E(params.paramZero, j));
2426 break;
2427
2428 // muove
2429 case eomc_calibration_type2_hard_stops_diff:
2430 calib.params.type2.pwmlimit = (int16_t)S_16(params.param1);
2431 calib.params.type2.velocity = (eOmeas_velocity_t)S_32(params.param2);
2432 calib.params.type2.calibrationZero = (int32_t)S_32(_measureConverter->posA2E(params.paramZero, j));
2433 break;
2434
2435 // muove
2436 case eomc_calibration_type3_abs_sens_digital:
2437 calib.params.type3.position = (int16_t)S_16(params.param1);
2438 calib.params.type3.velocity = (eOmeas_velocity_t)S_32(params.param2);
2439 calib.params.type3.offset = (int32_t)S_32(params.param3);
2440 calib.params.type3.calibrationZero = (int32_t)S_32(_measureConverter->posA2E(params.paramZero, j));
2441 break;
2442
2443 // muove
2444 case eomc_calibration_type4_abs_and_incremental:
2445 calib.params.type4.position = (int16_t)S_16(params.param1);
2446 calib.params.type4.velocity = (eOmeas_velocity_t)S_32(params.param2);
2447 calib.params.type4.maxencoder = (int32_t)S_32(params.param3);
2448 calib.params.type4.calibrationZero = (int32_t)S_32(_measureConverter->posA2E(params.paramZero, j));
2449 break;
2450
2451 // muove
2452 case eomc_calibration_type5_hard_stops:
2453 calib.params.type5.pwmlimit = (int32_t) S_32(params.param1);
2454 calib.params.type5.final_pos = (int32_t) S_32(params.param2);
2455 calib.params.type5.calibrationZero = (int32_t)S_32(_measureConverter->posA2E(params.paramZero, j));
2456 break;
2457
2458 // muove
2459 case eomc_calibration_type6_mais:
2460 calib.params.type6.position = (int32_t)S_32(params.param1);
2461 calib.params.type6.velocity = (int32_t)S_32(params.param2);
2462 calib.params.type6.current = (int32_t)S_32(params.param3);
2463 calib.params.type6.vmin = (int32_t)S_32(params.param4);
2464 calib.params.type6.vmax = (int32_t)S_32(params.param5);
2465 calib.params.type6.calibrationZero = (int32_t)S_32(_measureConverter->posA2E(params.paramZero, j));
2466 break;
2467
2468 // muove
2469 case eomc_calibration_type7_hall_sensor:
2470 calib.params.type7.position = (int32_t)S_32(params.param1);
2471 calib.params.type7.velocity = (int32_t)S_32(params.param2);
2472 //param3 is not used
2473 calib.params.type7.vmin = (int32_t)S_32(params.param4);
2474 calib.params.type7.vmax = (int32_t)S_32(params.param5);
2475 calib.params.type7.calibrationZero = (int32_t)S_32(_measureConverter->posA2E(params.paramZero, j));
2476 break;
2477
2478 //muove
2479 case eomc_calibration_type8_tripod_internal_hard_stop:
2480 calib.params.type8.pwmlimit = (int32_t) S_32(params.param1);
2481 calib.params.type8.max_delta = (int32_t) S_32(params.param2);
2482 calib.params.type8.calibrationZero = (int32_t)S_32(params.paramZero /* * _angleToEncoder[j] */);
2483 break;
2484
2485 case eomc_calibration_type9_tripod_external_hard_stop:
2486 calib.params.type9.pwmlimit = (int32_t) S_32(params.param1);
2487 calib.params.type9.max_delta = (int32_t) S_32(params.param2);
2488 calib.params.type9.calibrationZero = (int32_t)S_32(params.paramZero /* * _angleToEncoder[j] */);
2489 break;
2490
2491 case eomc_calibration_type10_abs_hard_stop:
2492 calib.params.type10.pwmlimit = (int32_t) S_32(params.param1);
2493 calib.params.type10.calibrationZero = (int32_t)S_32(_measureConverter->posA2E(params.paramZero, j));
2494 break;
2495
2496 case eomc_calibration_type11_cer_hands:
2497 calib.params.type11.offset0 = (int32_t)S_32(params.param1);
2498 calib.params.type11.offset1 = (int32_t)S_32(params.param2);
2499 calib.params.type11.offset2 = (int32_t)S_32(params.param3);
2500 calib.params.type11.cable_range = (int32_t)S_32(params.param4);
2501 calib.params.type11.pwm = (int32_t)S_32(params.param5);
2502 //calib.params.type11.calibrationZero = 32767;//(int32_t)S_32(params.paramZero * _angleToEncoder[j]);
2503 break;
2504
2505 case eomc_calibration_type12_absolute_sensor:
2506 calib.params.type12.rawValueAtZeroPos = (int32_t)S_32(params.param1);
2507 calib.params.type12.calibrationDelta = (int32_t)S_32(_measureConverter->posA2E(params.paramZero, j));
2508 break;
2509
2510 case eomc_calibration_type13_cer_hands_2:
2511 calib.params.type13.rawValueAtZeroPos0 = (int32_t)S_32(params.param1);
2512 calib.params.type13.rawValueAtZeroPos1 = (int32_t)S_32(params.param2);
2513 calib.params.type13.rawValueAtZeroPos2 = (int32_t)S_32(params.param3);
2514 calib.params.type13.rawValueAtZeroPos3 = (int32_t)S_32(params.param4);
2515 break;
2516
2517 case eomc_calibration_type14_qenc_hard_stop_and_fap:
2518 calib.params.type14.pwmlimit = (int32_t)S_32(params.param1);
2519 calib.params.type14.final_pos = (int32_t)S_32(params.param2);
2520 calib.params.type14.invertdirection = (uint8_t)U_32(params.param3);
2521 calib.params.type14.rotation = (int32_t)S_32(params.param4);
2522
2523 if (calib.params.type14.invertdirection != 0 && calib.params.type14.invertdirection != 1)
2524 {
2525 yError() << getBoardInfo() << "Error in param3 of calibartion type 14 for joint " << j << "Admitted values are: 0=FALSE and 1=TRUE";
2526 return ReturnValue_error_generic;
2527 }
2528
2529
2530 if(!checkCalib14RotationParam(calib.params.type14.rotation))
2531 {
2532 yError() << getBoardInfo() << "Error in param4 of calibartion type 14 for joint " << j << "Admitted values are: 0, 32768, 16384, -16384 [0, 180, 90, -90] in iCubDegree";
2533 return ReturnValue_error_generic;
2534 }
2535 calib.params.type14.offset = (int32_t)S_32(params.param5);
2536 calib.params.type14.calibrationZero = (int32_t)S_32(_measureConverter->posA2E(params.paramZero, j));
2537
2538 break;
2539
2540 default:
2541 yError() << getBoardInfo() << "joint" << j << "Calibration type unknown!! (embObjMotionControl)\n";
2542 return ReturnValue_error_generic;
2543 break;
2544 }
2545
2546 if (false == _ethRes->setRemoteValue(protid, &calib))
2547 {
2548 yError() << getBoardInfo() << "joint" << j << "while setting remote calibration parameters";
2549 return ReturnValue_error_method_failed;
2550 }
2551
2552
2553 return ReturnValue_ok;
2554}
2555
2556bool embObjMotionControl::checkCalib14RotationParam(int32_t calib_param4)
2557{
2558 eOmc_calib14_ROT_t urotation = eomc_int2calib14_ROT(calib_param4);
2559
2560 if (urotation == eOmc_calib14_ROT_zero ||
2561 urotation == eOmc_calib14_ROT_plus180 ||
2562 urotation == eOmc_calib14_ROT_plus090 ||
2563 urotation == eOmc_calib14_ROT_minus090)
2564 {
2565 return ReturnValue_ok;
2566 }
2567
2568 return false;
2569}
2570
2571ReturnValue embObjMotionControl::calibrateAxisWithParamsRaw(int j, unsigned int type, double p1, double p2, double p3)
2572{
2573 yTrace() << "calibrateRaw for" << getBoardInfo() << "joint" << j;
2574
2575 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_cmmnds_calibration);
2576 eOmc_calibrator_t calib;
2577 memset(&calib, 0x00, sizeof(calib));
2578 calib.type = type;
2579
2580 switch(type)
2581 {
2582 // muove -> amp+pid, poi calib
2583 case eomc_calibration_type0_hard_stops:
2584 calib.params.type0.pwmlimit = (int16_t) S_16(p1);
2585 calib.params.type0.velocity = (eOmeas_velocity_t) S_32(p2);
2586 break;
2587
2588 // fermo
2589 case eomc_calibration_type1_abs_sens_analog:
2590 calib.params.type1.position = (int16_t) S_16(p1);
2591 calib.params.type1.velocity = (eOmeas_velocity_t) S_32(p2);
2592 break;
2593
2594 // muove
2595 case eomc_calibration_type2_hard_stops_diff:
2596 calib.params.type2.pwmlimit = (int16_t) S_16(p1);
2597 calib.params.type2.velocity = (eOmeas_velocity_t) S_32(p2);
2598 break;
2599
2600 // muove
2601 case eomc_calibration_type3_abs_sens_digital:
2602 calib.params.type3.position = (int16_t) S_16(p1);
2603 calib.params.type3.velocity = (eOmeas_velocity_t) S_32(p2);
2604 calib.params.type3.offset = (int32_t) S_32(p3);
2605 break;
2606
2607 // muove
2608 case eomc_calibration_type4_abs_and_incremental:
2609 calib.params.type4.position = (int16_t) S_16(p1);
2610 calib.params.type4.velocity = (eOmeas_velocity_t) S_32(p2);
2611 calib.params.type4.maxencoder = (int32_t) S_32(p3);
2612 break;
2613
2614 default:
2615 yError() << getBoardInfo() << "joint" << j << "Calibration type unknown!! (embObjMotionControl)\n";
2616 return ReturnValue_error_generic;
2617 break;
2618 }
2619
2620 if (false == _ethRes->setRemoteValue(protid, &calib))
2621 {
2622 yError() << getBoardInfo() << "joint" << j << "while setting remote calibration parameters";
2623 return ReturnValue_error_method_failed;
2624 }
2625
2626 return ReturnValue_ok;
2627}
2628
2629
2630std::string embObjMotionControl::controlModeType2String(eOmc_controlmode_t type)
2631{
2632 return std::string (eomc_controlmode2string(/*(eOenum08_t)*/ type, true));
2633}
2634
2636{
2637 eOmc_joint_status_core_t jcore = {0};
2638 eOprotID32_t id32 = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, axis, eoprot_tag_mc_joint_status_core);
2639 if(!_ethRes->getLocalValue(id32, &jcore))
2640 {
2641 yError() << getBoardInfo() << "Failure of getLocalValue() for axis" << axis << "in "<< __YFUNCTION__;
2642 return ReturnValue_error_method_failed;
2643 }
2644
2645 eOmc_controlmode_t type = (eOmc_controlmode_t) jcore.modes.controlmodestatus;
2646 ReturnValue result = ReturnValue_error_generic;
2647 switch(type)
2648 {
2649 case eomc_controlmode_idle:
2650 return ((_parsedCfgData.maintenanceModeCfg.enableSkipRecalibration) ? ReturnValue_ok : ReturnValue_error_generic);
2651 case eomc_controlmode_calib:
2652 return ReturnValue_error_generic;
2653 case eomc_controlmode_hwFault:
2654 case eomc_controlmode_unknownError:
2655 case eomc_controlmode_notConfigured:
2656 case eomc_controlmode_configured:
2657 {
2658 yError() << getBoardInfo()<< "Unable to complete calibration: joint" << axis << " is in " << controlModeType2String(type) << " status in "<< __YFUNCTION__;
2659 return ReturnValue_error_generic;
2660 } ;
2661
2662 default: // if the control mode is no longer a calibration type, it means calibration ended
2663 return ReturnValue_ok;
2664 }
2665
2666}
2667
2669// Position control interface //
2671
2672ReturnValue embObjMotionControl::positionMoveRaw(int j, double ref)
2673{
2675 const auto& defaults = factory.getDefaults();
2676 if (yarp::os::Time::now()-_last_position_move_time[j] < defaults.maxPositionMoveInterval)
2677 {
2678 yWarning() << getBoardInfo() << "Performance warning: You are using positionMove commands at high rate (<"<< defaults.maxPositionMoveInterval*1000.0 <<" ms). Probably position control mode is not the right control mode to use.";
2679 }
2680 _last_position_move_time[j] = yarp::os::Time::now();
2681
2682 yarp::dev::ControlModeEnum mode{};
2683 getControlModeRaw(j, mode);
2684 if( (mode != yarp::dev::ControlModeEnum::VOCAB_CM_POSITION) &&
2685 (mode != yarp::dev::ControlModeEnum::VOCAB_CM_MIXED) &&
2686 (mode != yarp::dev::ControlModeEnum::VOCAB_CM_IMPEDANCE_POS) &&
2687 (mode != yarp::dev::ControlModeEnum::VOCAB_CM_IDLE))
2688 {
2689 if (_event_downsampler->canprint())
2690 {
2691 yError() << "positionMoveRaw: skipping command because " << getBoardInfo() << " joint " << j << " is not in VOCAB_CM_POSITION mode";
2692 }
2693 return ReturnValue_ok;
2694 }
2695
2696 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_cmmnds_setpoint);
2697 _ref_command_positions[j] = ref; // save internally the new value of pos.
2698
2699 eOmc_setpoint_t setpoint;
2700
2701 setpoint.type = (eOenum08_t) eomc_setpoint_position;
2702 setpoint.to.position.value = (eOmeas_position_t) S_32(_ref_command_positions[j]);
2703 setpoint.to.position.withvelocity = (eOmeas_velocity_t) S_32(_ref_speeds[j]);
2704
2705 return _ethRes->setRemoteValue(protid, &setpoint) ? ReturnValue_ok : ReturnValue_error_generic;
2706}
2707
2708ReturnValue embObjMotionControl::positionMoveRaw(const double *refs)
2709{
2710 bool ret = true;
2711
2712 for(int j=0, index=0; j< _njoints; j++, index++)
2713 {
2714 ret &= positionMoveRaw(j, refs[index]);
2715 }
2716 return ret ? ReturnValue_ok : ReturnValue_error_generic;
2717}
2718
2719ReturnValue embObjMotionControl::relativeMoveRaw(int j, double delta)
2720{
2721 return YARP_METHOD_NOT_YET_IMPLEMENTED();
2722}
2723
2724ReturnValue embObjMotionControl::relativeMoveRaw(const double *deltas)
2725{
2726 return YARP_METHOD_NOT_YET_IMPLEMENTED();
2727}
2728
2729
2730ReturnValue embObjMotionControl::checkMotionDoneRaw(int j, bool &flag)
2731{
2732 eObool_t ismotiondone = eobool_false;
2733 uint16_t size = 0;
2734
2735 eOprotID32_t id32 = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_core_modes_ismotiondone);
2736 if(false == askRemoteValue(id32, &ismotiondone, size))
2737 {
2738 yError () << "Failure of askRemoteValue() inside embObjMotionControl::checkMotionDoneRaw(j=" << j << ") for " << getBoardInfo();
2739 return ReturnValue_error_generic;
2740 }
2741
2742
2743 flag = ismotiondone; // eObool_t can have values only amongst: eobool_true (1) or eobool_false (0).
2744
2745 return ReturnValue_ok;
2746}
2747
2749{
2750 std::vector <eObool_t> ismotiondoneList(_njoints);
2751 bool ret = askRemoteValues(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, eoprot_tag_mc_joint_status_core_modes_ismotiondone, ismotiondoneList);
2752 if(false == ret)
2753 {
2754 yError () << "Failure of askRemoteValues() inside embObjMotionControl::checkMotionDoneRaw for all joints of" << getBoardInfo();
2755 return ReturnValue_error_generic;
2756 }
2757 flag=true;
2758 for(int j=0; j<_njoints; j++)
2759 {
2760 flag &= ismotiondoneList[j]; // eObool_t can have values only amongst: eobool_true (1) or eobool_false (0).
2761 }
2762 return ReturnValue_ok;
2763}
2764
2765ReturnValue embObjMotionControl::setTrajSpeedRaw(int j, double sp)
2766{
2767 // Velocity is expressed in iDegrees/s
2768 // save internally the new value of speed; it'll be used in the positionMove
2769 _ref_speeds[j] = sp;
2770 return ReturnValue_ok;
2771}
2772
2773ReturnValue embObjMotionControl::setTrajSpeedsRaw(const double *spds)
2774{
2775 // Velocity is expressed in iDegrees/s
2776 // save internally the new value of speed; it'll be used in the positionMove
2777 for(int j=0, index=0; j< _njoints; j++, index++)
2778 {
2779 setTrajSpeedRaw(j, spds[index]);
2780 }
2781 return ReturnValue_ok;
2782}
2783
2785{
2786 // Acceleration is expressed in iDegrees/s^2
2787 // save internally the new value of the acceleration; it'll be used in the velocityMove command
2788
2789 if (acc > 1e6)
2790 {
2791 _ref_accs[j ] = 1e6;
2792 }
2793 else if (acc < -1e6)
2794 {
2795 _ref_accs[j ] = -1e6;
2796 }
2797 else
2798 {
2799 _ref_accs[j ] = acc;
2800 }
2801
2802 return ReturnValue_ok;
2803}
2804
2806{
2807 // Acceleration is expressed in iDegrees/s^2
2808 // save internally the new value of the acceleration; it'll be used in the velocityMove command
2809 for(int j=0, index=0; j< _njoints; j++, index++)
2810 {
2811 if (accs[j] > 1e6)
2812 {
2813 _ref_accs[index] = 1e6;
2814 }
2815 else if (accs[j] < -1e6)
2816 {
2817 _ref_accs[index] = -1e6;
2818 }
2819 else
2820 {
2821 _ref_accs[index] = accs[j];
2822 }
2823 }
2824 return ReturnValue_ok;
2825}
2826
2827ReturnValue embObjMotionControl::getTrajSpeedRaw(int j, double *spd)
2828{
2829#if ASK_REFERENCE_TO_FIRMWARE
2830 *spd = _ref_speeds[j];
2831 //return YARP_METHOD_NOT_YET_IMPLEMENTED();
2832#else
2833 *spd = _ref_speeds[j];
2834#endif
2835 return ReturnValue_ok;
2836}
2837
2839{
2840 std::copy(_ref_speeds.begin(), _ref_speeds.end(), spds);
2841 return ReturnValue_ok;
2842}
2843
2845{
2846 *acc = _ref_accs[j];
2847 return ReturnValue_ok;
2848}
2849
2851{
2852 std::copy(_ref_accs.begin(), _ref_accs.end(), accs);
2853 return ReturnValue_ok;
2854}
2855
2857{
2858 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_cmmnds_stoptrajectory);
2859
2860 eObool_t stop = eobool_true;
2861
2862 return _ethRes->setRemoteValue(protid, &stop) ? ReturnValue_ok : ReturnValue_error_method_failed;
2863}
2864
2866{
2867 bool ret = true;
2868 for(int j=0; j< _njoints; j++)
2869 {
2870 ret &= stopRaw(j);
2871 }
2872 return ret ? ReturnValue_ok : ReturnValue_error_generic;
2873}
2874
2875
2877// Position control2 interface //
2879
2880ReturnValue embObjMotionControl::positionMoveRaw(const int n_joint, const int *joints, const double *refs)
2881{
2882 ReturnValue ret = ReturnValue_ok;
2883 for(int j=0; j<n_joint; j++)
2884 {
2885 ret &= positionMoveRaw(joints[j], refs[j]);
2886 }
2887 return ret;
2888}
2889
2890ReturnValue embObjMotionControl::relativeMoveRaw(const int n_joint, const int *joints, const double *deltas)
2891{
2892 ReturnValue ret = ReturnValue_ok;
2893 for(int j=0; j<n_joint; j++)
2894 {
2895 ret &= relativeMoveRaw(joints[j], deltas[j]);
2896 }
2897 return ret;
2898}
2899
2900ReturnValue embObjMotionControl::checkMotionDoneRaw(const std::vector<int>& joints, bool& flag)
2901{
2902
2903 //1) first of all, check if all joints number are ok
2904 for(int j=0; j<joints.size(); j++)
2905 {
2906 if((joints[j] >= _njoints) || (joints[j] < 0))
2907 {
2908 yError() << getBoardInfo() << ":checkMotionDoneRaw required for not existing joint ( " << joints[j] << ")";
2909 return ReturnValue_error_generic;
2910 }
2911 }
2912
2913 //2) ask check motion done for all my joints
2914 std::vector <eObool_t> ismotiondoneList(_njoints);
2915 bool ret = askRemoteValues(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, eoprot_tag_mc_joint_status_core_modes_ismotiondone, ismotiondoneList);
2916 if(false == ret)
2917 {
2918 yError () << getBoardInfo() << "Failure of askRemoteValues() inside embObjMotionControl::checkMotionDoneRaw for a group of joint"; getBoardInfo();
2919 return ReturnValue_error_generic;
2920 }
2921
2922 //3) verify only the given joints
2923 bool tot_val = true;
2924 for(int j=0; j<joints.size(); j++)
2925 {
2926 tot_val &= ismotiondoneList[joints[j]];
2927 }
2928
2929 flag = tot_val;
2930 return ReturnValue_ok;
2931
2932}
2933
2934ReturnValue embObjMotionControl::setTrajSpeedsRaw(const int n_joint, const int *joints, const double *spds)
2935{
2936 bool ret = true;
2937 for(int j=0; j<n_joint; j++)
2938 {
2939 ret = ret &&setTrajSpeedRaw(joints[j], spds[j]);
2940 }
2941 return ret ? ReturnValue_ok : ReturnValue_error_generic;
2942}
2943
2944ReturnValue embObjMotionControl::setTrajAccelerationsRaw(const int n_joint, const int *joints, const double *accs)
2945{
2946 bool ret = true;
2947 for(int j=0; j<n_joint; j++)
2948 {
2949 ret = ret &&setTrajAccelerationRaw(joints[j], accs[j]);
2950 }
2951 return ret ? ReturnValue_ok : ReturnValue_error_generic;
2952}
2953
2954ReturnValue embObjMotionControl::getTrajSpeedsRaw(const int n_joint, const int *joints, double *spds)
2955{
2956 bool ret = true;
2957 for(int j=0; j<n_joint; j++)
2958 {
2959 ret = ret && getTrajSpeedRaw(joints[j], &spds[j]);
2960 }
2961 return ret ? ReturnValue_ok : ReturnValue_error_generic;
2962}
2963
2964ReturnValue embObjMotionControl::getTrajAccelerationsRaw(const int n_joint, const int *joints, double *accs)
2965{
2966 bool ret = true;
2967 for(int j=0; j<n_joint; j++)
2968 {
2969 ret = ret && getTrajAccelerationRaw(joints[j], &accs[j]);
2970 }
2971 return ret ? ReturnValue_ok : ReturnValue_error_generic;
2972}
2973
2974ReturnValue embObjMotionControl::stopRaw(const int n_joint, const int *joints)
2975{
2976 bool ret = true;
2977 for(int j=0; j<n_joint; j++)
2978 {
2979 ret = ret &&stopRaw(joints[j]);
2980 }
2981 return ret ? ReturnValue_ok : ReturnValue_error_generic;
2982}
2983
2985
2986// ControlMode
2987
2988typedef struct
2989{
2990 std::vector<PidInfo> trj;
2991 std::vector<PidInfo> mix;
2992 std::vector<PidInfo> dir_pos;
2993 std::vector<PidInfo> dir_vel;
2994 std::vector<TrqPidInfo> trq;
2995 std::vector<PidInfo> cur;
2996 std::vector<PidInfo> vel;
2998
2999ReturnValue embObjMotionControl::getAvailableControlModesRaw(int j, std::vector<yarp::dev::SelectableControlModeEnum>& avail)
3000{
3001 avail.clear();
3002 if (_parsedCfgData.pidControllers.trj[j].enabled)
3003 avail.push_back(yarp::dev::SelectableControlModeEnum::VOCAB_CM_POSITION);
3004
3005 if (_parsedCfgData.pidControllers.mix[j].enabled)
3006 avail.push_back(yarp::dev::SelectableControlModeEnum::VOCAB_CM_MIXED);
3007
3008 if (_parsedCfgData.pidControllers.dir_pos[j].enabled)
3009 avail.push_back(yarp::dev::SelectableControlModeEnum::VOCAB_CM_POSITION_DIRECT);
3010
3011 if (_parsedCfgData.pidControllers.dir_vel[j].enabled)
3012 avail.push_back(yarp::dev::SelectableControlModeEnum::VOCAB_CM_VELOCITY_DIRECT);
3013
3014
3015 if (_parsedCfgData.pidControllers.trq[j].enabled)
3016 avail.push_back(yarp::dev::SelectableControlModeEnum::VOCAB_CM_TORQUE);
3017
3018 if( _parsedCfgData.pidControllers.cur[j].enabled)
3019 avail.push_back(yarp::dev::SelectableControlModeEnum::VOCAB_CM_CURRENT);
3020
3021 if( _parsedCfgData.pidControllers.vel[j].enabled)
3022 avail.push_back(yarp::dev::SelectableControlModeEnum::VOCAB_CM_VELOCITY);
3023
3024
3025 avail.push_back(yarp::dev::SelectableControlModeEnum::VOCAB_CM_IMPEDANCE_POS);
3026 avail.push_back(yarp::dev::SelectableControlModeEnum::VOCAB_CM_PWM);
3027 avail.push_back(yarp::dev::SelectableControlModeEnum::VOCAB_CM_IDLE);
3028 avail.push_back(yarp::dev::SelectableControlModeEnum::VOCAB_CM_FORCE_IDLE);
3029
3030 return ReturnValue_ok;
3031}
3032
3033ReturnValue embObjMotionControl::getControlModeRaw(int j, yarp::dev::ControlModeEnum& mode)
3034{
3035 eOmc_joint_status_core_t jcore = {0};
3036 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_core);
3037 if(! _ethRes->getLocalValue(protid, &jcore))
3038 return ReturnValue_error_generic;
3039
3040 eOmc_controlmode_t type = (eOmc_controlmode_t) jcore.modes.controlmodestatus;
3041
3042 mode = static_cast<yarp::dev::ControlModeEnum>(controlModeStatusConvert_embObj2yarp(type));
3043 return ReturnValue_ok;
3044}
3045
3046// IControl Mode 2
3047ReturnValue embObjMotionControl::getControlModesRaw(std::vector<yarp::dev::ControlModeEnum>& mode)
3048{
3049 if(mode.size() != _njoints)
3050 {
3051 yError() << "getControlModesRaw: size of input vector does not match number of joints for " << getBoardInfo();
3052 return ReturnValue_error_generic;
3053 }
3054 bool ret = true;
3055 for(int j=0; j< _njoints; j++)
3056 {
3057 ret = ret && getControlModeRaw(j, mode[j]);
3058 }
3059 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3060}
3061
3062ReturnValue embObjMotionControl::getControlModesRaw(const std::vector<int>& joints, std::vector<yarp::dev::ControlModeEnum>& modes)
3063{
3064 modes.resize(joints.size()); //TODO: is this resize necessary?
3065 bool ret = true;
3066 for(size_t j=0; j< joints.size(); j++)
3067 {
3068 ret = ret && getControlModeRaw(joints[j], modes[j]);
3069 }
3070 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3071}
3072
3073
3074
3075// marco.accame: con alberto cardellino abbiamo parlato della correttezza di effettuare la verifica di quanto imposto (in setControlModeRaw() ed affini)
3076// andando a rileggere il valore nella scheda eth fino a che esso non sia quello atteso. si deve fare oppure no?
3077// con il control mode il can ora lo fa ma e' giusto? era cosi' anche in passato?
3078ReturnValue embObjMotionControl::setControlModeRaw(int j, yarp::dev::SelectableControlModeEnum _mode)
3079{
3080 bool ret = true;
3081 eOenum08_t controlmodecommand = 0;
3082 int modeInt = static_cast<int>(_mode);
3083
3084 if((modeInt == VOCAB_CM_TORQUE) && (_parsedCfgData.pidControllers.trq[j].enabled == false))
3085 {
3086 yError()<<"Torque control is disabled for joint "<< j <<"in " << getBoardInfo() << ". Check your configuration parameters ";
3087 return ReturnValue_error_generic;
3088 }
3089
3090 if((modeInt == VOCAB_CM_VELOCITY_DIRECT) && (_parsedCfgData.pidControllers.dir_vel[j].enabled == false))
3091 {
3092 yError()<<"Velocity direct control is disabled for joint "<< j <<"in " << getBoardInfo() << ". Check your configuration parameters ";
3093 return ReturnValue_error_generic;
3094 }
3095
3096 if((modeInt == VOCAB_CM_POSITION_DIRECT) && (_parsedCfgData.pidControllers.dir_pos[j].enabled == false))
3097 {
3098 yError()<<"Position direct control is disabled for joint "<< j <<"in " << getBoardInfo() << ". Check your configuration parameters ";
3099 return ReturnValue_error_generic;
3100 }
3101
3102 if(!controlModeCommandConvert_yarp2embObj(modeInt, controlmodecommand) )
3103 {
3104 yError() << "SetControlMode: received unknown control mode for " << getBoardInfo() << " joint " << j << " mode " << Vocab32::decode(modeInt);
3105 return ReturnValue_error_generic;
3106 }
3107
3108 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_cmmnds_controlmode);
3109 if(false == _ethRes->setRemoteValue(protid, &controlmodecommand) )
3110 {
3111 yError() << "setControlModeRaw failed for " << getBoardInfo() << " joint " << j << " mode " << Vocab32::decode(modeInt);
3112 return ReturnValue_error_generic;
3113 }
3114
3115 if(!checkRemoteControlModeStatus(j, modeInt))
3116 {
3117 yError() << "In embObjMotionControl::setControlModeRaw(j=" << j << ", mode=" << yarp::os::Vocab32::decode(modeInt).c_str() << ") for " << getBoardInfo() << " has failed checkRemoteControlModeStatus()";
3118 return ReturnValue_error_generic;
3119 }
3120
3121 return ReturnValue_ok;
3122}
3123
3124
3125ReturnValue embObjMotionControl::setControlModesRaw(const std::vector<int>& joints, const std::vector<yarp::dev::SelectableControlModeEnum>& modes)
3126{
3127 ReturnValue ret = ReturnValue_ok;
3128 for (size_t i = 0; i < joints.size(); ++i)
3129 {
3130 ret &= setControlModeRaw(joints[i], modes[i]);
3131 }
3132 return ret;
3133}
3134
3135ReturnValue embObjMotionControl::setControlModesRaw(const std::vector<yarp::dev::SelectableControlModeEnum> &modes)
3136{
3137 ReturnValue ret = ReturnValue_ok;
3138 for (int i = 0; i < _njoints; ++i)
3139 {
3140 ret &= setControlModeRaw(i, modes[i]);
3141 }
3142 return ret;
3143}
3144
3146
3147ReturnValue embObjMotionControl::setEncoderRaw(int j, double val)
3148{
3149 return YARP_METHOD_NOT_YET_IMPLEMENTED();
3150}
3151
3152ReturnValue embObjMotionControl::setEncodersRaw(const double *vals)
3153{
3154 return YARP_METHOD_NOT_YET_IMPLEMENTED();
3155}
3156
3158{
3159 return YARP_METHOD_NOT_YET_IMPLEMENTED();
3160}
3161
3163{
3164 return YARP_METHOD_NOT_YET_IMPLEMENTED();
3165}
3166
3167ReturnValue embObjMotionControl::getEncoderRaw(int j, double *value)
3168{
3169 eOmc_joint_status_core_t core;
3170 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_core);
3171
3172 bool ret = _ethRes->getLocalValue(protid, &core);
3173
3174 if(ret)
3175 {
3176 *value = (double) core.measures.meas_position;
3177 }
3178 else
3179 {
3180 yError() << "embObjMotionControl while reading encoder";
3181 *value = 0;
3182 }
3183
3184 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3185}
3186
3188{
3189 bool ret = true;
3190 for(int j=0; j< _njoints; j++)
3191 {
3192 ret &= getEncoderRaw(j, &encs[j]);
3193
3194 }
3195 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3196}
3197
3198ReturnValue embObjMotionControl::getEncoderSpeedRaw(int j, double *sp)
3199{
3200 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_core);
3201 eOmc_joint_status_core_t core;
3202 *sp = 0;
3203 if(!_ethRes->getLocalValue(protid, &core))
3204 {
3205 return ReturnValue_error_generic;
3206 }
3207 // extract requested data from status
3208 *sp = (double) core.measures.meas_velocity;
3209 return ReturnValue_ok;
3210}
3211
3213{
3214 bool ret = true;
3215 for(int j=0; j< _njoints; j++)
3216 {
3217 ret &= getEncoderSpeedRaw(j, &spds[j]);
3218 }
3219 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3220}
3221
3223{
3224 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_core);
3225 eOmc_joint_status_core_t core;
3226 *acc = 0;
3227 if(! _ethRes->getLocalValue(protid, &core))
3228 {
3229 return ReturnValue_error_generic;
3230 }
3231 *acc = (double) core.measures.meas_acceleration;
3232 return ReturnValue_ok;
3233}
3234
3236{
3237 bool ret = true;
3238 for(int j=0; j< _njoints; j++)
3239 {
3240 ret &= getEncoderAccelerationRaw(j, &accs[j]);
3241 }
3242 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3243}
3244
3246
3247ReturnValue embObjMotionControl::getEncodersTimedRaw(double *encs, double *stamps)
3248{
3249 bool ret = getEncodersRaw(encs);
3250 std::lock_guard<std::mutex> lck(_mutex);
3251 for(int i=0; i<_njoints; i++)
3252 stamps[i] = _encodersStamp[i];
3253 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3254}
3255
3256ReturnValue embObjMotionControl::getEncoderTimedRaw(int j, double *encs, double *stamp)
3257{
3258 bool ret = getEncoderRaw(j, encs);
3259 std::lock_guard<std::mutex> lck(_mutex);
3260 *stamp = _encodersStamp[j];
3261 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3262}
3263
3265
3267{
3268 *num=_njoints;
3269 return ReturnValue_ok;
3270}
3271
3272ReturnValue embObjMotionControl::setMotorEncoderRaw(int m, const double val)
3273{
3274 return YARP_METHOD_NOT_YET_IMPLEMENTED();
3275}
3276
3277ReturnValue embObjMotionControl::setMotorEncodersRaw(const double *vals)
3278{
3279 return YARP_METHOD_NOT_YET_IMPLEMENTED();
3280}
3281
3283{
3284 return YARP_METHOD_NOT_YET_IMPLEMENTED();
3285}
3286
3288{
3289 return YARP_METHOD_NOT_YET_IMPLEMENTED();
3290}
3291
3293{
3294 return YARP_METHOD_NOT_YET_IMPLEMENTED();
3295}
3296
3298{
3299 return YARP_METHOD_NOT_YET_IMPLEMENTED();
3300}
3301
3302ReturnValue embObjMotionControl::getMotorEncoderRaw(int m, double *value)
3303{
3304 eOmc_motor_status_basic_t status;
3305 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, m, eoprot_tag_mc_motor_status_basic);
3306
3307 bool ret = _ethRes->getLocalValue(protid, &status);
3308 if(ret)
3309 {
3310 *value = (double) status.mot_position;
3311 }
3312 else
3313 {
3314 yError() << "embObjMotionControl while reading motor encoder position";
3315 *value = 0;
3316 }
3317
3318 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3319}
3320
3322{
3323 bool ret = true;
3324 for(int j=0; j< _njoints; j++)
3325 {
3326 ret &= getMotorEncoderRaw(j, &encs[j]);
3327
3328 }
3329 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3330}
3331
3333{
3334 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, m, eoprot_tag_mc_motor_status_basic);
3335 eOmc_motor_status_basic_t tmpMotorStatus;
3336 bool ret = _ethRes->getLocalValue(protid, &tmpMotorStatus);
3337 if(ret)
3338 {
3339 *sp = (double) tmpMotorStatus.mot_velocity;
3340 }
3341 else
3342 {
3343 yError() << "embObjMotionControl while reading motor encoder speed";
3344 *sp = 0;
3345 }
3346 return ReturnValue_ok;
3347}
3348
3350{
3351 bool ret = true;
3352 for(int j=0; j< _njoints; j++)
3353 {
3354 ret &= getMotorEncoderSpeedRaw(j, &spds[j]);
3355 }
3356 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3357}
3358
3360{
3361 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, m, eoprot_tag_mc_motor_status_basic);
3362 eOmc_motor_status_basic_t tmpMotorStatus;
3363 bool ret = _ethRes->getLocalValue(protid, &tmpMotorStatus);
3364 if(ret)
3365 {
3366 *acc = (double) tmpMotorStatus.mot_acceleration;
3367 }
3368 else
3369 {
3370 yError() << "embObjMotionControl while reading motor encoder acceleration";
3371 *acc = 0;
3372 }
3373 return ReturnValue_ok;
3374}
3375
3377{
3378 bool ret = true;
3379 for(int j=0; j< _njoints; j++)
3380 {
3381 ret &= getMotorEncoderAccelerationRaw(j, &accs[j]);
3382 }
3383 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3384}
3385
3386ReturnValue embObjMotionControl::getMotorEncodersTimedRaw(double *encs, double *stamps)
3387{
3388 bool ret = getMotorEncodersRaw(encs);
3389 std::lock_guard<std::mutex> lck(_mutex);
3390 for(int i=0; i<_njoints; i++)
3391 stamps[i] = _encodersStamp[i];
3392 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3393}
3394
3395ReturnValue embObjMotionControl::getMotorEncoderTimedRaw(int m, double *encs, double *stamp)
3396{
3397 bool ret = getMotorEncoderRaw(m, encs);
3398 std::lock_guard<std::mutex> lck(_mutex);
3399 *stamp = _encodersStamp[m];
3400 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3401}
3402
3403
3405
3407{
3408 return YARP_METHOD_DEPRECATED();
3409}
3410
3412{
3413 return YARP_METHOD_DEPRECATED();
3414}
3415
3416ReturnValue embObjMotionControl::getCurrentRaw(int j, double *value)
3417{
3418 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_status_basic);
3419 eOmc_motor_status_basic_t tmpMotorStatus;
3420 bool ret = _ethRes->getLocalValue(protid, &tmpMotorStatus);
3421
3422 *value = (double) tmpMotorStatus.mot_current;
3423 return ReturnValue_ok;
3424}
3425
3427{
3428 bool ret = true;
3429 for(int j=0; j< _njoints; j++)
3430 {
3431 ret &= getCurrentRaw(j, &vals[j]);
3432 }
3433 return ret ? ReturnValue_ok : ReturnValue_error_generic;
3434}
3435
3436ReturnValue embObjMotionControl::setMaxCurrentRaw(int j, double val)
3437{
3438 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config_currentlimits);
3439 uint16_t size;
3440 eOmc_current_limits_params_t currentlimits = {0};
3441
3442 if(!askRemoteValue(protid, &currentlimits, size))
3443 {
3444 yError() << "embObjMotionControl::setMaxCurrentRaw() could not read max current for " << getBoardInfo() << "joint " << j;
3445 return ReturnValue_error_generic;
3446 }
3447
3448 //set current overload
3449 currentlimits.overloadCurrent = (eOmeas_current_t) S_16(val);
3450
3451 //send new values
3452 return _ethRes->setRemoteValue(protid, &currentlimits) ? ReturnValue_ok : ReturnValue_error_generic;
3453}
3454
3455ReturnValue embObjMotionControl::getMaxCurrentRaw(int j, double *val)
3456{
3457 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config_currentlimits);
3458 uint16_t size;
3459 eOmc_current_limits_params_t currentlimits = {0};
3460 *val = 0;
3461
3462 if(!askRemoteValue(protid, &currentlimits, size))
3463 {
3464 yError() << "embObjMotionControl::getMaxCurrentRaw() could not read max current for " << getBoardInfo() << "joint " << j;
3465 return ReturnValue_error_generic;
3466 }
3467
3468 *val = (double) currentlimits.overloadCurrent;
3469
3470 return ReturnValue_ok;
3471}
3472
3473ReturnValue embObjMotionControl::getAmpStatusRaw(int j, int *st)
3474{
3475 yarp::dev::ControlModeEnum mode{};
3476 if(!getControlModeRaw(j, mode))
3477 return ReturnValue_error_method_failed;
3478
3479 switch (static_cast<int>(mode))
3480 { case VOCAB_CM_IDLE:
3481 case VOCAB_CM_HW_FAULT:
3482 case VOCAB_CM_NOT_CONFIGURED:
3483 case VOCAB_CM_CONFIGURED:
3484 case VOCAB_CM_UNKNOWN:
3485 (*st) = 0; // disabled
3486 return ReturnValue_ok;
3487
3488 default:
3489 (*st) = 1; // disabled
3490 return ReturnValue_ok;
3491 };
3492
3493}
3494
3496{
3497 ReturnValue ret = ReturnValue_ok;
3498 for(int j=0; j<_njoints; j++)
3499 ret &= getAmpStatusRaw(j, &sts[j]);
3500
3501 return ret;
3502}
3503
3504#ifdef IMPLEMENT_DEBUG_INTERFACE
3505//----------------------------------------------\\
3506// Debug interface
3507//----------------------------------------------\\
3508
3509bool embObjMotionControl::setParameterRaw(int j, unsigned int type, double value) { return YARP_METHOD_NOT_YET_IMPLEMENTED(); }
3510bool embObjMotionControl::getParameterRaw(int j, unsigned int type, double* value) { return YARP_METHOD_NOT_YET_IMPLEMENTED(); }
3511bool embObjMotionControl::getDebugParameterRaw(int j, unsigned int index, double* value) { return YARP_METHOD_NOT_YET_IMPLEMENTED(); }
3512bool embObjMotionControl::setDebugParameterRaw(int j, unsigned int index, double value) { return YARP_METHOD_NOT_YET_IMPLEMENTED(); }
3513bool embObjMotionControl::setDebugReferencePositionRaw(int j, double value) { return YARP_METHOD_NOT_YET_IMPLEMENTED(); }
3514bool embObjMotionControl::getDebugReferencePositionRaw(int j, double* value) { return YARP_METHOD_NOT_YET_IMPLEMENTED();}
3515
3516#endif //IMPLEMENT_DEBUG_INTERFACE
3517
3518// Limit interface
3519ReturnValue embObjMotionControl::setPosLimitsRaw(int j, double min, double max)
3520{
3521 bool ret = true;
3522 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_config_userlimits);
3523
3524 eOmeas_position_limits_t limits;
3525 limits.max = (eOmeas_position_t) S_32(max);
3526 limits.min = (eOmeas_position_t) S_32(min);
3527
3528 ret = _ethRes->setRemoteValue(protid, &limits);
3529
3530
3531 if(!ret)
3532 {
3533 yError() << "while setting position limits for joint" << j << " \n";
3534 }
3535 return ReturnValue_ok;
3536}
3537
3538ReturnValue embObjMotionControl::getPosLimitsRaw(int j, double *min, double *max)
3539{
3540 eOmeas_position_limits_t limits;
3541 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_config_userlimits);
3542 uint16_t size;
3543
3544 if(! askRemoteValue(protoid, &limits, size))
3545 return ReturnValue_error_method_failed;
3546
3548 const auto& defaults = factory.getDefaults();
3549 // TODO: is it correct to apply the delta to the limits read from the firmware?
3550 *min = (double)limits.min + defaults.jointPosLimitsDelta;
3551 *max = (double)limits.max - defaults.jointPosLimitsDelta;
3552 return ReturnValue_ok;
3553}
3554
3555ReturnValue embObjMotionControl::getGearboxRatioRaw(int j, double *gearbox)
3556{
3557 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config);
3558 uint16_t size;
3559 eOmc_motor_config_t motor_cfg;
3560 if(! askRemoteValue(protoid, &motor_cfg, size))
3561 return ReturnValue_error_generic;
3562
3563 // refresh cached value when reading data from the EMS
3564 *gearbox = (double)motor_cfg.gearbox_M2J;
3565
3566 return ReturnValue_ok;
3567}
3568
3569ReturnValue embObjMotionControl::setGearboxRatioRaw(int j, const double val)
3570{
3571 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config);
3572 uint16_t size;
3573 eOmc_motor_config_t motor_cfg = {0};
3574
3575
3576 if(!askRemoteValue(protoid, &motor_cfg, size))
3577 {
3578 yError() << "setGearboxRatioRaw: failed to GET motor config for joint" << j;
3579 return ReturnValue_error_method_failed;
3580 }
3581
3582 motor_cfg.gearbox_M2J = (double)val;
3583
3584 // Now, write the modified configuration back
3585 if(false == _ethRes->setRemoteValue(protoid, &motor_cfg))
3586 {
3587 yError() << "setGearboxRatioRaw: failed to SET motor config for joint" << j;
3588 return ReturnValue_error_method_failed;
3589 }
3590
3591 return ReturnValue_ok;
3592}
3593
3594bool embObjMotionControl::getRotorLimitsRaw(int j, double *rotorMin, double *rotorMax)
3595{
3596 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config);
3597 uint16_t size;
3598 eOmc_motor_config_t motor_cfg;
3599 if(! askRemoteValue(protoid, &motor_cfg, size))
3600 return false;
3601 *rotorMax = (double)( motor_cfg.limitsofrotor.max);
3602 *rotorMin = (double)( motor_cfg.limitsofrotor.min);
3603 return true;
3604}
3605
3607{
3608 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_config);
3609 uint16_t size;
3610 eOmc_joint_config_t joint_cfg;
3611 if(! askRemoteValue(protoid, &joint_cfg, size))
3612 return false;
3613
3614 // refresh cached value when reading data from the EMS
3615 type = (int)joint_cfg.tcfiltertype;
3616 return true;
3617}
3618
3620{
3621 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config);
3622 uint16_t size;
3623 eOmc_motor_config_t motor_cfg;
3624 if(! askRemoteValue(protoid, &motor_cfg, size))
3625 return false;
3626
3627 // refresh cached value when reading data from the EMS
3628 rotres = (double)motor_cfg.rotorEncoderResolution;
3629
3630 return ReturnValue_ok;
3631}
3632
3634{
3635 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_config);
3636 uint16_t size;
3637 eOmc_joint_config_t joint_cfg;
3638 if(! askRemoteValue(protoid, &joint_cfg, size))
3639 return false;
3640
3641 // refresh cached value when reading data from the EMS
3642 jntres = (double)joint_cfg.jntEncoderResolution;
3643
3644 return true;
3645}
3646
3648{
3649 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_config);
3650 uint16_t size;
3651 eOmc_joint_config_t joint_cfg;
3652 if(! askRemoteValue(protoid, &joint_cfg, size))
3653 return false;
3654
3655 // refresh cached value when reading data from the EMS
3656 type = (int)joint_cfg.jntEncoderType;
3657
3658 return true;
3659}
3660
3662{
3663 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config);
3664 uint16_t size;
3665 eOmc_motor_config_t motor_cfg;
3666 if(! askRemoteValue(protoid, &motor_cfg, size))
3667 return false;
3668
3669 // refresh cached value when reading data from the EMS
3670 type = (int)motor_cfg.rotorEncoderType;
3671
3672 return true;
3673}
3674
3676{
3677 yError("getKinematicMJRaw not yet implemented");
3678 return false;
3679}
3680
3682{
3683 // refresh cached value when reading data from the EMS
3684 ret = "NONE";
3685 if (_parsedCfgData.temperatureSensorsVector.at(j)->getType() == motor_temperature_sensor_pt100)
3686 {
3687 ret = "PT100";
3688 }
3689 else if (_parsedCfgData.temperatureSensorsVector.at(j)->getType() == motor_temperature_sensor_pt1000)
3690 {
3691 ret = "PT1000";
3692 }
3693 else
3694 {
3695 ret = "NONE";
3696 }
3697
3698 return true;
3699}
3700
3702{
3703 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config);
3704 uint16_t size;
3705 eOmc_motor_config_t motor_cfg;
3706 if(! askRemoteValue(protoid, &motor_cfg, size))
3707 return false;
3708
3709 // refresh cached value when reading data from the EMS
3710 ret = (int)motor_cfg.hasTempSensor;
3711
3712 return true;
3713}
3714
3716{
3717 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config);
3718 uint16_t size;
3719 eOmc_motor_config_t motor_cfg;
3720 if(! askRemoteValue(protoid, &motor_cfg, size))
3721 return false;
3722
3723 // refresh cached value when reading data from the EMS
3724 ret = (int)motor_cfg.hasHallSensor;
3725
3726 return true;
3727}
3728
3730{
3731 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config);
3732 uint16_t size;
3733 eOmc_motor_config_t motor_cfg;
3734 if(! askRemoteValue(protoid, &motor_cfg, size))
3735 return false;
3736
3737 // refresh cached value when reading data from the EMS
3738 ret = (int)motor_cfg.hasRotorEncoder;
3739
3740 return true;
3741}
3742
3744{
3745 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config);
3746 uint16_t size;
3747 eOmc_motor_config_t motor_cfg;
3748 if(! askRemoteValue(protoid, &motor_cfg, size))
3749 return false;
3750
3751 // refresh cached value when reading data from the EMS
3752 ret = (int)motor_cfg.hasRotorEncoderIndex;
3753
3754 return true;
3755}
3756
3758{
3759 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config);
3760
3761 uint16_t size;
3762 eOmc_motor_config_t motor_cfg;
3763 if(! askRemoteValue(protoid, &motor_cfg, size))
3764 return false;
3765
3766 // refresh cached value when reading data from the EMS
3767 poles = (int)motor_cfg.motorPoles;
3768
3769 return true;
3770}
3771
3772bool embObjMotionControl::getRotorIndexOffsetRaw(int j, double& rotorOffset)
3773{
3774 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config);
3775 uint16_t size;
3776 eOmc_motor_config_t motor_cfg;
3777 if(! askRemoteValue(protoid, &motor_cfg, size))
3778 return false;
3779
3780 // refresh cached value when reading data from the EMS
3781 rotorOffset = (double)motor_cfg.rotorIndexOffset;
3782
3783 return true;
3784}
3785
3786ReturnValue embObjMotionControl::getAxisNameRaw(int axis, std::string& name)
3787{
3788 if (axis >= 0 && axis < _njoints)
3789 {
3790 name = _parsedCfgData.axesInfo[axis].name;
3791 return ReturnValue_ok;
3792 }
3793 else
3794 {
3795 name = "ERROR";
3796 return ReturnValue::return_code::return_value_error_input_out_of_bounds;
3797 }
3798}
3799
3800ReturnValue embObjMotionControl::getJointTypeRaw(int axis, yarp::dev::JointTypeEnum& type)
3801{
3802 if (axis >= 0 && axis < _njoints)
3803 {
3804 type = _parsedCfgData.axesInfo[axis].type;
3805 return ReturnValue_ok;
3806 }
3807 else
3808 {
3809 return ReturnValue_error_generic;
3810 }
3811}
3812
3813bool embObjMotionControl::getJointDeadZoneRaw(int j, double &jntDeadZone)
3814{
3815 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_config);
3816 uint16_t size;
3817 eOmc_joint_config_t joint_cfg;
3818 if(! askRemoteValue(protoid, &joint_cfg, size))
3819 return false;
3820
3821 // refresh cached value when reading data from the EMS
3822 jntDeadZone = _measureConverter->posE2A((double)joint_cfg.deadzone, _parsedCfgData.axisMap[j]);
3823
3824 return true;
3825}
3826
3827// IRemoteVariables
3828ReturnValue embObjMotionControl::getRemoteVariableRaw(std::string key, yarp::os::Bottle& val)
3829{
3830 val.clear();
3831 if (key == "kinematic_mj")
3832 {
3833 // Return the reduced kinematic_mj matrix considering only the joints actually exposed to the user
3834 Bottle& ret = val.addList();
3835
3836 eOmn_serv_type_t mc_serv_type = (eOmn_serv_type_t)_parsedCfgData.serviceConfig.ethservice.configuration.type;
3837 if(iNeedCouplingsInfo())
3838 {
3839 for (int r=0; r<_njoints; r++)
3840 {
3841 for (int c = 0; c < _njoints; c++)
3842 {
3843 // matrixJ2M is stored as row major in the eomc_couplingInfo_t,
3844 // and kinematic_mj is returned as a row major serialization as well
3845 ret.addFloat64(_parsedCfgData.couplingInfo.matrixJ2M[4 * r + c]);
3846 }
3847 }
3848 }
3849 else
3850 {
3851 ret.addFloat64(0.0);
3852 }
3853 return ReturnValue_ok;
3854 }
3855 else if (key == "encoders")
3856 {
3857 Bottle& r = val.addList(); for (int i = 0; i < _njoints; i++) { r.addFloat64(_measureConverter->posA2E(1.0, i)); }
3858 return ReturnValue_ok;
3859 }
3860 else if (key == "rotorEncoderResolution")
3861 {
3862 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { double tmp = 0; getRotorEncoderResolutionRaw(i, tmp); r.addFloat64(tmp); }
3863 return ReturnValue_ok;
3864 }
3865 else if (key == "jointEncoderResolution")
3866 {
3867 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { double tmp = 0; getJointEncoderResolutionRaw(i, tmp); r.addFloat64(tmp); }
3868 return ReturnValue_ok;
3869 }
3870 else if (key == "gearbox_M2J")
3871 {
3872 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { double tmp=0; getGearboxRatioRaw(i, &tmp); r.addFloat64(tmp); }
3873 return ReturnValue_ok;
3874 }
3875 else if (key == "gearbox_E2J")
3876 {
3877 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { double tmp=0; getGerabox_E2J(i, &tmp); r.addFloat64(tmp); }
3878 return ReturnValue_ok;
3879 }
3880 else if (key == "hasHallSensor")
3881 {
3882 Bottle& r = val.addList(); for (int i = 0; i < _njoints; i++) { int tmp = 0; getHasHallSensorRaw(i, tmp); r.addInt32(tmp); }
3883 return ReturnValue_ok;
3884 }
3885 else if (key == "hasTempSensor")
3886 {
3887 Bottle& r = val.addList(); for (int i = 0; i < _njoints; i++) { int tmp = 0; getHasTempSensorsRaw(i, tmp); r.addInt32(tmp); }
3888 return ReturnValue_ok;
3889 }
3890 else if (key == "TemperatureSensorType")
3891 {
3892 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { std::string tmp = ""; getTemperatureSensorTypeRaw(i, tmp); r.addString(tmp); }
3893 return ReturnValue_ok;
3894 }
3895 else if (key == "hasRotorEncoder")
3896 {
3897 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { int tmp = 0; getHasRotorEncoderRaw(i, tmp); r.addInt32(tmp); }
3898 return ReturnValue_ok;
3899 }
3900 else if (key == "hasRotorEncoderIndex")
3901 {
3902 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { int tmp = 0; getHasRotorEncoderIndexRaw(i, tmp); r.addInt32(tmp); }
3903 return ReturnValue_ok;
3904 }
3905 else if (key == "rotorIndexOffset")
3906 {
3907 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { double tmp = 0; getRotorIndexOffsetRaw(i, tmp); r.addFloat64(tmp); }
3908 return ReturnValue_ok;
3909 }
3910 else if (key == "motorPoles")
3911 {
3912 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { int tmp = 0; getMotorPolesRaw(i, tmp); r.addInt32(tmp); }
3913 return ReturnValue_ok;
3914 }
3915 else if (key == "pidCurrentKp")
3916 {
3917 Bottle& r = val.addList(); for (int i = 0; i < _njoints; i++) { Pid p; getPidRaw(PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT, i, &p); r.addFloat64(p.kp); }
3918 return ReturnValue_ok;
3919 }
3920 else if (key == "pidCurrentKi")
3921 {
3922 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { Pid p; getPidRaw(PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT, i, &p); r.addFloat64(p.ki); }
3923 return ReturnValue_ok;
3924 }
3925 else if (key == "pidCurrentShift")
3926 {
3927 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { Pid p; getPidRaw(PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT, i, &p); r.addFloat64(p.scale); }
3928 return ReturnValue_ok;
3929 }
3930 else if (key == "pidCurrentOutput")
3931 {
3932 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { Pid p; getPidRaw(PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT, i, &p); r.addFloat64(p.max_output); }
3933 return ReturnValue_ok;
3934 }
3935 else if (key == "jointEncoderType")
3936 {
3937 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++)
3938 {
3939 int t; string s;
3940 getJointEncoderTypeRaw(i, t); uint8_t tt = t; bool b = EncoderType_eo2iCub(&tt, &s);
3941 if (b == false)
3942 {
3943 yError("Invalid jointEncoderType");
3944 }
3945 r.addString(s);
3946 }
3947 return ReturnValue_ok;
3948 }
3949 else if (key == "rotorEncoderType")
3950 {
3951 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++)
3952 {
3953 int t; string s;
3954 getRotorEncoderTypeRaw(i, t); uint8_t tt = t; bool b = EncoderType_eo2iCub(&tt, &s);
3955 if (b == false)
3956 {
3957 yError("Invalid motorEncoderType");
3958 }
3959 r.addString(s);
3960 }
3961 return ReturnValue_ok;
3962 }
3963 else if (key == "coulombThreshold")
3964 {
3965 val.addString("not implemented yet");
3966 return ReturnValue_ok;
3967 }
3968 else if (key == "torqueControlFilterType")
3969 {
3970 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { int t; getTorqueControlFilterType(i, t); r.addFloat64(t); }
3971 return ReturnValue_ok;
3972 }
3973 else if (key == "torqueControlEnabled")
3974 {
3975
3976 Bottle& r = val.addList();
3977 for(int i = 0; i<_njoints; i++)
3978 {
3979 r.addInt32((int)_parsedCfgData.pidControllers.trq[i].enabled );
3980 }
3981 return ReturnValue_ok;
3982 }
3983 else if (key == "PWMLimit")
3984 {
3985 Bottle& r = val.addList(); for (int i = 0; i< _njoints; i++) { double tmp = 0; getPWMLimitRaw(i, &tmp); r.addFloat64(tmp); }
3986 return ReturnValue_ok;
3987 }
3988 else if (key == "motOverloadCurr")
3989 {
3990 Bottle& r = val.addList(); for (int i = 0; i< _njoints; i++) { double tmp = 0; getMaxCurrentRaw(i, &tmp); r.addFloat64(tmp); }
3991 return ReturnValue_ok;
3992 }
3993 else if (key == "motNominalCurr")
3994 {
3995 Bottle& r = val.addList(); for (int i = 0; i< _njoints; i++) { double tmp = 0; getNominalCurrentRaw(i, &tmp); r.addFloat64(tmp); }
3996 return ReturnValue_ok;
3997 }
3998 else if (key == "motPeakCurr")
3999 {
4000 Bottle& r = val.addList(); for (int i = 0; i< _njoints; i++) { double tmp = 0; getPeakCurrentRaw(i, &tmp); r.addFloat64(tmp); }
4001 return ReturnValue_ok;
4002 }
4003 else if (key == "PowerSuppVoltage")
4004 {
4005 Bottle& r = val.addList(); for (int i = 0; i< _njoints; i++) { double tmp = 0; getPowerSupplyVoltageRaw(i, &tmp); r.addFloat64(tmp); }
4006 return ReturnValue_ok;
4007 }
4008 else if (key == "rotorMax")
4009 {
4010 double tmp1, tmp2;
4011 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { double tmp = 0; getRotorLimitsRaw(i, &tmp1, &tmp2); r.addFloat64(tmp2); }
4012 return ReturnValue_ok;
4013 }
4014 else if (key == "rotorMin")
4015 {
4016 double tmp1, tmp2;
4017 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { double tmp = 0; getRotorLimitsRaw(i, &tmp1, &tmp2); r.addFloat64(tmp1); }
4018 return ReturnValue_ok;
4019 }
4020 else if (key == "jointMax")
4021 {
4022 double tmp1, tmp2;
4023 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { double tmp = 0; getPosLimitsRaw(i, &tmp1, &tmp2); r.addFloat64(tmp2); }
4024 return ReturnValue_ok;
4025 }
4026 else if (key == "jointMin")
4027 {
4028 double tmp1, tmp2;
4029 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { double tmp = 0; getPosLimitsRaw(i, &tmp1, &tmp2); r.addFloat64(tmp1); }
4030 return ReturnValue_ok;
4031 }
4032 else if (key == "jointEncTolerance")
4033 {
4034 double tmp1;
4035 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { double tmp = 0; getJointEncTolerance(i, &tmp1); r.addFloat64(tmp1); }
4036 return ReturnValue_ok;
4037 }
4038 else if (key == "motorEncTolerance")
4039 {
4040 double tmp1;
4041 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { double tmp = 0; getMotorEncTolerance(i, &tmp1); r.addFloat64(tmp1); }
4042 return ReturnValue_ok;
4043 }
4044 else if (key == "jointDeadZone")
4045 {
4046 double tmp1;
4047 Bottle& r = val.addList(); for (int i = 0; i<_njoints; i++) { double tmp = 0; getJointDeadZoneRaw(i, tmp1); r.addFloat64(tmp1); }
4048 return ReturnValue_ok;
4049 }
4050 else if (key == "readonly_position_PIDraw")
4051 {
4052 Bottle& r = val.addList();
4053 for (int i = 0; i < _njoints; i++)
4054 { Pid p;
4055 getPidRaw(PidControlTypeEnum::VOCAB_PIDTYPE_POSITION, i, &p);
4056 char buff[1000];
4057 snprintf(buff, 1000, "J %d : kp %+3.3f ki %+3.3f kd %+3.3f maxint %+3.3f maxout %+3.3f off %+3.3f scale %+3.3f kff %+3.3f", i, p.kp, p.ki, p.kd, p.max_int, p.max_output, p.offset, p.scale, p.kff);
4058 r.addString(buff);
4059 }
4060 return ReturnValue_ok;
4061 }
4062 else if (key == "readonly_velocity_PIDraw")
4063 {
4064 Bottle& r = val.addList();
4065 for (int i = 0; i < _njoints; i++)
4066 { Pid p; getPidRaw(PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY, i, &p);
4067 char buff[1000];
4068 snprintf(buff, 1000, "J %d : kp %+3.3f ki %+3.3f kd %+3.3f maxint %+3.3f maxout %+3.3f off %+3.3f scale %+3.3f kff %+3.3f", i, p.kp, p.ki, p.kd, p.max_int, p.max_output, p.offset, p.scale, p.kff);
4069 r.addString(buff);
4070 }
4071 return ReturnValue_ok;
4072 }
4073 else if (key == "readonly_torque_PIDraw")
4074 {
4075 Bottle& r = val.addList();
4076 for (int i = 0; i < _njoints; i++)
4077 { Pid p; getPidRaw(PidControlTypeEnum::VOCAB_PIDTYPE_TORQUE, i, &p);
4078 char buff[1000];
4079 snprintf(buff, 1000, "J %d : kp %+3.3f ki %+3.3f kd %+3.3f maxint %+3.3f maxout %+3.3f off %+3.3f scale %+3.3f kff %+3.3f", i, p.kp, p.ki, p.kd, p.max_int, p.max_output, p.offset, p.scale, p.kff);
4080 r.addString(buff);
4081 }
4082 return ReturnValue_ok;
4083 }
4084 else if (key == "readonly_current_PIDraw")
4085 {
4086 Bottle& r = val.addList();
4087 for (int i = 0; i < _njoints; i++)
4088 { Pid p; getPidRaw(PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT, i, &p);
4089 char buff[1000];
4090 snprintf(buff, 1000, "J %d : kp %+3.3f ki %+3.3f kd %+3.3f maxint %+3.3f maxout %+3.3f off %+3.3f scale %+3.3f kff %+3.3f", i, p.kp, p.ki, p.kd, p.max_int, p.max_output, p.offset, p.scale, p.kff);
4091 r.addString(buff);
4092 }
4093 return ReturnValue_ok;
4094 }
4095 else if (key == "readonly_llspeed_PIDraw")
4096 {
4097 Bottle& r = val.addList();
4098 for (int i = 0; i < _njoints; i++)
4099 {
4100 Pid p; getPidRaw(PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY, i, &p);
4101 char buff[1000];
4102 snprintf(buff, 1000, "J %d : kp %+3.3f ki %+3.3f kd %+3.3f maxint %+3.3f maxout %+3.3f off %+3.3f scale %+3.3f kff %+3.3f", i, p.kp, p.ki, p.kd, p.max_int, p.max_output, p.offset, p.scale, p.kff);
4103 r.addString(buff);
4104 }
4105 return ReturnValue_ok;
4106 }
4107 else if (key == "readonly_motor_torque_params_raw")
4108 {
4109 Bottle& r = val.addList();
4110 for (int i = 0; i < _njoints; i++)
4111 {
4112 MotorTorqueParameters params;
4113 getMotorTorqueParamsRaw(i, &params);
4114 char buff[1000];
4115 snprintf(buff, 1000, "J %d : bemf %+3.3f bemf_scale %+3.3f ktau %+3.3f ktau_scale %+3.3f viscousPos %+3.3f viscousNeg %+3.3f coulombPos %+3.3f coulombNeg %+3.3f velocityThres %+3.3f", i, params.bemf, params.bemf_scale, params.ktau, params.ktau_scale, params.viscousPos, params.viscousNeg, params.coulombPos, params.coulombNeg, params.velocityThres);
4116 r.addString(buff);
4117 }
4118 return ReturnValue_ok;
4119 }
4120 yWarning("getRemoteVariable(): Unknown variable %s", key.c_str());
4121 return ReturnValue_error_generic;
4122}
4123
4124ReturnValue embObjMotionControl::setRemoteVariableRaw(std::string key, const yarp::os::Bottle& val)
4125{
4126 string s1 = val.toString();
4127 if (val.size() != _njoints)
4128 {
4129 yWarning("setRemoteVariable(): Protocol error %s", s1.c_str());
4130 return ReturnValue_error_generic;
4131 }
4132
4133 if (key == "kinematic_mj")
4134 {
4135 yWarning("setRemoteVariable(): Impossible to set kinematic_mj parameter at runtime.");
4136 return ReturnValue_error_generic;
4137 }
4138// else if (key == "rotor")
4139// {
4140// for (int i = 0; i < _njoints; i++) _rotorEncoderRes[i] = val.get(i).asInt32();//this operation has none effect on motor controlelr, so i remove it
4141// return true;
4142// }
4143// else if (key == "gearbox_M2J")
4144// {
4145// for (int i = 0; i < _njoints; i++) _gearbox_M2J[i] = val.get(i).asFloat64();//this operation has none effect on motor controlelr, so i remove it
4146// return true;
4147// }
4148 else if (key == "PWMLimit")
4149 {
4150 for (int i = 0; i < _njoints; i++) setPWMLimitRaw(i, val.get(i).asFloat64());
4151 return ReturnValue_ok;
4152 }
4153 //disabled for used safety
4154#if 0
4155 else if (key == "jointMax")
4156 {
4157 double min, max;
4158 for (int i = 0; i < _njoints; i++)
4159 {
4160 getPosLimitsRaw(i, &min, &max);
4161 setLimitsRaw(i, min, val.get(i).asFloat64());
4162 }
4163 return ReturnValue_ok;
4164 }
4165 else if (key == "jointMin")
4166 {
4167 double min, max;
4168 for (int i = 0; i < _njoints; i++)
4169 {
4170 getPosLimitsRaw(i, &min, &max);
4171 setLimitsRaw(i, val.get(i).asFloat64(), max);
4172 }
4173 }
4174#endif
4175 yWarning("setRemoteVariable(): Unknown variable %s", key.c_str());
4176 return ReturnValue_error_generic;
4177}
4178
4179ReturnValue embObjMotionControl::getRemoteVariablesListRaw(yarp::os::Bottle* listOfKeys)
4180{
4181 listOfKeys->clear();
4182 listOfKeys->addString("kinematic_mj");
4183 listOfKeys->addString("encoders");
4184 listOfKeys->addString("gearbox_M2J");
4185 listOfKeys->addString("gearbox_E2J");
4186 listOfKeys->addString("hasHallSensor");
4187 listOfKeys->addString("hasTempSensor");
4188 listOfKeys->addString("TemperatureSensorType");
4189 listOfKeys->addString("hasRotorEncoder");
4190 listOfKeys->addString("hasRotorEncoderIndex");
4191 listOfKeys->addString("rotorIndexOffset");
4192 listOfKeys->addString("rotorEncoderResolution");
4193 listOfKeys->addString("jointEncoderResolution");
4194 listOfKeys->addString("motorPoles");
4195 listOfKeys->addString("pidCurrentKp");
4196 listOfKeys->addString("pidCurrentKi");
4197 listOfKeys->addString("pidCurrentShift");
4198 listOfKeys->addString("pidCurrentOutput");
4199 listOfKeys->addString("coulombThreshold");
4200 listOfKeys->addString("torqueControlFilterType");
4201 listOfKeys->addString("jointEncoderType");
4202 listOfKeys->addString("rotorEncoderType");
4203 listOfKeys->addString("PWMLimit");
4204 listOfKeys->addString("motOverloadCurr");
4205 listOfKeys->addString("motNominalCurr");
4206 listOfKeys->addString("motPeakCurr");
4207 listOfKeys->addString("PowerSuppVoltage");
4208 listOfKeys->addString("rotorMax");
4209 listOfKeys->addString("rotorMin");
4210 listOfKeys->addString("jointMax");
4211 listOfKeys->addString("jointMin");
4212 listOfKeys->addString("jointEncTolerance");
4213 listOfKeys->addString("motorEncTolerance");
4214 listOfKeys->addString("jointDeadZone");
4215 listOfKeys->addString("readonly_position_PIDraw");
4216 listOfKeys->addString("readonly_velocity_PIDraw");
4217 listOfKeys->addString("readonly_current_PIDraw");
4218 listOfKeys->addString("readonly_torque_PIDraw");
4219 listOfKeys->addString("readonly_motor_torque_params_raw");
4220 return ReturnValue_ok;
4221}
4222
4223// IControlLimits2
4224ReturnValue embObjMotionControl::setVelLimitsRaw(int axis, double min, double max)
4225{
4226 return YARP_METHOD_NOT_YET_IMPLEMENTED();
4227}
4228
4229ReturnValue embObjMotionControl::getVelLimitsRaw(int axis, double *min, double *max)
4230{
4231 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, axis, eoprot_tag_mc_joint_config);
4232 uint16_t size;
4233 eOmc_joint_config_t joint_cfg;
4234 if(! askRemoteValue(protoid, &joint_cfg, size))
4235 return ReturnValue_error_method_failed;
4236
4237 *max = joint_cfg.maxvelocityofjoint;
4238 *min = 0;
4239
4240 return ReturnValue_ok;
4241}
4242
4243
4244 //IVirtualAnalogSensor Interface
4246{
4247 return VAS_status::VAS_OK;
4248};
4249
4251{
4252 return _njoints;
4253};
4254
4256{
4257 bool ret = true;
4258
4259 for(int j=0; j< _njoints; j++)
4260 {
4261 ret = ret && updateVirtualAnalogSensorMeasure(j, fTorques[j]);
4262 }
4263 return ret;
4264}
4265
4266bool embObjMotionControl::updateVirtualAnalogSensorMeasure(int userLevel_jointNumber, double &fTorque)
4267{
4268 int j = _parsedCfgData.axisMap[userLevel_jointNumber];
4269
4270 eOmeas_torque_t meas_torque = 0;
4271 static double curr_time = Time::now();
4272 static int count_saturation=0;
4273
4274 meas_torque = (eOmeas_torque_t) S_32(_measureConverter->trqN2S(fTorque, j));
4275
4276 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_inputs_externallymeasuredtorque);
4277// We don't need anymore to cache locally because ems board broadcast its torque value in joint status core
4278// // i write also locally because i want to read it back later on inside getTorqueRaw()
4279// _ethRes->setLocalValue(protoid, &meas_torque);
4280
4281 // and i want also to send it to the board
4282 return _ethRes->setRemoteValue(protoid, &meas_torque);
4283}
4284
4285// end IVirtualAnalogSensor //
4286
4287
4288// Torque control
4289ReturnValue embObjMotionControl::getTorqueRaw(int j, double *t)
4290{
4291 eOmc_joint_status_core_t jstatus;
4292 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_core);
4293 bool ret = _ethRes->getLocalValue(protoid, &jstatus);
4294 *t = (double) _measureConverter->trqS2N(jstatus.measures.meas_torque, j);
4295 return ret ? ReturnValue_ok : ReturnValue_error_method_failed;
4296}
4297
4299{
4300 bool ret = true;
4301 for(int j=0; j<_njoints; j++)
4302 ret = ret && getTorqueRaw(j, &t[j]);
4303 return ReturnValue_ok;
4304}
4305
4306ReturnValue embObjMotionControl::getTorqueRangeRaw(int j, double *min, double *max)
4307{
4308 //return YARP_METHOD_NOT_YET_IMPLEMENTED();
4309 return ReturnValue_ok;
4310}
4311
4312ReturnValue embObjMotionControl::getTorqueRangesRaw(double *min, double *max)
4313{
4314 //return YARP_METHOD_NOT_YET_IMPLEMENTED();
4315 return ReturnValue_ok;
4316}
4317
4318ReturnValue embObjMotionControl::setRefTorquesRaw(const double *t)
4319{
4320 bool ret = true;
4321 for(int j=0; j<_njoints && ret; j++)
4322 ret &= setRefTorqueRaw(j, t[j]);
4323 return ret ? ReturnValue_ok : ReturnValue_error_method_failed;
4324}
4325
4326ReturnValue embObjMotionControl::setRefTorqueRaw(int j, double t)
4327{
4328 eOmc_setpoint_t setpoint;
4329 setpoint.type = (eOenum08_t) eomc_setpoint_torque;
4330 setpoint.to.torque.value = (eOmeas_torque_t) S_32(t);
4331
4332 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_cmmnds_setpoint);
4333 return _ethRes->setRemoteValue(protid, &setpoint) ? ReturnValue_ok : ReturnValue_error_method_failed;
4334}
4335
4336ReturnValue embObjMotionControl::setRefTorquesRaw(const int n_joint, const int *joints, const double *t)
4337{
4338 bool ret = true;
4339 for(int j=0; j< n_joint; j++)
4340 {
4341 ret &= setRefTorqueRaw(joints[j], t[j]);
4342 }
4343 return ret ? ReturnValue_ok : ReturnValue_error_method_failed;
4344}
4345
4347{
4348 bool ret = true;
4349 for(int j=0; j<_njoints && ret; j++)
4350 ret &= getRefTorqueRaw(j, &t[j]);
4351 return ret ? ReturnValue_ok : ReturnValue_error_method_failed;
4352}
4353
4354ReturnValue embObjMotionControl::getRefTorqueRaw(int j, double *t)
4355{
4356 eOprotID32_t id32 = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_core);
4357 eOmc_joint_status_core_t jcore = {0};
4358 *t =0 ;
4359
4360
4361 if(!_ethRes->getLocalValue(id32, &jcore))
4362 {
4363 yError() << "embObjMotionControl::getRefTorqueRaw() could not read pid torque reference pos for " << getBoardInfo() << "joint " << j;
4364 return ReturnValue_error_method_failed;
4365 }
4366
4367 if ((eOmc_interactionmode_compliant == jcore.modes.interactionmodestatus) &&
4368 (eomc_controlmode_position == jcore.modes.controlmodestatus))
4369 {
4370 *t = (double) jcore.ofpid.complpos.reftrq;
4371 }
4372
4373 if(eomc_controlmode_torque == jcore.modes.controlmodestatus)
4374 {
4375 *t = (double) jcore.ofpid.torque.reftrq;
4376 }
4377
4378 return ReturnValue_ok;
4379}
4380
4381ReturnValue embObjMotionControl::getImpedanceRaw(int j, double *stiffness, double *damping)
4382{
4383 eOmc_impedance_t val;
4384
4385 if(!getWholeImpedanceRaw(j, val))
4386 return ReturnValue_error_method_failed;
4387
4388 *stiffness = (double) (val.stiffness);
4389 *damping = (double) (val.damping);
4390 return ReturnValue_ok;
4391}
4392
4393bool embObjMotionControl::getWholeImpedanceRaw(int j, eOmc_impedance_t &imped)
4394{
4395 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_config_impedance);
4396 uint16_t size;
4397 if(! askRemoteValue(protoid, &imped, size))
4398 return false;
4399
4400 // refresh cached value when reading data from the EMS
4401 _cacheImpedance[j].damping = imped.damping;
4402 _cacheImpedance[j].stiffness = imped.stiffness;
4403 _cacheImpedance[j].offset = imped.offset;
4404 return true;
4405}
4406
4407ReturnValue embObjMotionControl::setImpedanceRaw(int j, double stiffness, double damping)
4408{
4409 bool ret = true;
4410 eOmc_impedance_t val;
4411
4412 // Need to read the whole struct and modify just 2 of them -> now aching the old values and re-using them.
4413 // first set is done in the open function because the whole joint config is sent to the EMSs
4414 // cleaner solution, split the impedance structure into 2 separeted nework variables
4415
4416 _cacheImpedance[j].stiffness = (eOmeas_stiffness_t) stiffness;
4417 _cacheImpedance[j].damping = (eOmeas_damping_t) damping;
4418
4419 val.stiffness = _cacheImpedance[j].stiffness;
4420 val.damping = _cacheImpedance[j].damping;
4421 val.offset = _cacheImpedance[j].offset;
4422
4423 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_config_impedance);
4424 ret &= _ethRes->setRemoteValue(protid, &val);
4425
4426 return ret ? ReturnValue_ok : ReturnValue_error_method_failed;
4427}
4428
4430{
4431 bool ret = true;
4432 eOmc_impedance_t val;
4433
4434 _cacheImpedance[j].offset = (eOmeas_torque_t) S_32(offset);
4435 val.stiffness = _cacheImpedance[j].stiffness;
4436 val.damping = _cacheImpedance[j].damping;
4437 val.offset = _cacheImpedance[j].offset;
4438
4439 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_config_impedance);
4440 ret &= _ethRes->setRemoteValue(protid, &val);
4441
4442 return ret ? ReturnValue_ok : ReturnValue_error_method_failed;
4443}
4444
4446{
4447 eOmc_impedance_t val;
4448
4449 if(!getWholeImpedanceRaw(j, val))
4450 return ReturnValue_error_generic;
4451
4452 *offset = val.offset;
4453 return ReturnValue_ok;
4454}
4455
4456ReturnValue embObjMotionControl::getCurrentImpedanceLimitRaw(int j, double *min_stiff, double *max_stiff, double *min_damp, double *max_damp)
4457{
4458 *min_stiff = _parsedCfgData.impedance_limits[j].min_stiff;
4459 *max_stiff = _parsedCfgData.impedance_limits[j].max_stiff;
4460 *min_damp = _parsedCfgData.impedance_limits[j].min_damp;
4461 *max_damp = _parsedCfgData.impedance_limits[j].max_damp;
4462 return ReturnValue_ok;
4463}
4464
4465ReturnValue embObjMotionControl::getMotorTorqueParamsRaw(int j, MotorTorqueParameters *params)
4466{
4467 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_config_motor_params);
4468
4469 uint16_t size;
4470 eOmc_motor_params_t eo_params = {0};
4471 if(! askRemoteValue(protoid, &eo_params, size))
4472 return ReturnValue_error_generic;
4473
4474 params->bemf = 0.0;
4475 params->bemf_scale = 0;
4476 params->ktau = eo_params.ktau_value;
4477 params->ktau_scale = eo_params.ktau_scale;
4478 params->viscousPos = eo_params.friction.viscous_pos_val;
4479 params->viscousNeg = eo_params.friction.viscous_neg_val ;
4480 params->coulombPos = eo_params.friction.coulomb_pos_val;
4481 params->coulombNeg = eo_params.friction.coulomb_neg_val;
4482 params->velocityThres = eo_params.friction.velocityThres_val;
4483
4484 //printf("debug getMotorTorqueParamsRaw %f %f %f %f %f %f %f %f\n", params->bemf, params->bemf_scale, params->ktau,params->ktau_scale, params->viscousPos, params->viscousNeg, params->coulombPos, params->coulombNeg, params->threshold);
4485
4486 return ReturnValue_ok;
4487}
4488
4489ReturnValue embObjMotionControl::setMotorTorqueParamsRaw(int j, const MotorTorqueParameters params)
4490{
4491 if((params.bemf != 0.0) || (params.bemf_scale != 0))
4492 {
4493 yError() << "embObjMotionControl::setMotorTorqueParamsRaw() torque back-EMF parameters are not supported by this firmware protocol";
4494 return ReturnValue_error_method_failed;
4495 }
4496
4497 eOprotID32_t id32 = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_config_motor_params);
4498 eOmc_motor_params_t eo_params = {0};
4499
4500 //printf("setMotorTorqueParamsRaw for j %d(INPUT): benf=%f ktau=%f viscousPos=%f viscousNeg=%f coulombPos=%f coulombNeg=%f\n",j, params.bemf, params.ktau, params.viscousPos, params.viscousNeg, params.coulombPos, params.coulombNeg, params.threshold);
4501
4502 eo_params.bemf_scale = 0;
4503 eo_params.ktau_value = (float) params.ktau;
4504 eo_params.ktau_scale = (uint8_t) params.ktau_scale;
4505 eo_params.friction.viscous_pos_val = static_cast<float32_t>(params.viscousPos);
4506 eo_params.friction.viscous_neg_val = static_cast<float32_t>(params.viscousNeg);
4507 eo_params.friction.coulomb_pos_val = static_cast<float32_t>(params.coulombPos);
4508 eo_params.friction.coulomb_neg_val = static_cast<float32_t>(params.coulombNeg);
4509 eo_params.friction.velocityThres_val = static_cast<float32_t>(params.velocityThres);
4510
4511 //save these values in the trqPid structure because the motor torque parameters are used inside the torque PID controller in the parser so they are alway consisten
4512 _parsedCfgData.pidControllers.trq[j].viscousPos = params.viscousPos;
4513 _parsedCfgData.pidControllers.trq[j].viscousNeg = params.viscousNeg;
4514 _parsedCfgData.pidControllers.trq[j].coulombPos = params.coulombPos;
4515 _parsedCfgData.pidControllers.trq[j].coulombNeg = params.coulombNeg;
4516 _parsedCfgData.pidControllers.trq[j].velocityThres = params.velocityThres;
4517
4518 if(false == _ethRes->setRemoteValue(id32, &eo_params))
4519 {
4520 yError() << "embObjMotionControl::setMotorTorqueParamsRaw() could not send set message for" << getBoardInfo() << "joint " << j;
4521 return ReturnValue_error_generic;
4522 }
4523
4524 return ReturnValue_ok;
4525}
4526
4527// IVelocityControl2
4528ReturnValue embObjMotionControl::velocityMoveRaw(const int n_joint, const int *joints, const double *spds)
4529{
4530 ReturnValue ret = ReturnValue_ok;
4531
4532 for(int j=0; j< n_joint; j++)
4533 {
4534 ret &= velocityMoveRaw(joints[j], spds[j]);
4535 }
4536 return ret;
4537}
4538
4539// PositionDirect Interface
4540ReturnValue embObjMotionControl::setPositionRaw(int j, double ref)
4541{
4542 yarp::dev::ControlModeEnum mode{};
4543 getControlModeRaw(j, mode);
4544 if (mode != yarp::dev::ControlModeEnum::VOCAB_CM_POSITION_DIRECT &&
4545 mode != yarp::dev::ControlModeEnum::VOCAB_CM_IDLE)
4546 {
4547 if(_event_downsampler->canprint())
4548 {
4549 yError() << "setReferenceRaw: skipping command because" << getBoardInfo() << " joint " << j << " is not in VOCAB_CM_POSITION_DIRECT mode";
4550 }
4551 return ReturnValue_ok;
4552 }
4553
4554 eOprotID32_t protoId = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_cmmnds_setpoint);
4555 eOmc_setpoint_t setpoint = {0};
4556
4557 _ref_positions[j] = ref; // save internally the new value of pos.
4558 setpoint.type = (eOenum08_t) eomc_setpoint_positionraw;
4559 setpoint.to.position.value = (eOmeas_position_t) S_32(ref);
4560 setpoint.to.position.withvelocity = 0;
4561
4562 return _ethRes->setRemoteValue(protoId, &setpoint) ? ReturnValue_ok : ReturnValue_error_generic;
4563}
4564
4565ReturnValue embObjMotionControl::setPositionsRaw(const int n_joint, const int *joints, const double *refs)
4566{
4567 ReturnValue ret = ReturnValue_ok;
4568 for(int i=0; i<n_joint; i++)
4569 {
4570 ret &= setPositionRaw(joints[i], refs[i]);
4571 }
4572 return ret;
4573}
4574
4575ReturnValue embObjMotionControl::setPositionsRaw(const double *refs)
4576{
4577 ReturnValue ret = ReturnValue_ok;
4578 for (int i = 0; i<_njoints; i++)
4579 {
4580 ret &= setPositionRaw(i, refs[i]);
4581 }
4582 return ret;
4583}
4584
4585
4586ReturnValue embObjMotionControl::getTargetPositionRaw(int axis, double *ref)
4587{
4588#if ASK_REFERENCE_TO_FIRMWARE
4589 eOprotID32_t id32 = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, axis, eoprot_tag_mc_joint_status_target);
4590 *ref = 0;
4591
4592 // Get the value
4593 uint16_t size;
4594 eOmc_joint_status_target_t target = {0};
4595 if(!askRemoteValue(id32, &target, size))
4596 {
4597 yError() << "embObjMotionControl::getTargetPositionRaw() could not read reference pos for " << getBoardInfo() << "joint " << axis;
4598 return ReturnValue_error_generic;
4599 }
4600
4601 *ref = (double) target.trgt_position;
4602 //yError() << "embObjMotionControl::getTargetPositionRaw() BOARD" << _fId.boardNumber << "joint " << axis << "pos=" << target.trgt_position;
4603 return ReturnValue_ok;
4604#else
4605 *ref = _ref_command_positions[axis];
4606 return ReturnValue_ok;
4607#endif
4608}
4609
4611{
4612 bool ret = true;
4613 for (int i = 0; i<_njoints; i++)
4614 {
4615 ret &= getTargetPositionRaw(i, &refs[i]);
4616 }
4617 return ret ? ReturnValue_ok : ReturnValue_error_generic;
4618}
4619
4620ReturnValue embObjMotionControl::getTargetPositionsRaw(int nj, const int * jnts, double *refs)
4621{
4622 bool ret = true;
4623 for (int i = 0; i<nj; i++)
4624 {
4625 ret &= getTargetPositionRaw(jnts[i], &refs[i]);
4626 }
4627 return ret ? ReturnValue_ok : ReturnValue_error_generic;
4628}
4629
4630
4631ReturnValue embObjMotionControl::getTargetVelocityRaw(int axis, double *ref)
4632{
4633#if ASK_REFERENCE_TO_FIRMWARE
4634 eOprotID32_t id32 = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, axis, eoprot_tag_mc_joint_status_target);
4635 *ref = 0;
4636
4637 // Get the value
4638 uint16_t size;
4639 eOmc_joint_status_target_t target = {0};
4640 if(!askRemoteValue(id32, &target, size))
4641 {
4642 yError() << "embObjMotionControl::getTargetVelocityRaw() could not read reference vel for " << getBoardInfo() << "joint " << axis;
4643 return ReturnValue_error_generic;
4644 }
4645 *ref = (double) target.trgt_velocity;
4646 return ReturnValue_ok;
4647#else
4648 *ref = _ref_command_speeds[axis];
4649 return ReturnValue_ok;
4650#endif
4651}
4652
4654{
4655 #if ASK_REFERENCE_TO_FIRMWARE
4656 std::vector <eOmc_joint_status_target_t> targetList(_njoints);
4657 bool ret = askRemoteValues(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, eoprot_tag_mc_joint_status_target, targetList);
4658 if(!ret)
4659 {
4660 yError() << "embObjMotionControl::getTargetVelocitiesRaw() could not read reference vel for " << getBoardInfo() ;
4661 return ReturnValue_error_generic;
4662 }
4663 // Get the value
4664 for(int j=0; j<_njoints; j++)
4665 {
4666 refs[j] = (double) targetList[j].trgt_velocity;
4667 }
4668 return ReturnValue_ok;
4669 #else
4670 for(int j=0; j<_njoints; j++)
4671 {
4672 refs[j] = _ref_command_speeds[j];
4673 }
4674 return ReturnValue_ok;
4675 #endif
4676}
4677
4678ReturnValue embObjMotionControl::getTargetVelocitiesRaw(int nj, const int * jnts, double *refs)
4679{
4680 std::vector <double> refsList(_njoints);
4681 if(!getTargetVelocitiesRaw(refsList.data()))
4682 return ReturnValue_error_generic;
4683
4684 for (int i = 0; i<nj; i++)
4685 {
4686 if(jnts[i]>= _njoints)
4687 {
4688 yError() << getBoardInfo() << "getTargetVelocitiesRaw: joint " << jnts[i] << "doesn't exist";
4689 return ReturnValue_error_generic;
4690 }
4691 refs[i] = refsList[jnts[i]];
4692 }
4693 return ReturnValue_ok;
4694}
4695
4696ReturnValue embObjMotionControl::getRefPositionRaw(int axis, double *ref)
4697{
4698#if ASK_REFERENCE_TO_FIRMWARE
4699 eOprotID32_t id32 = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, axis, eoprot_tag_mc_joint_status_target);
4700 *ref = 0;
4701 // Get the value
4702 uint16_t size;
4703 eOmc_joint_status_target_t target = {0};
4704 if(!askRemoteValue(id32, &target, size))
4705 {
4706 yError() << "embObjMotionControl::getRefPositionRaw() could not read reference pos for " << getBoardInfo() << "joint " << axis;
4707 return ReturnValue_error_generic;
4708 }
4709
4710 *ref = (double) target.trgt_positionraw;
4711 return ReturnValue_ok;
4712#else
4713 *ref = _ref_positions[axis];
4714 return ReturnValue_ok;
4715#endif
4716}
4717
4719{
4720 #if ASK_REFERENCE_TO_FIRMWARE
4721 std::vector <eOmc_joint_status_target_t> targetList(_njoints);
4722 bool ret = askRemoteValues(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, eoprot_tag_mc_joint_status_target, targetList);
4723 if(!ret)
4724 {
4725 yError() << "embObjMotionControl::getRefPositionsRaw() could not read reference pos for " << getBoardInfo();
4726 return ReturnValue_error_generic;
4727 }
4728 // Get the value
4729 for(int j=0; j< _njoints; j++)
4730 refs[j] = (double) targetList[j].trgt_positionraw;
4731 return ReturnValue_ok;
4732 #else
4733 for(int j=0; j< _njoints; j++)
4734 refs[j] = _ref_positions[j];
4735 return ReturnValue_ok;
4736 #endif
4737}
4738
4739ReturnValue embObjMotionControl::getRefPositionsRaw(int nj, const int * jnts, double *refs)
4740{
4741 ReturnValue ret = ReturnValue_ok;
4742 for (int i = 0; i<nj; i++)
4743 {
4744 ret &= getRefPositionRaw(jnts[i], &refs[i]);
4745 }
4746 return ret;
4747}
4748
4749// InteractionMode
4750ReturnValue embObjMotionControl::getInteractionModeRaw(int j, yarp::dev::InteractionModeEnum & _mode)
4751{
4752 eOenum08_t interactionmodestatus;
4753// std::cout << "eoMC getInteractionModeRaw SINGLE joint " << j << std::endl;
4754
4755 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_core_modes_interactionmodestatus);
4756 if(! _ethRes->getLocalValue(protid, &interactionmodestatus)) // it is broadcasted toghether with the jointStatus full
4757 return ReturnValue_error_generic;
4758
4759 int tmp = (int)_mode;
4760 if(!interactionModeStatusConvert_embObj2yarp(interactionmodestatus, tmp) )
4761 return ReturnValue_error_generic;
4762
4763 _mode = (yarp::dev::InteractionModeEnum) tmp;
4764 return ReturnValue_ok;
4765}
4766
4767ReturnValue embObjMotionControl::getInteractionModesRaw(const std::vector<int>& joints, std::vector<yarp::dev::InteractionModeEnum>& modes)
4768{
4769// std::cout << "eoMC getInteractionModeRaw GROUP joints" << std::endl;
4770 if(joints.size() != modes.size())
4771 {
4772 yError() << "getInteractionModesRaw: size of input vector " << modes.size() << " is different from size of joints vector " << joints.size();
4773 return ReturnValue_error_generic;
4774 }
4775 bool ret = true;
4776 for(int idx=0; idx<joints.size(); idx++)
4777 {
4778 ret = getInteractionModeRaw(joints[idx], modes[idx]);
4779 }
4780 return ret ? ReturnValue_ok : ReturnValue_error_generic;
4781}
4782
4783ReturnValue embObjMotionControl::getInteractionModesRaw(std::vector<yarp::dev::InteractionModeEnum>& modes)
4784{
4785// std::cout << "eoMC getInteractionModeRaw ALL joints" << std::endl;
4786 bool ret = true;
4787 if(modes.size() != _njoints)
4788 {
4789 yError() << "getInteractionModesRaw: size of input vector " << modes.size() << " is different from number of joints " << _njoints;
4790 return ReturnValue_error_generic;
4791 }
4792 for(int j=0; j<_njoints; j++)
4793 ret = ret && getInteractionModeRaw(j, modes[j]);
4794 return ret ? ReturnValue_ok : ReturnValue_error_generic;
4795}
4796
4797// marco.accame: con alberto cardellino abbiamo parlato della correttezza di effettuare la verifica di quanto imposto (in setInteractionModeRaw() ed affini)
4798// andando a rileggere il valore nella scheda eth fino a che esso non sia quello atteso. si deve fare oppure no?
4799// con il interaction mode il can ora non lo fa. mentre lo fa per il control mode. perche' diverso?
4800ReturnValue embObjMotionControl::setInteractionModeRaw(int j, yarp::dev::InteractionModeEnum _mode)
4801{
4802 eOenum08_t interactionmodecommand = 0;
4803
4804
4805 // yDebug() << "received setInteractionModeRaw command (SINGLE) for" << getBoardInfo() << " joint " << j << " mode " << Vocab32::decode(_mode);
4806
4807 if (_mode == VOCAB_IM_COMPLIANT && _parsedCfgData.pidControllers.trq[j].enabled == false) {yError()<<"Torque control is disabled. Check your configuration parameters"; return ReturnValue_error_generic;}
4808
4809 if(!interactionModeCommandConvert_yarp2embObj(_mode, interactionmodecommand) )
4810 {
4811 yError() << "setInteractionModeRaw: received unknown mode for" << getBoardInfo() << " joint " << j << " mode " << Vocab32::decode(_mode);
4812 return ReturnValue_error_generic;
4813 }
4814
4815 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_cmmnds_interactionmode);
4816
4817 if(false == _ethRes->setRemoteValue(protid, &interactionmodecommand) )
4818 {
4819 yError() << "setInteractionModeRaw failed for" << getBoardInfo() << " joint " << j << " mode " << Vocab32::decode(_mode);
4820 return ReturnValue_error_generic;
4821 }
4822
4823 // marco.accame: use the following if you want to check the value of interactionmode on the remote board
4824#if 0
4825 eOenum08_t interactionmodestatus = 0;
4826 uint16_t size = 0;
4827 eOprotID32_t id32 = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_interactionmodestatus);
4828 bool ret = askRemoteValue(id32, &interactionmodestatus, size);
4829
4830 if((false == ret) || (interactionmodecommand != interactionmodestatus))
4831 {
4832 yError() << "check of embObjMotionControl::setInteractionModeRaw() failed for" << getBoardInfo() << " joint " << j << " mode " << Vocab32::decode(_mode);
4833 return ReturnValue_error_generic;
4834 }
4835#endif
4836
4837 return ReturnValue_ok;
4838}
4839
4840
4841ReturnValue embObjMotionControl::setInteractionModesRaw(const std::vector<int>& joints, const std::vector<yarp::dev::InteractionModeEnum>& modes)
4842{
4843 ReturnValue ret = ReturnValue_ok;
4844 if(joints.size() != modes.size())
4845 {
4846 yError() << "setInteractionModesRaw: size of input vector " << modes.size() << " is different from size of joints vector " << joints.size();
4847 return ReturnValue_error_generic;
4848 }
4849 for (auto i = 0; i < joints.size(); ++i)
4850 {
4851 ret &= setInteractionModeRaw(joints[i], modes[i]);
4852 }
4853 return ret;
4854}
4855
4856ReturnValue embObjMotionControl::setInteractionModesRaw(const std::vector<yarp::dev::InteractionModeEnum>& modes)
4857{
4858 ReturnValue ret = ReturnValue_ok;
4859 if(modes.size() != _njoints)
4860 {
4861 yError() << "setInteractionModesRaw: size of input vector " << modes.size() << " is different from number of joints " << _njoints;
4862 return ReturnValue_error_generic;
4863 }
4864 for (auto i = 0; i < modes.size(); ++i)
4865 {
4866 ret &= setInteractionModeRaw(i, modes[i]);
4867 }
4868 return ret;
4869}
4870
4871
4872ReturnValue embObjMotionControl::getPidOutputRaw(const PidControlTypeEnum& pidtype, int j, double *out)
4873{
4874 *out = 0;
4875 if (isUnsupportedPidAlias(pidtype))
4876 {
4877 return ReturnValue_ok;
4878 }
4879
4880 eOprotID32_t protoId = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_core);
4881 eOmc_joint_status_core_t jcore = {0};
4882 if(!_ethRes->getLocalValue(protoId, &jcore) )
4883 return ReturnValue_error_method_failed;
4884
4885 switch (pidtype)
4886 {
4887 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION:
4888 if((eomc_controlmode_torque == jcore.modes.controlmodestatus) || (eomc_controlmode_current == jcore.modes.controlmodestatus))
4889 *out=0;
4890 else
4891 *out = (double) jcore.ofpid.generic.output;
4892 break;
4893 case PidControlTypeEnum::VOCAB_PIDTYPE_POSITION_DIRECT:
4894 *out=0;
4895 break;
4896 case PidControlTypeEnum::VOCAB_PIDTYPE_TORQUE:
4897 if ((eomc_controlmode_torque == jcore.modes.controlmodestatus) ||
4898 ((eomc_controlmode_position == jcore.modes.controlmodestatus) && (eOmc_interactionmode_compliant == jcore.modes.interactionmodestatus)))
4899 *out = jcore.ofpid.generic.output;
4900 else
4901 *out = 0;
4902 break;
4903 case PidControlTypeEnum::VOCAB_PIDTYPE_CURRENT:
4904 *out = jcore.ofpid.generic.output;
4905 break;
4906 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY:
4907 *out = jcore.ofpid.generic.output;
4908 break;
4909 case PidControlTypeEnum::VOCAB_PIDTYPE_VELOCITY_DIRECT:
4910 *out = jcore.ofpid.generic.output;
4911 break;
4912 default:
4913 const auto pidtypeVocab = static_cast<yarp::conf::vocab32_t>(pidtype);
4914 yError() << getBoardInfo() << "Invalid pidtype:"<< yarp::os::Vocab32::decode(pidtypeVocab) << "in "<< __YFUNCTION__;
4915 break;
4916 }
4917 return ReturnValue_ok;
4918}
4919
4920ReturnValue embObjMotionControl::getPidOutputsRaw(const PidControlTypeEnum& pidtype, double *outs)
4921{
4922 if (isUnsupportedPidAlias(pidtype))
4923 {
4924 std::fill_n(outs, _njoints, 0.0);
4925 return ReturnValue_ok;
4926 }
4927
4928 ReturnValue ret = ReturnValue_ok;
4929 for(int j=0; j< _njoints; j++)
4930 {
4931 ret &= getPidOutputRaw(pidtype, j, &outs[j]);
4932 }
4933 return ret;
4934}
4935
4937{
4938 *num=_njoints;
4939 return ReturnValue_ok;
4940}
4941
4942ReturnValue embObjMotionControl::getTemperatureRaw(int m, double* val)
4943{
4944 eOmc_motor_status_basic_t status;
4945 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, m, eoprot_tag_mc_motor_status_basic);
4946
4947 *val = NAN;
4948 if (_parsedCfgData.temperatureSensorsVector.at(m)->getType() == motor_temperature_sensor_none)
4949 return ReturnValue_ok;
4950
4951
4952 bool ret = _ethRes->getLocalValue(protid, &status);
4953 if(!ret)
4954 {
4955 yError() << getBoardInfo() << "At timestamp" << yarp::os::Time::now() << "In motor" << m << "embObjMotionControl::getTemperatureRaw failed to complete getLocalValue()";
4956 return ret ? ReturnValue_ok : ReturnValue_error_generic;
4957 }
4958
4959 *val = _parsedCfgData.temperatureSensorsVector.at(m)->convertRawToTempCelsius((double)status.mot_temperature);
4960
4961
4962 return ret ? ReturnValue_ok : ReturnValue_error_generic;
4963}
4964
4966{
4967 bool ret = true;
4968 for(int j=0; j< _njoints; j++)
4969 {
4970 ret &= getTemperatureRaw(j, &vals[j]);
4971 }
4972 return ret ? ReturnValue_ok : ReturnValue_error_generic;
4973}
4974
4975ReturnValue embObjMotionControl::getTemperatureLimitRaw(int m, double *temp)
4976{
4977 *temp= _parsedCfgData.temperatureLimits[m].warning;
4978
4979 return ReturnValue_ok;
4980}
4981
4982ReturnValue embObjMotionControl::setTemperatureLimitRaw(int m, const double temp)
4983{
4984 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, m, eoprot_tag_mc_motor_config_temperaturelimit);
4985 eOmeas_temperature_t temperatureLimit = (eOmeas_pwm_t) S_16(temp);
4986
4987 return _ethRes->setRemoteValue(protid, &temperatureLimit) ? ReturnValue_ok : ReturnValue_error_generic;
4988
4989}
4990
4991ReturnValue embObjMotionControl::getPeakCurrentRaw(int m, double *val)
4992{
4993 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, m, eoprot_tag_mc_motor_config_currentlimits);
4994 uint16_t size;
4995 eOmc_current_limits_params_t currentlimits = {0};
4996 *val = 0;
4997 if(!askRemoteValue(protid, &currentlimits, size))
4998 {
4999 yError() << "embObjMotionControl::getPeakCurrentRaw() can't read current limits for" << getBoardInfo() << " motor " << m;
5000 return ReturnValue_error_generic;
5001 }
5002
5003 *val = (double) currentlimits.peakCurrent ;
5004 return ReturnValue_ok;
5005}
5006
5007ReturnValue embObjMotionControl::setPeakCurrentRaw(int m, const double val)
5008{
5009 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, m, eoprot_tag_mc_motor_config_currentlimits);
5010 //get current limit params
5011 uint16_t size;
5012 eOmc_current_limits_params_t currentlimits = {0};
5013 if(!askRemoteValue(protid, &currentlimits, size))
5014 {
5015 yError() << "embObjMotionControl::setPeakCurrentRaw can't read current limits for" << getBoardInfo() << " motor " << m ;
5016 return ReturnValue_error_generic;
5017 }
5018
5019 //set current overload
5020 currentlimits.peakCurrent = (eOmeas_current_t) S_16(val);
5021
5022 //send new values
5023 bool ret = _ethRes->setRemoteValue(protid, &currentlimits);
5024 if(!ret)
5025 {
5026 yError() << "embObjMotionControl::setPeakCurrentRaw failed sending new value for" << getBoardInfo() << " motor " << m ;
5027 }
5028 return ret ? ReturnValue_ok : ReturnValue_error_generic;
5029}
5030
5031ReturnValue embObjMotionControl::getNominalCurrentRaw(int m, double *val)
5032{
5033 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, m, eoprot_tag_mc_motor_config_currentlimits);
5034 uint16_t size;
5035 eOmc_current_limits_params_t currentlimits = {0};
5036 *val = 0;
5037 if(!askRemoteValue(protid, &currentlimits, size))
5038 {
5039 yError() << "embObjMotionControl::getNominalCurrentRaw() can't read current limits for" << getBoardInfo() << " motor " << m;
5040 return ReturnValue_error_generic;
5041 }
5042
5043 *val = (double) currentlimits.nominalCurrent ;
5044 return ReturnValue_ok;
5045}
5046
5047ReturnValue embObjMotionControl::setNominalCurrentRaw(int m, const double val)
5048{
5049 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, m, eoprot_tag_mc_motor_config_currentlimits);
5050
5051 //get current limit params
5052 uint16_t size;
5053 eOmc_current_limits_params_t currentlimits = {0};
5054 if(!askRemoteValue(protid, &currentlimits, size))
5055 {
5056 yError() << "embObjMotionControl::setNominalCurrentRaw can't read current limits for" << getBoardInfo() << " motor " << m ;
5057 return ReturnValue_error_generic;
5058 }
5059
5060 //set current overload
5061 currentlimits.nominalCurrent = (eOmeas_current_t) S_16(val);
5062
5063 //send new values
5064 bool ret = _ethRes->setRemoteValue(protid, &currentlimits);
5065 if(!ret)
5066 {
5067 yError() << "embObjMotionControl::setNominalCurrentRaw failed sending new value for" << getBoardInfo() << " motor " << m ;
5068 }
5069
5070 return ret ? ReturnValue_ok : ReturnValue_error_generic;
5071}
5072
5073ReturnValue embObjMotionControl::getPWMRaw(int j, double* val)
5074{
5075 eOmc_motor_status_basic_t status;
5076 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_status_basic);
5077
5078 bool ret = _ethRes->getLocalValue(protid, &status);
5079 if(ret)
5080 {
5081 *val = (double) status.mot_pwm;
5082 }
5083 else
5084 {
5085 yError() << "embObjMotionControl::getPWMRaw failed for" << getBoardInfo() << " motor " << j ;
5086 *val = 0;
5087 }
5088
5089 return ret ? ReturnValue_ok : ReturnValue_error_generic;
5090}
5091
5092ReturnValue embObjMotionControl::getPWMLimitRaw(int j, double* val)
5093{
5094 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config_pwmlimit);
5095 uint16_t size;
5096 eOmeas_pwm_t motorPwmLimit;
5097
5098 bool ret = askRemoteValue(protid, &motorPwmLimit, size);
5099 if(ret)
5100 {
5101 *val = (double) motorPwmLimit;
5102 }
5103 else
5104 {
5105 yError() << "embObjMotionControl::getPWMLimitRaw failed for" << getBoardInfo() << " motor " << j ;
5106 *val = 0;
5107 }
5108
5109 return ret ? ReturnValue_ok : ReturnValue_error_generic;
5110}
5111
5112ReturnValue embObjMotionControl::setPWMLimitRaw(int j, const double val)
5113{
5114 if (val < 0)
5115 {
5116 yError() << "embObjMotionControl::setPWMLimitRaw failed because pwmLimit is negative for" << getBoardInfo() << " motor " << j ;
5117 return ReturnValue_ok; //return true because the error ios not due to communication error
5118 }
5119 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config_pwmlimit);
5120 eOmeas_pwm_t motorPwmLimit = (eOmeas_pwm_t) S_16(val);
5121
5122 return _ethRes->setRemoteValue(protid, &motorPwmLimit) ? ReturnValue_ok : ReturnValue_error_generic;
5123}
5124
5126{
5127 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_controller, 0, eoprot_tag_mc_controller_status);
5128 uint16_t size;
5129 eOmc_controller_status_t controllerStatus;
5130
5131 bool ret = askRemoteValue(protid, &controllerStatus, size);
5132 if(ret)
5133 {
5134 *val = (double) controllerStatus.supplyVoltage;
5135 }
5136 else
5137 {
5138 yError() << "embObjMotionControl::getPowerSupplyVoltageRaw failed for" << getBoardInfo() << " motor " << j ;
5139 *val = 0;
5140 }
5141
5142 return ret ? ReturnValue_ok : ReturnValue_error_generic;
5143}
5144
5145bool embObjMotionControl::askRemoteValue(eOprotID32_t id32, void* value, uint16_t& size)
5146{
5147 return _ethRes->getRemoteValue(id32, value, 0.200, 0);
5148}
5149
5150template <class T>
5151bool embObjMotionControl::askRemoteValues(eOprotEndpoint_t ep, eOprotEntity_t entity, eOprotTag_t tag, std::vector<T>& values)
5152{
5153 std::vector<eOprotID32_t> idList;
5154 std::vector<void*> valueList;
5155 idList.clear();
5156 valueList.clear();
5157 for(int j=0; j<_njoints; j++)
5158 {
5159 eOprotID32_t protoId = eoprot_ID_get(ep, entity, j, tag);
5160 idList.push_back(protoId);
5161 valueList.push_back((void*)&values[j]);
5162 }
5163
5164 bool ret = _ethRes->getRemoteValues(idList, valueList);
5165 if(!ret)
5166 {
5167 yError() << "embObjMotionControl::askRemoteValues failed for all joints of" << getBoardInfo();
5168 }
5169
5170 return ret;
5171}
5172
5173bool embObjMotionControl::checkRemoteControlModeStatus(int joint, int target_mode)
5174{
5175 bool ret = false;
5176 eOenum08_t temp = 0;
5177 uint16_t size = 0;
5178
5179 eOprotID32_t id32 = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, joint, eoprot_tag_mc_joint_status_core_modes_controlmodestatus);
5180 const double timeout = 0.250; // 250 msec
5181 const int maxretries = 25;
5182 const double delaybetweenqueries = 0.010; // 10 msec
5183
5184 // now i repeat the query until i am satisfied. how many times? for maximum time timeout seconds and with a gap of delaybetweenqueries
5185
5186 double timeofstart = yarp::os::Time::now();
5187 int attempt = 0;
5188
5189 for( attempt = 0; attempt < maxretries; attempt++)
5190 {
5191 ret = askRemoteValue(id32, &temp, size);
5192 if(ret == false)
5193 {
5194 yError ("An error occurred inside embObjMotionControl::checkRemoteControlModeStatus(j=%d, targetmode=%s) for BOARD %s IP %s", joint, yarp::os::Vocab32::decode(target_mode).c_str(), _ethRes->getProperties().boardnameString.c_str(), _ethRes->getProperties().ipv4addrString.c_str());
5195 break;
5196 }
5197 int current_mode = controlModeStatusConvert_embObj2yarp(temp);
5198 if(current_mode == target_mode)
5199 {
5200 ret = true;
5201 break;
5202 }
5203 if((current_mode == VOCAB_CM_IDLE) && (target_mode == VOCAB_CM_FORCE_IDLE))
5204 {
5205 ret = true;
5206 break;
5207 }
5208 if(current_mode == VOCAB_CM_HW_FAULT)
5209 {
5210 if(target_mode != VOCAB_CM_FORCE_IDLE) { yError ("embObjMotionControl::checkRemoteControlModeStatus(%d, %d) is unable to check the control mode of BOARD %s IP %s because it is now in HW_FAULT", joint, target_mode, _ethRes->getProperties().boardnameString.c_str(), _ethRes->getProperties().ipv4addrString.c_str()); }
5211 ret = true;
5212 break;
5213 }
5214
5215 if((yarp::os::Time::now()-timeofstart) > timeout)
5216 {
5217 ret = false;
5218 yError ("A %f sec timeout occured in embObjMotionControl::checkRemoteControlModeStatus(), BOARD %s IP %s, joint %d, current mode: %s, requested: %s", timeout, _ethRes->getProperties().boardnameString.c_str(), _ethRes->getProperties().ipv4addrString.c_str(), joint, yarp::os::Vocab32::decode(current_mode).c_str(), yarp::os::Vocab32::decode(target_mode).c_str());
5219 break;
5220 }
5221 if(attempt > 0)
5222 { // i print the warning only after at least one retry.
5223 yWarning ("embObjMotionControl::checkRemoteControlModeStatus() has done %d attempts and will retry again after a %f sec delay. (BOARD %s IP %s, joint %d) -> current mode = %s, requested = %s", attempt+1, delaybetweenqueries, _ethRes->getProperties().boardnameString.c_str() , _ethRes->getProperties().ipv4addrString.c_str(), joint, yarp::os::Vocab32::decode(current_mode).c_str(), yarp::os::Vocab32::decode(target_mode).c_str());
5224 }
5225 SystemClock::delaySystem(delaybetweenqueries);
5226 }
5227
5228 if(false == ret)
5229 {
5230 yError("failure of embObjMotionControl::checkRemoteControlModeStatus(j=%d, targetmode=%s) for BOARD %s IP %s after %d attempts and %f seconds", joint, yarp::os::Vocab32::decode(target_mode).c_str(), _ethRes->getProperties().boardnameString.c_str(), _ethRes->getProperties().ipv4addrString.c_str(), attempt, yarp::os::Time::now()-timeofstart);
5231 }
5232
5233
5234 return ret;
5235}
5236
5237//the device needs coupling info if it manages joints controlled by 2foc and mc4plus.
5238bool embObjMotionControl::iNeedCouplingsInfo(void)
5239{
5240 eOmn_serv_type_t mc_serv_type = (eOmn_serv_type_t)_parsedCfgData.serviceConfig.ethservice.configuration.type;
5241 if( (mc_serv_type == eomn_serv_MC_foc) ||
5242 (mc_serv_type == eomn_serv_MC_mc4plus) ||
5243 (mc_serv_type == eomn_serv_MC_mc4plusmais) ||
5244 (mc_serv_type == eomn_serv_MC_mc2pluspsc) ||
5245 (mc_serv_type == eomn_serv_MC_mc4plusfaps) ||
5246 (mc_serv_type == eomn_serv_MC_advfoc)
5247 )
5248 return true;
5249 else
5250 return false;
5251}
5252
5253//PWM interface
5255{
5256 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_cmmnds_setpoint);
5257
5258 eOmc_setpoint_t setpoint;
5259
5260 setpoint.type = (eOenum08_t)eomc_setpoint_openloop;
5261 setpoint.to.openloop.value = (eOmeas_pwm_t)S_16(v);
5262
5263 return _ethRes->setRemoteValue(protid, &setpoint) ? ReturnValue_ok : ReturnValue_error_generic;
5264}
5265
5267{
5268 bool ret = true;
5269 for (int j = 0; j<_njoints; j++)
5270 {
5271 ret = ret && setRefDutyCycleRaw(j, v[j]);
5272 }
5273 return ret ? ReturnValue_ok : ReturnValue_error_generic;
5274}
5275
5276ReturnValue embObjMotionControl::getRefDutyCycleRaw(int j, double *v)
5277{
5278 eOprotID32_t protoId = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_target);
5279 uint16_t size = 0;
5280 *v = 0;
5281 eOmc_joint_status_target_t target = { 0 };
5282
5283
5284 if (!askRemoteValue(protoId, &target, size))
5285 {
5286 yError() << "embObjMotionControl::getRefDutyCycleRaw() could not read openloop reference for " << getBoardInfo() << "joint " << j;
5287 return ReturnValue_error_generic;
5288 }
5289
5290 *v = (double)target.trgt_pwm;
5291
5292 return ReturnValue_ok;
5293}
5294
5296{
5297 std::vector <eOmc_joint_status_target_t> targetList(_njoints);
5298 bool ret = askRemoteValues(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, eoprot_tag_mc_joint_status_target, targetList);
5299 if(!ret)
5300 {
5301 yError() << "embObjMotionControl::getDutyCyclesRaw failed for all joints of" << getBoardInfo();
5302 }
5303
5304 for (int j = 0; j<_njoints; j++)
5305 {
5306 v[j]= targetList[j].trgt_pwm;
5307 }
5308 return ret ? ReturnValue_ok : ReturnValue_error_generic;
5309}
5310
5311ReturnValue embObjMotionControl::getDutyCycleRaw(int j, double *v)
5312{
5313 eOmc_motor_status_basic_t status;
5314 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_status_basic);
5315
5316 bool ret = _ethRes->getLocalValue(protid, &status);
5317 if (ret)
5318 {
5319 *v = (double)status.mot_pwm;
5320 }
5321 else
5322 {
5323 yError() << "embObjMotionControl::getDutyCycleRaw failed for" << getBoardInfo() << " motor " << j;
5324 *v = 0;
5325 }
5326
5327 return ret ? ReturnValue_ok : ReturnValue_error_method_failed;
5328}
5329
5331{
5332 bool ret = true;
5333 for (int j = 0; j< _njoints; j++)
5334 {
5335 ret &= getDutyCycleRaw(j, &v[j]);
5336 }
5337 return ret ? ReturnValue_ok : ReturnValue_error_method_failed;;
5338}
5339
5340// Current interface
5341
5342ReturnValue embObjMotionControl::getCurrentRangeRaw(int j, double *min, double *max)
5343{
5344 //this should be completed with numbers obtained from configuration files.
5345 //some caveats: currently current limits are expressed in robot configuration files in milliAmperes. Amperes should be used instead.
5346 //yarp does not perform any conversion on these numbers. Should it?
5347 *min = -10000.0;
5348 *max = 10000.0;
5349 return ReturnValue_ok;
5350}
5351
5352ReturnValue embObjMotionControl::getCurrentRangesRaw(double *min, double *max)
5353{
5354 ReturnValue ret = ReturnValue_ok;
5355 for (int j = 0; j< _njoints; j++)
5356 {
5357 ret &= getCurrentRangeRaw(j, &min[j], &max[j]);
5358 }
5359 return ret;
5360}
5361
5362ReturnValue embObjMotionControl::setRefCurrentsRaw(const double *t)
5363{
5364 ReturnValue ret = ReturnValue_ok;
5365 for (int j = 0; j<_njoints; j++)
5366 {
5367 ret = ret && setRefCurrentRaw(j, t[j]);
5368 }
5369 return ret;
5370}
5371
5372ReturnValue embObjMotionControl::setRefCurrentRaw(int j, double t)
5373{
5374 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_cmmnds_setpoint);
5375
5376 eOmc_setpoint_t setpoint;
5377
5378 setpoint.type = (eOenum08_t)eomc_setpoint_current;
5379 setpoint.to.current.value = (eOmeas_pwm_t)S_16(t);
5380
5381 return _ethRes->setRemoteValue(protid, &setpoint) ? ReturnValue_ok : ReturnValue_error_method_failed;
5382}
5383
5384ReturnValue embObjMotionControl::setRefCurrentsRaw(const int n_joint, const int *joints, const double *t)
5385{
5386 ReturnValue ret = ReturnValue_ok;
5387 for (int j = 0; j<n_joint; j++)
5388 {
5389 ret = ret && setRefCurrentRaw(joints[j], t[j]);
5390 }
5391 return ret;
5392}
5393
5395{
5396 std::vector <eOmc_joint_status_target_t> targetList(_njoints);
5397 bool ret = askRemoteValues(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, eoprot_tag_mc_joint_status_target, targetList);
5398 if (!ret)
5399 {
5400 yError() << "embObjMotionControl::getDutyCyclesRaw failed for all joints of" << getBoardInfo();
5401 }
5402
5403 for (int j = 0; j<_njoints; j++)
5404 {
5405 t[j] = targetList[j].trgt_current;
5406 }
5407 return ret ? ReturnValue_ok : ReturnValue_error_method_failed;
5408}
5409
5410ReturnValue embObjMotionControl::getRefCurrentRaw(int j, double *t)
5411{
5412 eOprotID32_t protoId = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_target);
5413 uint16_t size = 0;
5414 *t = 0;
5415 eOmc_joint_status_target_t target = { 0 };
5416
5417
5418 if (!askRemoteValue(protoId, &target, size))
5419 {
5420 yError() << "embObjMotionControl::getRefDutyCycleRaw() could not read openloop reference for " << getBoardInfo() << "joint " << j;
5421 return ReturnValue_error_method_failed;
5422 }
5423
5424 *t = (double)target.trgt_current;
5425
5426 return ReturnValue_ok;
5427}
5428
5429ReturnValue embObjMotionControl::helper_setVelDirPidRaw(int j, const Pid &pid)
5430{
5431 eOprotID32_t protoId;
5432 eOmc_PID_t outPid;
5433 Pid hwPid = pid;
5434
5435 if (!_parsedCfgData.pidControllers.dir_vel[j].enabled)
5436 {
5437 yError() << "eoMc " << getBoardInfo() << ": it is not possible set direct velocity pid for motor " << j << ", because current pid is not enabled in xml files";
5438 return ReturnValue_error_generic;
5439 }
5440
5441 if( _parsedCfgData.pidControllers.dir_vel[j].out_type == eomc_ctrl_out_type_vel_pwm )
5442 {
5443 protoId = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config_pidvelpwm);
5444 }
5445 else if( _parsedCfgData.pidControllers.dir_vel[j].out_type == eomc_ctrl_out_type_vel_cur )
5446 {
5447 protoId = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config_pidvelcur);
5448 }
5449 else
5450 { yError() << "eoMc " << getBoardInfo() << __YFUNCTION__ << " for motor " << j ;
5451 return ReturnValue_error_generic;
5452 }
5453
5454 copyPid_iCub2eo(&hwPid, &outPid);
5455
5456 if (false == _ethRes->setRemoteValue(protoId, &outPid))
5457 {
5458 yError() << getBoardInfo() << __YFUNCTION__ << "while asking remote value for" << " joint " << j;
5459 return ReturnValue_error_method_failed;
5460 }
5461
5462 return ReturnValue_ok;
5463}
5464
5465ReturnValue embObjMotionControl::helper_getVelDirPidRaw(int j, Pid *pid)
5466{
5467 eOprotID32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, j, eoprot_tag_mc_motor_config);
5468 uint16_t size;
5469 eOmc_motor_config_t motor_cfg;
5470 if (!askRemoteValue(protoid, &motor_cfg, size))
5471 {
5472 yError() << getBoardInfo() << __YFUNCTION__ << "error in asking velocity direct pid for joint" << j ;
5473 return ReturnValue_error_method_failed;
5474 }
5475
5476 eOmc_PID_t tmp;
5477 switch(_parsedCfgData.pidControllers.dir_vel[j].out_type)
5478 {
5479 case eomc_ctrl_out_type_vel_pwm:
5480 tmp = (eOmc_PID_t)motor_cfg.pidvelpwm;
5481 break;
5482 case eomc_ctrl_out_type_vel_cur:
5483 tmp = (eOmc_PID_t)motor_cfg.pidvelcur;
5484 break;
5485 default:
5486 yError() << getBoardInfo() << __YFUNCTION__ << "Invalid output type for velocity direct pid for joint " << j;
5487 return ReturnValue_error_method_failed;
5488 }
5489 copyPid_eo2iCub(&tmp, pid);
5490
5491 return ReturnValue_ok;
5492}
5493
5494ReturnValue embObjMotionControl::helper_getVelDirPidsRaw(Pid *pids)
5495{
5496 std::vector <eOmc_motor_config_t> motor_cfg_list(_njoints);
5497 bool ret = askRemoteValues<eOmc_motor_config_t>(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, eoprot_tag_mc_motor_config, motor_cfg_list);
5498 if(! ret)
5499 {
5500 yError() << getBoardInfo() << __YFUNCTION__ << "error in asking velocity direct pids for all joints ";
5501 return ReturnValue_error_method_failed;
5502 }
5503 for(int j=0; j<_njoints; j++)
5504 {
5505 eOmc_PID_t tmp;
5506 switch(_parsedCfgData.pidControllers.dir_vel[j].out_type)
5507 {
5508 case eomc_ctrl_out_type_vel_pwm:
5509 tmp = (eOmc_PID_t)motor_cfg_list[j].pidvelpwm;
5510 break;
5511 case eomc_ctrl_out_type_vel_cur:
5512 tmp = (eOmc_PID_t)motor_cfg_list[j].pidvelcur;
5513 break;
5514 default:
5515 yError() << getBoardInfo() << __YFUNCTION__ << "Invalid output type for velocity direct pid for joint " << j;
5516 return ReturnValue_error_method_failed;
5517 }
5518 copyPid_eo2iCub(&tmp, &pids[j]);
5519 }
5520 return ReturnValue_ok;
5521}
5522
5523bool embObjMotionControl::getJointConfiguration(int joint, eOmc_joint_config_t *jntCfg_ptr)
5524{
5525 uint32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, joint, eoprot_tag_mc_joint_config);
5526 uint16_t size;
5527 if(!askRemoteValue(protoid, jntCfg_ptr, size))
5528 {
5529 yError ("Failure of askRemoteValue() inside embObjMotionControl::getJointConfiguration(axis=%d) for BOARD %s IP %s", joint, _ethRes->getProperties().boardnameString.c_str(), _ethRes->getProperties().ipv4addrString.c_str());
5530 return false;
5531 }
5532 return true;
5533}
5534
5535bool embObjMotionControl::getMotorConfiguration(int axis, eOmc_motor_config_t *motCfg_ptr)
5536{
5537 uint32_t protoid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_motor, axis, eoprot_tag_mc_motor_config);
5538 uint16_t size;
5539 if(!askRemoteValue(protoid, motCfg_ptr, size))
5540 {
5541 yError ("Failure of askRemoteValue() inside embObjMotionControl::getMotorConfiguration(axis=%d) for BOARD %s IP %s", axis, _ethRes->getProperties().boardnameString.c_str(), _ethRes->getProperties().ipv4addrString.c_str());
5542 return false;
5543 }
5544 return true;
5545}
5546
5547
5548bool embObjMotionControl::getGerabox_E2J(int joint, double *gearbox_E2J_ptr)
5549{
5550 eOmc_joint_config_t jntCfg;
5551
5552 if(!getJointConfiguration(joint, &jntCfg))
5553 {
5554 yError ("Failure embObjMotionControl::getGerabox_E2J(axis=%d) for BOARD %s IP %s", joint, _ethRes->getProperties().boardnameString.c_str(), _ethRes->getProperties().ipv4addrString.c_str());
5555 return false;
5556 }
5557 *gearbox_E2J_ptr = jntCfg.gearbox_E2J;
5558 return true;
5559}
5560
5561bool embObjMotionControl::getJointEncTolerance(int joint, double *jEncTolerance_ptr)
5562{
5563 eOmc_joint_config_t jntCfg;
5564
5565 if(!getJointConfiguration(joint, &jntCfg))
5566 {
5567 yError ("Failure embObjMotionControl::getJointEncTolerance(axis=%d) for BOARD %s IP %s", joint, _ethRes->getProperties().boardnameString.c_str(), _ethRes->getProperties().ipv4addrString.c_str());
5568 return false;
5569 }
5570 *jEncTolerance_ptr = jntCfg.jntEncTolerance;
5571 return true;
5572}
5573
5574bool embObjMotionControl::getMotorEncTolerance(int axis, double *mEncTolerance_ptr)
5575{
5576 eOmc_motor_config_t motorCfg;
5577 if(!getMotorConfiguration(axis, &motorCfg))
5578 {
5579 yError ("Failure embObjMotionControl::getMotorEncTolerance(axis=%d) for BOARD %s IP %s", axis, _ethRes->getProperties().boardnameString.c_str(), _ethRes->getProperties().ipv4addrString.c_str());
5580 return false;
5581 }
5582 *mEncTolerance_ptr = motorCfg.rotEncTolerance;
5583 return true;
5584}
5585
5586ReturnValue embObjMotionControl::getLastJointFaultRaw(int j, int& fault, std::string& message)
5587{
5588 eOmc_motor_status_t status;
5589
5590 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol,
5591 eoprot_entity_mc_motor, j,
5592 eoprot_tag_mc_motor_status);
5593
5594 bool ret = _ethRes->getLocalValue(protid, &status);
5595
5596 message.clear();
5597
5598 if (!ret)
5599 {
5600 fault = -1;
5601 message = "Could not retrieve the fault state.";
5602 return ReturnValue_error_method_failed;
5603 }
5604
5605 if (status.mc_fault_state == EOERROR_CODE_DUMMY)
5606 {
5607 fault = EOERROR_CODE_DUMMY;
5608 message = "No fault detected.";
5609
5610 return ReturnValue_ok;
5611 }
5612
5613 fault = eoerror_code2value(status.mc_fault_state);
5614 message = eoerror_code2string(status.mc_fault_state);
5615
5616 return ReturnValue_ok;
5617}
5618
5619bool embObjMotionControl::getRawData_core(std::string key, std::vector<std::int32_t> &data)
5620{
5621 // Here I need to be sure 100% the key exists!!!
5622 // It must exists since the call is made while iterating over the map
5623 data.clear();
5624 for(int j=0; j< _njoints; j++)
5625 {
5626 eOmc_joint_status_additionalInfo_t addinfo;
5627 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, j, eoprot_tag_mc_joint_status_addinfo_multienc);
5628 if(!_ethRes->getLocalValue(protid, &addinfo))
5629 {
5630 return false;
5631 }
5632 for (int k = 0; k < std::size(addinfo.multienc); k++)
5633 {
5634 data.push_back((int32_t)addinfo.multienc[k]);
5635 }
5636
5637 }
5638 return true;
5639}
5640
5641bool embObjMotionControl::getRawDataMap(std::map<std::string, std::vector<std::int32_t>> &map)
5642{
5643 for (auto it = _rawValuesMetadataMap.begin(); it != _rawValuesMetadataMap.end(); it++)
5644 {
5645 if(!getRawData_core(it->first, _rawDataAuxVector))
5646 {
5647 yError() << getBoardInfo() << "getRawData failed. Cannot retrieve all raw data from local memory";
5648 return false;
5649 }
5650 map.insert({it->first, _rawDataAuxVector});
5651 }
5652
5653 return true;
5654}
5655
5656bool embObjMotionControl::getRawData(std::string key, std::vector<std::int32_t> &data)
5657{
5658 if(_rawValuesMetadataMap.find(key) != _rawValuesMetadataMap.end())
5659 {
5660 getRawData_core(key, data);
5661 }
5662 else
5663 {
5664 yError() << getBoardInfo() << "Request key:" << key << "is not available. Cannot retrieve get raw data.";
5665 return false;
5666 }
5667
5668 return true;
5669}
5670
5671bool embObjMotionControl::getKeys(std::vector<std::string> &keys)
5672{
5673 for (const auto &p : _rawValuesMetadataMap)
5674 {
5675 keys.push_back(p.first);
5676 }
5677
5678 return true;
5679}
5680
5682{
5683 return _rawValuesMetadataMap.size();
5684}
5685
5687{
5688 if (_rawValuesMetadataMap.empty())
5689 {
5690 yError() << getBoardInfo() << "embObjMotionControl Map is empty. Closing...";
5691 return false;
5692 }
5693
5694 metamap.metadataMap = _rawValuesMetadataMap;
5695 return true;
5696}
5698{
5699 if(_rawValuesMetadataMap.find(key) != _rawValuesMetadataMap.end())
5700 {
5701 meta = _rawValuesMetadataMap[key];
5702 }
5703 else
5704 {
5705 yError() << getBoardInfo() << "Requested key" << key << "is not available in the map. Closing...";
5706 return false;
5707 }
5708
5709
5710 return true;
5711}
5712
5713bool embObjMotionControl::getAxesNames(std::string key, std::vector<std::string> &axesNames)
5714{
5715 axesNames.clear();
5716 if (_rawValuesMetadataMap.find(key) != _rawValuesMetadataMap.end())
5717 {
5718 axesNames.assign(_rawValuesMetadataMap[key].axesNames.begin(), _rawValuesMetadataMap[key].axesNames.end());
5719 }
5720 else
5721 {
5722 yError() << getBoardInfo() << "Requested key" << key << "is not available in the map. Exiting";
5723 return false;
5724 }
5725 return true;
5726}
5727
5728ReturnValue embObjMotionControl::getAxes(size_t& axes)
5729{
5730 axes=_njoints;
5731 return ReturnValue_ok;
5732}
5733
5734ReturnValue embObjMotionControl::setRefVelocityRaw(int jnt, double vel)
5735{
5736 yarp::dev::ControlModeEnum mode{};
5737 getControlModeRaw(jnt, mode);
5738 if( (mode != yarp::dev::ControlModeEnum::VOCAB_CM_VELOCITY_DIRECT) &&
5739 (mode != yarp::dev::ControlModeEnum::VOCAB_CM_IDLE)) //TODO: remove VOCAB_CM_IDLE exception when eoMc boards will properly support switching to VOCAB_CM_VELOCITY_DIRECT from other control modes different from VOCAB_CM_IDLE
5740 {
5741 if(_event_downsampler->canprint())
5742 {
5743 yError() << "setRefVelocityRaw: skipping command because " << getBoardInfo() << " joint " << jnt << " is not in VOCAB_CM_VELOCITY_DIRECT mode";
5744 }
5745 return ReturnValue_ok;
5746 }
5747
5748 eOmc_setpoint_t setpoint;
5749 setpoint.type = eomc_setpoint_velocityraw;
5750
5751 setpoint.to.velocityraw.value = (eOmeas_velocity_t) S_32(vel);
5752
5753 eOprotID32_t protid = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, jnt, eoprot_tag_mc_joint_cmmnds_setpoint);
5754
5755 if(false == _ethRes->setRemoteValue(protid, &setpoint))
5756 {
5757 yError() << getBoardInfo() << "while setting velocity direct target for" << "joint " << jnt;
5758 return ReturnValue_error_method_failed;
5759 }
5760
5761 return ReturnValue_ok;
5762}
5763
5764ReturnValue embObjMotionControl::setRefVelocityRaw(const std::vector<double>& vels)
5765{
5766 // Velocity is expressed in iDegrees/s
5767 ReturnValue ret = ReturnValue_ok;
5768 for(auto j=0; j< _njoints; j++)
5769 {
5770 ret &= setRefVelocityRaw(j, vels[j]);
5771
5772 if (!ret)
5773 return ret;
5774 }
5775 return ret;
5776}
5777
5778ReturnValue embObjMotionControl::setRefVelocityRaw(const std::vector<int>& jnts, const std::vector<double>& vels)
5779{
5780 // Velocity is expressed in iDegrees/s
5781 ReturnValue ret = ReturnValue_ok;
5782
5783 for (auto j=0; j < jnts.size(); j++)
5784 {
5785 ret &= setRefVelocityRaw(jnts[j], vels[j]);
5786 if (!ret)
5787 return ret;
5788 }
5789 return ret;
5790}
5791
5792ReturnValue embObjMotionControl::getRefVelocityRaw(const int jnt, double& vel)
5793{
5794 // Using joint related datatypes, instead of motor related datatypes
5795 eOprotID32_t protoId = eoprot_ID_get(eoprot_endpoint_motioncontrol, eoprot_entity_mc_joint, jnt, eoprot_tag_mc_joint_status_target);
5796
5797 uint16_t size;
5798
5799 eOmc_joint_status_target_t target;
5800
5801 if (!askRemoteValue(protoId, &target, size))
5802 {
5803 yError() << __YFUNCTION__ << " could not read velocity direct reference for " << getBoardInfo() << "joint " << jnt;
5804 return ReturnValue_error_method_failed;
5805 }
5806
5807 vel = (double)target.trgt_velocityraw;
5808
5809 return ReturnValue_ok;
5810}
5811
5812ReturnValue embObjMotionControl::getRefVelocityRaw(std::vector<double>& vels)
5813{
5814 ReturnValue ret = ReturnValue_ok;
5815
5816 for (auto j = 0; j< _njoints; j++)
5817 {
5818 ret &= getRefVelocityRaw(j, vels[j]);
5819 if (!ret)
5820 return ret;
5821
5822 }
5823 return ret;
5824}
5825
5826ReturnValue embObjMotionControl::getRefVelocityRaw(const std::vector<int>& jnts, std::vector<double>& vels)
5827{
5828 ReturnValue ret = ReturnValue_ok;
5829
5830 for (auto j = 0; j< jnts.size(); j++)
5831 {
5832 ret &= getRefVelocityRaw(jnts[j], vels[j]);
5833 if (!ret)
5834 return ret;
5835 }
5836 return ret;
5837}
5838
5839ReturnValue embObjMotionControl::setPidFeedforwardRaw(const PidControlTypeEnum& pidtype,int j, double v)
5840{
5841 if (isUnsupportedPidAlias(pidtype))
5842 {
5843 return ReturnValue_ok;
5844 }
5845
5846 return YARP_METHOD_NOT_YET_IMPLEMENTED();
5847}
5848
5849ReturnValue embObjMotionControl::getPidOffsetRaw(const PidControlTypeEnum& pidtype,int j, double& v)
5850{
5851 v = 0;
5852 if (isUnsupportedPidAlias(pidtype))
5853 {
5854 return ReturnValue_ok;
5855 }
5856
5857 return YARP_METHOD_NOT_YET_IMPLEMENTED();
5858}
5859
5860ReturnValue embObjMotionControl::getPidFeedforwardRaw(const PidControlTypeEnum& pidtype,int j, double& v)
5861{
5862 v = 0;
5863 if (isUnsupportedPidAlias(pidtype))
5864 {
5865 return ReturnValue_ok;
5866 }
5867
5868 return YARP_METHOD_NOT_YET_IMPLEMENTED();
5869}
5870
5871ReturnValue embObjMotionControl::isPidEnabledRaw(const PidControlTypeEnum& pidtype, int j, bool& enabled)
5872{
5873 enabled = false;
5874 if (isUnsupportedPidAlias(pidtype))
5875 {
5876 return ReturnValue_ok;
5877 }
5878 //return YARP_METHOD_NOT_YET_IMPLEMENTED();
5879 return ReturnValue_ok;
5880}
5881
5882ReturnValue embObjMotionControl::getPidExtraInfoRaw(const PidControlTypeEnum& pidtype, int j, yarp::dev::PidExtraInfo& units)
5883{
5884 units = yarp::dev::PidExtraInfo();
5885 if (isUnsupportedPidAlias(pidtype))
5886 {
5887 return ReturnValue_ok;
5888 }
5889 //return YARP_METHOD_NOT_YET_IMPLEMENTED();
5890 return ReturnValue_ok;
5891}
5892
5893ReturnValue embObjMotionControl::getPidExtraInfosRaw(const PidControlTypeEnum& pidtype, std::vector<yarp::dev::PidExtraInfo>& units)
5894{
5895 if (isUnsupportedPidAlias(pidtype))
5896 {
5897 std::fill(units.begin(), units.end(), yarp::dev::PidExtraInfo());
5898 return ReturnValue_ok;
5899 }
5900
5901 //return YARP_METHOD_NOT_YET_IMPLEMENTED();
5902 return ReturnValue_ok;
5903
5904}
5905
5906// DeviceDriverParams
5907bool embObjMotionControl::parseParams(const yarp::os::Searchable& config)
5908{
5909 return YARP_METHOD_NOT_YET_IMPLEMENTED();
5910}
5911
5913{
5914 return "embObjMotionControl";
5915}
5916
5918{
5919 return getBoardInfo();
5920}
5921
5923{
5924 return "No documentation available for embObjMotionControl";
5925}
5926
5927std::vector<std::string> embObjMotionControl::getListOfParams() const
5928{
5929 return std::vector<std::string>();
5930}
5931
5932bool embObjMotionControl::getParamValue(const std::string& paramName, std::string& paramValue) const
5933{
5934 return YARP_METHOD_NOT_YET_IMPLEMENTED();
5935}
5936
5938{
5939 return "No configuration available for" + getBoardInfo();
5940}
5941
5942//IJointBrake
5943yarp::dev::ReturnValue embObjMotionControl::isJointBrakedRaw(int j, bool& braked) const
5944{
5945 braked=false;
5946 return (ReturnValue_ok);
5947}
5948yarp::dev::ReturnValue embObjMotionControl::setManualBrakeActiveRaw(int j, bool active)
5949{
5950 return YARP_METHOD_NOT_YET_IMPLEMENTED();
5951}
5952yarp::dev::ReturnValue embObjMotionControl::setAutoBrakeEnabledRaw(int j, bool enabled)
5953{
5954 return YARP_METHOD_NOT_YET_IMPLEMENTED();
5955}
5956yarp::dev::ReturnValue embObjMotionControl::getAutoBrakeEnabledRaw(int j, bool& enabled) const
5957{
5958 return YARP_METHOD_NOT_YET_IMPLEMENTED();
5959}
5960
5961// eof
@ data
virtual bool getLocalValue(const eOprotID32_t id32, void *value)=0
virtual bool getRemoteValue(const eOprotID32_t id32, void *value, const double timeout=0.100, const unsigned int retries=0)=0
virtual bool getRemoteValues(const std::vector< eOprotID32_t > &id32s, const std::vector< void * > &values, const double timeout=0.500)=0
int releaseResource2(eth::AbstractEthResource *ethresource, IethResource *interface)
static bool killYourself()
static TheEthManager * instance()
std::map< std::string, rawValuesKeyMetadata > metadataMap
virtual ReturnValue getEncoderSpeedsRaw(double *spds) override
virtual ReturnValue getCurrentRangeRaw(int j, double *min, double *max) override
virtual ReturnValue getPidExtraInfosRaw(const PidControlTypeEnum &pidtype, std::vector< yarp::dev::PidExtraInfo > &units) override
virtual ReturnValue setInteractionModesRaw(const std::vector< int > &joints, const std::vector< yarp::dev::InteractionModeEnum > &modes) override
virtual bool getRawData(std::string key, std::vector< std::int32_t > &data) override
virtual ReturnValue getRefTorqueRaw(int j, double *t) override
virtual ReturnValue getPWMRaw(int j, double *val) override
virtual ReturnValue setEncoderRaw(int j, double val) override
virtual ReturnValue setPidReferenceRaw(const PidControlTypeEnum &pidtype, int j, double ref) override
virtual ReturnValue getPidErrorsRaw(const PidControlTypeEnum &pidtype, double *errs) override
virtual bool getEncoderTypeName(uint32_t jomoId, eOmc_position_t pos, std::string &encoderTypeName) override
virtual ReturnValue enablePidRaw(const PidControlTypeEnum &pidtype, int j) override
virtual ReturnValue setImpedanceOffsetRaw(int j, double offset) override
virtual ReturnValue disablePidRaw(const PidControlTypeEnum &pidtype, int j) override
virtual std::string getDeviceName() const override
Get the name of the device (i.e.
virtual ReturnValue setRefCurrentsRaw(const double *t) override
bool getRotorEncoderTypeRaw(int j, int &type)
virtual ReturnValue getAvailablePidsRaw(int j, std::vector< PidControlTypeEnum > &avail) override
virtual ReturnValue resetEncodersRaw() override
virtual ReturnValue setRefTorquesRaw(const double *t) override
virtual ReturnValue getRemoteVariablesListRaw(yarp::os::Bottle *listOfKeys) override
virtual ReturnValue getEncoderTimedRaw(int j, double *encs, double *stamp) override
virtual ReturnValue setPosLimitsRaw(int axis, double min, double max) override
virtual bool update(eOprotID32_t id32, double timestamp, void *rxdata)
virtual ReturnValue disableAmpRaw(int j) override
virtual ReturnValue getMotorEncoderAccelerationsRaw(double *accs) override
virtual ReturnValue getMotorEncoderTimedRaw(int m, double *encs, double *stamp) override
virtual ReturnValue getPeakCurrentRaw(int m, double *val) override
bool getHasRotorEncoderRaw(int j, int &ret)
virtual ReturnValue setRefVelocityRaw(int jnt, double vel) override
virtual ReturnValue calibrateAxisWithParamsRaw(int axis, unsigned int type, double p1, double p2, double p3) override
virtual ReturnValue setImpedanceRaw(int j, double stiffness, double damping) override
virtual ReturnValue getImpedanceRaw(int j, double *stiffness, double *damping) override
virtual ReturnValue calibrationDoneRaw(int j) override
virtual ReturnValue setPidErrorLimitRaw(const PidControlTypeEnum &pidtype, int j, double limit) override
virtual ReturnValue getRefPositionRaw(const int joint, double *ref) override
virtual ReturnValue getTrajAccelerationsRaw(double *accs) override
virtual ReturnValue getTargetVelocityRaw(const int joint, double *ref) override
virtual ReturnValue getTorquesRaw(double *t) override
virtual ReturnValue getMotorEncodersRaw(double *encs) override
virtual ReturnValue getAxisNameRaw(int axis, std::string &name) override
virtual ReturnValue setControlModesRaw(const std::vector< int > &joints, const std::vector< yarp::dev::SelectableControlModeEnum > &modes) override
virtual ReturnValue getPidRaw(const PidControlTypeEnum &pidtype, int j, Pid *pid) override
virtual ReturnValue setPositionsRaw(const int n_joint, const int *joints, const double *refs) override
bool getRotorLimitsRaw(int j, double *rotorMin, double *rotorMax)
virtual ReturnValue getTorqueRangeRaw(int j, double *min, double *max) override
virtual std::vector< std::string > getListOfParams() const override
Return a list of all params used by the device.
virtual bool open(yarp::os::Searchable &par)
virtual ReturnValue getTargetPositionRaw(const int joint, double *ref) override
virtual ReturnValue setRefCurrentRaw(int j, double t) override
virtual ReturnValue setPositionRaw(int j, double ref) override
bool getJointEncoderResolutionRaw(int m, double &jntres)
virtual ReturnValue getEncodersTimedRaw(double *encs, double *stamps) override
virtual ReturnValue setPidFeedforwardRaw(const PidControlTypeEnum &pidtype, int j, double v) override
virtual ReturnValue setPidReferencesRaw(const PidControlTypeEnum &pidtype, const double *refs) override
virtual ReturnValue setNominalCurrentRaw(int m, const double val) override
virtual ReturnValue getNumberOfMotorEncodersRaw(int *num) override
virtual ReturnValue getMotorEncodersTimedRaw(double *encs, double *stamps) override
virtual bool getEntityName(uint32_t entityId, std::string &entityName)
virtual eth::iethresType_t type()
virtual ReturnValue getEncoderSpeedRaw(int j, double *sp) override
bool getTemperatureSensorTypeRaw(int j, std::string &ret)
virtual bool getEntityControlModeName(uint32_t entityId, eOenum08_t control_mode, std::string &controlModeName, eObool_t compact_string) override
virtual ReturnValue getTorqueRaw(int j, double *t) override
virtual ReturnValue getPidErrorLimitRaw(const PidControlTypeEnum &pidtype, int j, double *limit) override
virtual yarp::dev::ReturnValue isJointBrakedRaw(int j, bool &braked) const override
virtual bool updateVirtualAnalogSensorMeasure(yarp::sig::Vector &fTorques) override
virtual ReturnValue setControlModeRaw(int j, yarp::dev::SelectableControlModeEnum mode) override
virtual ReturnValue getTrajAccelerationRaw(int j, double *acc) override
virtual ReturnValue getMotorEncoderRaw(int m, double *v) override
virtual yarp::dev::ReturnValue setAutoBrakeEnabledRaw(int j, bool enabled) override
virtual ReturnValue getNumberOfMotorsRaw(int *num) override
virtual ReturnValue getCurrentRangesRaw(double *min, double *max) override
virtual ReturnValue getTemperaturesRaw(double *vals) override
virtual ReturnValue getPidExtraInfoRaw(const PidControlTypeEnum &pidtype, int j, yarp::dev::PidExtraInfo &units) override
virtual ReturnValue getPidOffsetRaw(const PidControlTypeEnum &pidtype, int j, double &v) override
virtual ReturnValue getControlModeRaw(int j, yarp::dev::ControlModeEnum &mode) override
virtual yarp::dev::VAS_status getVirtualAnalogSensorStatus(int ch) override
virtual ReturnValue setMotorEncodersRaw(const double *vals) override
virtual ReturnValue getPidReferenceRaw(const PidControlTypeEnum &pidtype, int j, double *ref) override
virtual ReturnValue getCurrentImpedanceLimitRaw(int j, double *min_stiff, double *max_stiff, double *min_damp, double *max_damp) override
virtual ReturnValue resetEncoderRaw(int j) override
virtual ReturnValue setVelLimitsRaw(int axis, double min, double max) override
virtual ReturnValue getMotorEncoderSpeedRaw(int m, double *sp) override
virtual ReturnValue getAvailableControlModesRaw(int j, std::vector< yarp::dev::SelectableControlModeEnum > &avail) override
virtual std::string getDeviceClassName() const override
Get the name of the DeviceDriver class.
virtual ReturnValue setPeakCurrentRaw(int m, const double val) override
virtual ReturnValue setPidsRaw(const PidControlTypeEnum &pidtype, const Pid *pids) override
virtual ReturnValue setMotorTorqueParamsRaw(int j, const MotorTorqueParameters params) override
virtual std::string getConfiguration() const override
Return the configuration of the device.
virtual ReturnValue getRefCurrentsRaw(double *t) override
virtual ReturnValue getTrajSpeedRaw(int j, double *ref) override
virtual ReturnValue getMotorEncoderCountsPerRevolutionRaw(int m, double *v) override
virtual bool getRawDataMap(std::map< std::string, std::vector< std::int32_t > > &map) override
virtual ReturnValue getPidOutputRaw(const PidControlTypeEnum &pidtype, int j, double *out) override
virtual ReturnValue getRefTorquesRaw(double *t) override
virtual ReturnValue getPowerSupplyVoltageRaw(int j, double *val) override
virtual ReturnValue getTorqueRangesRaw(double *min, double *max) override
virtual ReturnValue getImpedanceOffsetRaw(int j, double *offset) override
virtual ReturnValue getNominalCurrentRaw(int m, double *val) override
virtual ReturnValue stopRaw() override
virtual bool getMetadataMap(rawValuesKeyMetadataMap &metamap) override
virtual ReturnValue getPidOutputsRaw(const PidControlTypeEnum &pidtype, double *outs) override
virtual ReturnValue getPidReferencesRaw(const PidControlTypeEnum &pidtype, double *refs) override
virtual ReturnValue getAmpStatusRaw(int *st) override
virtual ReturnValue getMotorTorqueParamsRaw(int j, MotorTorqueParameters *params) override
virtual ReturnValue setTrajAccelerationRaw(int j, double acc) override
virtual ReturnValue setInteractionModeRaw(int j, yarp::dev::InteractionModeEnum _mode) override
virtual ReturnValue setMotorEncoderRaw(int m, const double val) override
virtual ReturnValue positionMoveRaw(int j, double ref) override
virtual ReturnValue getRefPositionsRaw(double *refs) override
virtual ReturnValue getTargetPositionsRaw(double *refs) override
virtual ReturnValue getTemperatureRaw(int m, double *val) override
bool getRotorEncoderResolutionRaw(int m, double &rotres)
virtual ReturnValue getPWMLimitRaw(int j, double *val) override
virtual ReturnValue setEncodersRaw(const double *vals) override
virtual ReturnValue getLastJointFaultRaw(int j, int &fault, std::string &message) override
virtual ReturnValue getDutyCycleRaw(int j, double *v) override
virtual ReturnValue setRemoteVariableRaw(std::string key, const yarp::os::Bottle &val) override
virtual ReturnValue getEncoderAccelerationsRaw(double *accs) override
bool getWholeImpedanceRaw(int j, eOmc_impedance_t &imped)
virtual ReturnValue checkMotionDoneRaw(bool &flag) override
virtual ReturnValue setCalibrationParametersRaw(int axis, const CalibrationParameters &params) override
bool getJointEncoderTypeRaw(int j, int &type)
virtual ReturnValue getJointTypeRaw(int axis, yarp::dev::JointTypeEnum &type) override
virtual ReturnValue setPWMLimitRaw(int j, const double val) override
virtual ReturnValue setRefDutyCycleRaw(int j, double v) override
virtual ReturnValue getEncoderAccelerationRaw(int j, double *spds) override
virtual ReturnValue isPidEnabledRaw(const PidControlTypeEnum &pidtype, int j, bool &enabled) override
virtual ReturnValue getPidFeedforwardRaw(const PidControlTypeEnum &pidtype, int j, double &v) override
virtual ReturnValue setRefTorqueRaw(int j, double t) override
virtual ReturnValue getAxes(size_t &axes) override
virtual ReturnValue setTrajSpeedRaw(int j, double sp) override
virtual ReturnValue getCurrentRaw(int j, double *val) override
virtual ReturnValue setRefDutyCyclesRaw(const double *v) override
virtual ReturnValue setMaxCurrentRaw(int j, double val) override
virtual ReturnValue getPidErrorRaw(const PidControlTypeEnum &pidtype, int j, double *err) override
virtual ReturnValue getMotorEncoderAccelerationRaw(int m, double *spds) override
virtual ReturnValue getEncoderRaw(int j, double *v) override
bool getMotorPolesRaw(int j, int &poles)
virtual ReturnValue getPosLimitsRaw(int axis, double *min, double *max) override
virtual ReturnValue setTemperatureLimitRaw(int m, const double temp) override
virtual ReturnValue getRemoteVariableRaw(std::string key, yarp::os::Bottle &val) override
virtual ReturnValue getRefVelocityRaw(const int jnt, double &vel) override
virtual bool getKeys(std::vector< std::string > &keys) override
bool getKinematicMJRaw(int j, double &rotres)
virtual std::string getDocumentationOfDeviceParams() const override
Get the documentation of the DeviceDriver's parameters.
virtual ReturnValue velocityMoveRaw(int j, double sp) override
virtual yarp::dev::ReturnValue setManualBrakeActiveRaw(int j, bool active) override
virtual yarp::dev::ReturnValue getAutoBrakeEnabledRaw(int j, bool &enabled) const override
virtual ReturnValue getInteractionModeRaw(int j, yarp::dev::InteractionModeEnum &_mode) override
virtual ReturnValue resetMotorEncodersRaw() override
virtual ReturnValue getEncodersRaw(double *encs) override
virtual ReturnValue resetPidRaw(const PidControlTypeEnum &pidtype, int j) override
virtual ReturnValue relativeMoveRaw(int j, double delta) override
virtual ReturnValue getTemperatureLimitRaw(int m, double *temp) override
virtual bool getAxesNames(std::string key, std::vector< std::string > &axesNames) override
virtual ReturnValue getRefDutyCycleRaw(int j, double *v) override
virtual bool parseParams(const yarp::os::Searchable &config) override
virtual ReturnValue getRefDutyCyclesRaw(double *v) override
virtual ReturnValue getInteractionModesRaw(const std::vector< int > &joints, std::vector< yarp::dev::InteractionModeEnum > &modes) override
virtual ReturnValue getDutyCyclesRaw(double *v) override
virtual ReturnValue setTrajAccelerationsRaw(const double *accs) override
virtual ReturnValue setPidRaw(const PidControlTypeEnum &pidtype, int j, const Pid &pid) override
virtual ReturnValue getControlModesRaw(std::vector< yarp::dev::ControlModeEnum > &mode) override
virtual ReturnValue getMotorEncoderSpeedsRaw(double *spds) override
virtual ReturnValue getTrajSpeedsRaw(double *spds) override
virtual ReturnValue getCurrentsRaw(double *vals) override
virtual ReturnValue setTrajSpeedsRaw(const double *spds) override
bool getTorqueControlFilterType(int j, int &type)
virtual ReturnValue getRefCurrentRaw(int j, double *t) override
virtual ReturnValue getVelLimitsRaw(int axis, double *min, double *max) override
virtual int getVirtualAnalogSensorChannels() override
bool getRotorIndexOffsetRaw(int j, double &rotorOffset)
virtual ReturnValue getMaxCurrentRaw(int j, double *val) override
virtual ReturnValue resetMotorEncoderRaw(int m) override
virtual ReturnValue setPidOffsetRaw(const PidControlTypeEnum &pidtype, int j, double v) override
virtual ReturnValue setGearboxRatioRaw(int m, const double val) override
virtual bool getParamValue(const std::string &paramName, std::string &paramValue) const override
Return the value (represented as a string) of the requested parameter.
virtual ReturnValue setMotorEncoderCountsPerRevolutionRaw(int m, const double cpr) override
virtual ReturnValue setPidErrorLimitsRaw(const PidControlTypeEnum &pidtype, const double *limits) override
virtual bool getKeyMetadata(std::string key, rawValuesKeyMetadata &meta) override
virtual ReturnValue getGearboxRatioRaw(int m, double *gearbox) override
virtual ReturnValue getPidsRaw(const PidControlTypeEnum &pidtype, Pid *pids) override
virtual ReturnValue getTargetVelocitiesRaw(double *refs) override
virtual ReturnValue getPidErrorLimitsRaw(const PidControlTypeEnum &pidtype, double *limits) override
bool getHasRotorEncoderIndexRaw(int j, int &ret)
virtual ReturnValue enableAmpRaw(int j) override
Singleton factory class to create and manage default values with runtime configuration This class ens...
const embObjMotionControlDefaults_t & getDefaults() const
Get the current defaults structure.
static DefaultsFactory & getInstance()
Get the singleton instance (thread-safe in C++11+) Uses Meyer's singleton pattern for automatic threa...
_3f_vect_t acc
Definition dataTypes.h:1
int n
static uint32_t idx[BOARD_NUM]
constexpr int PARSER_MOTION_CONTROL_VERSION
static bool isUnsupportedPidAlias(PidControlTypeEnum pidtype)
bool read(yarp::os::Searchable &cfgtotal, pc104Data &pc104data)
Definition ethParser.cpp:92
iethresType_t
@ iethres_motioncontrol
Default (fallback) values for embObjMotionControl configuration parameters.
int S_32(double x)
Definition eomcUtils.h:71
int controlModeStatusConvert_embObj2yarp(eOenum08_t embObjMode)
Definition eomcUtils.h:260
bool interactionModeStatusConvert_embObj2yarp(eOenum08_t embObjMode, int &vocabOut)
Definition eomcUtils.h:369
bool controlModeCommandConvert_yarp2embObj(int vocabMode, eOenum08_t &embOut)
Definition eomcUtils.h:199
void copyPid_eo2iCub(eOmc_PID_t *in, Pid *out)
Definition eomcUtils.h:185
bool EncoderType_eo2iCub(const uint8_t *in, std::string *out)
Definition eomcUtils.h:126
short S_16(double x)
Definition eomcUtils.h:44
void copyPid_iCub2eo(const Pid *in, eOmc_PID_t *out)
Definition eomcUtils.h:172
bool interactionModeCommandConvert_yarp2embObj(int vocabMode, eOenum08_t &embOut)
Definition eomcUtils.h:347
int U_16(double x)
Definition eomcUtils.h:32
int U_32(double x)
Definition eomcUtils.h:59
out
Definition sine.m:8
degrees offset
Definition sine.m:4
std::vector< PidInfo > dir_vel
std::vector< PidInfo > vel
std::vector< PidInfo > dir_pos
std::vector< PidInfo > cur
std::vector< PidInfo > trj
std::vector< PidInfo > mix
std::vector< TrqPidInfo > trq
eOmc_encoder_descriptor_t desc