YARP CiA-402 EtherCAT Device 0.6.0
YARP device plugin for EtherCAT CiA-402 drives
Loading...
Searching...
No Matches
CiA402MotionControl.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Fondazione Istituto Italiano di Tecnologia (IIT)
2// SPDX-License-Identifier: BSD-3-Clause
3
6
9
10// YARP
11#include <yarp/os/LogStream.h>
12#include <yarp/os/Value.h>
13
14// STD
15#include <algorithm>
16#include <chrono>
17#include <cmath>
18#include <cstdint>
19#include <cstring>
20#include <memory>
21#include <mutex>
22#include <string>
23#include <string_view>
24#include <vector>
25
26namespace yarp::dev
27{
28
29/**
30 * Private implementation holding configuration, runtime state, and helpers.
31 * Concurrency:
32 * - variables.mutex guards feedback snapshots returned to YARP APIs
33 * - controlModeState.mutex guards target/active control modes
34 * - setPoints.mutex guards user setpoints and their first‑cycle latches
35 * Units:
36 * - Positions: degrees (joint and motor)
37 * - Velocities: degrees/second
38 * - Torques: joint Nm (converted to motor Nm and then to per‑thousand for PDOs)
39 */
41{
42 enum class PosSrc
43 {
44 S6064, // Use CiA 402 Position Actual Value (0x6064)
45 Enc1, // Use encoder 1 position (0x2111:02 in PDO)
46 Enc2 // Use encoder 2 position (0x2113:02 in PDO)
47 };
48 // Which object supplies velocity feedback for a given consumer (joint/motor)
49 enum class VelSrc
50 {
51 S606C, // Use CiA 402 Velocity Actual Value (0x606C) [rpm]
52 Enc1, // Use encoder 1 velocity (0x2111:03) [rpm]
53 Enc2 // Use encoder 2 velocity (0x2113:03) [rpm]
54 };
55 // Where each encoder is physically mounted relative to the gearbox
56 enum class Mount
57 {
58 None, // Not present / unknown
59 Motor, // Pre‑gearbox (motor shaft)
60 Joint // Post‑gearbox (load/joint shaft)
61 };
62 // Which sensor the drive uses internally for the closed loop
63 enum class SensorSrc
64 {
65 Unknown, // Not reported via SDOs (fallback heuristics apply)
66 Enc1, // Internal loop uses encoder 1
67 Enc2 // Internal loop uses encoder 2
68 };
69
70 // Human-readable name for log messages
71 static constexpr std::string_view kClassName = "CiA402MotionControl";
72
73 // EtherCat manager
75
76 // mutex to protect the run and the stop
78
79 // Constants (unit conversions used throughout)
80 static constexpr double MICROSECONDS_TO_SECONDS = 1e-6; // µs → s
81 // Device timestamp wraps every ~42.949672 s (spec: (2^32 - 1)/100 µs)
82 // Use +1 to account for the fractional remainder and avoid drift negative steps.
83 // 42,949,673 µs
84 static constexpr uint64_t TIMESTAMP_WRAP_PERIOD_US = (((uint64_t)1 << 32) - 1) / 100 + 1;
85 // Heuristic for wrap detection: consider a wrap only if the value is jumps backward by more
86 // than half of its range. Small backward steps can happen due to clock adjustments/resets and
87 // must not be treated as wraps.
88 static constexpr uint32_t TIMESTAMP_WRAP_HALF_RANGE = TIMESTAMP_WRAP_PERIOD_US / 2;
89 // Parameters that come from the .xml file (see open())
90 //--------------------------------------------------------------------------
91 size_t numAxes{0}; // how many joints we expose to YARP
92 int firstSlave{1}; // bus index of the first drive we care about
93 std::string expectedName{}; // sanity-check each slave.name if not empty
94
95 //--------------------------------------------------------------------------
96 // Runtime bookkeeping
97 //--------------------------------------------------------------------------
98 std::vector<double> gearRatio; // motor-revs : load-revs
100 std::vector<double> torqueConstants; // [Nm/A] from 0x2003:01
104 std::vector<uint32_t> enc1Res, enc2Res; // from 0x2110, 0x2112
106 std::vector<Mount> enc1Mount, enc2Mount; // from config (and SDO sanity)
107 std::vector<PosSrc> posSrcJoint, posSrcMotor; // from config (0x2012:08 semantics)
108 std::vector<VelSrc> velSrcJoint, velSrcMotor; // from config (0x2011:04 semantics)
109 std::vector<SensorSrc> posLoopSrc; // drive internal pos loop source (0x2012:09)
110 std::vector<SensorSrc> velLoopSrc; // drive internal vel loop source (0x2011:05)
111 std::vector<double> velToDegS; // multiply device value to get deg/s
112 std::vector<double> degSToVel; // multiply deg/s to get device value
113 std::vector<bool> invertedMotionSenseDirection; // if true the torque, current, velocity and
114 // position have inverted sign
115 struct Limits
116 {
119 std::vector<bool> usePositionLimitsFromConfig; // if false, read 0x607D from SDO and cache
120 // here
121 std::mutex mutex; // protects *all* the above vectors
123
125 {
126 mutable std::mutex mutex; // protect the variables in this structure from concurrent access
127 std::vector<double> motorEncoders; // for getMotorEncoders()
128 std::vector<double> motorVelocities; // for getMotorVelocities()
129 std::vector<double> motorAccelerations; // for getMotorAccelerations()
130 std::vector<double> jointPositions; // for getJointPositions()
131 std::vector<double> jointVelocities; // for getJointVelocities()
132 std::vector<double> jointAccelerations; // for getJointAccelerations()
133 std::vector<double> jointTorques; // for getJointTorques()
134 std::vector<double> motorCurrents; // for getCurrents()
135 std::vector<double> feedbackTime; // feedback time in seconds. Computed from
136 // drive’s own internal timestep that starts when the
137 // drive boots (or resets)
141 std::vector<bool> targetReached; // cached Statusword bit 10
142 std::vector<double> driveTemperatures; // cached drive temperature if available
143
145 {
146 this->motorEncoders.resize(numAxes);
147 this->motorVelocities.resize(numAxes);
148 this->motorAccelerations.resize(numAxes);
149 this->feedbackTime.resize(numAxes);
150 this->jointPositions.resize(numAxes);
151 this->jointVelocities.resize(numAxes);
152 this->jointAccelerations.resize(numAxes);
153 this->jointNames.resize(numAxes);
154 this->jointTorques.resize(numAxes);
155 this->motorCurrents.resize(numAxes);
156 this->STO.resize(numAxes);
157 this->SBC.resize(numAxes);
158 this->targetReached.resize(numAxes);
159 this->driveTemperatures.resize(numAxes);
160 }
161 };
162
164
166 {
167 std::vector<int> target; // what the user asked for
168 std::vector<int> active; // what the drive is really doing
169 std::vector<int> cstFlavor; // custom flavor for each axis (torque/current)
170 std::vector<int> prevCstFlavor; // previous flavor, for change detection
171 mutable std::mutex mutex; // protects *both* vectors
172
174 {
175 target.assign(n, VOCAB_CM_IDLE);
176 active = target;
177 cstFlavor.assign(n, VOCAB_CM_UNKNOWN);
179 }
180 };
182
184 {
185 std::mutex mutex; // protects the following vectors
187 std::vector<double> jointVelocities; // for velocityMove() or joint velocity commands
189 std::vector<bool> hasTorqueSP; // user provided a torque since entry?
190 std::vector<bool> hasVelSP; // user provided a velocity since entry?
191 std::vector<bool> hasCurrentSP; // user provided a current since entry?
192
193 std::vector<double> ppJointTargetsDeg; // last requested PP target [deg] joint-side
194 std::vector<int32_t> ppTargetCounts; // computed PP target for 0x607A (loop-shaft)
195 std::vector<bool> ppHasPosSP; // a new PP command available this cycle?
196 std::vector<bool> ppIsRelative; // this PP set-point is relative
197 std::vector<bool> ppPulseHi; // drive CW bit4 high this cycle?
198 std::vector<bool> ppPulseCoolDown; // bring bit4 low next
199
202
204 {
208 hasTorqueSP.assign(n, false);
209 hasVelSP.assign(n, false);
210 hasCurrentSP.assign(n, false);
211
214 ppHasPosSP.assign(n, false);
215 ppIsRelative.assign(n, false);
216 ppPulseHi.assign(n, false);
217 ppPulseCoolDown.assign(n, false);
218
221 }
222
223 void reset()
224 {
225 std::lock_guard<std::mutex> lock(this->mutex);
226 std::fill(this->jointTorques.begin(), this->jointTorques.end(), 0.0);
227 std::fill(this->jointVelocities.begin(), this->jointVelocities.end(), 0.0);
228 std::fill(this->motorCurrents.begin(), this->motorCurrents.end(), 0.0);
229 std::fill(this->hasTorqueSP.begin(), this->hasTorqueSP.end(), false);
230 std::fill(this->hasCurrentSP.begin(), this->hasCurrentSP.end(), false);
231 std::fill(this->hasVelSP.begin(), this->hasVelSP.end(), false);
232 std::fill(this->ppJointTargetsDeg.begin(), this->ppJointTargetsDeg.end(), 0.0);
233 std::fill(this->ppTargetCounts.begin(), this->ppTargetCounts.end(), 0);
234 std::fill(this->ppHasPosSP.begin(), this->ppHasPosSP.end(), false);
235 std::fill(this->ppIsRelative.begin(), this->ppIsRelative.end(), false);
236 std::fill(this->ppPulseHi.begin(), this->ppPulseHi.end(), false);
237 std::fill(this->ppPulseCoolDown.begin(), this->ppPulseCoolDown.end(), false);
238
239 std::fill(this->positionDirectJointTargetsDeg.begin(),
240 this->positionDirectJointTargetsDeg.end(),
241 0.0);
242 std::fill(this->positionDirectTargetCounts.begin(),
243 this->positionDirectTargetCounts.end(),
244 0);
245 }
246
247 void reset(int axis)
248 {
249 std::lock_guard<std::mutex> lock(this->mutex);
250 this->jointTorques[axis] = 0.0;
251 this->jointVelocities[axis] = 0.0;
252 this->motorCurrents[axis] = 0.0;
253 this->hasTorqueSP[axis] = false;
254 this->hasCurrentSP[axis] = false;
255 this->ppJointTargetsDeg[axis] = 0.0;
256 this->ppTargetCounts[axis] = 0;
257 this->hasVelSP[axis] = false;
258 this->ppHasPosSP[axis] = false;
259 this->ppIsRelative[axis] = false;
260 this->ppPulseHi[axis] = false;
261 this->ppPulseCoolDown[axis] = false;
262 this->positionDirectJointTargetsDeg[axis] = 0.0;
263 this->positionDirectTargetCounts[axis] = 0;
264 }
265 };
266
268
269 /* --------------- CiA-402 power-state machine ------------------------ */
271
272 // First-cycle latches and seed
274 std::vector<bool> posLatched; // true if we have a valid target
277
278 // Timestamp unwrap (per-axis) for 32-bit drive timestamps
279 std::vector<uint32_t> tsLastRaw; // last raw 32-bit timestamp read from drive
280 std::vector<uint64_t> tsWraps; // number of wraps (increments on large backward jumps)
281
290
291 bool opRequested{false}; // true after the first run() call
292
293 // ------------- runtime profiling (run() duration and 5s average) -------------
294 std::chrono::steady_clock::time_point avgWindowStart{std::chrono::steady_clock::now()};
295 double runTimeAccumSec{0.0};
297
298 /** Dummy interaction mode for all the joints */
299 yarp::dev::InteractionModeEnum dummyInteractionMode{
300 yarp::dev::InteractionModeEnum::VOCAB_IM_STIFF};
301
302 Impl() = default;
303 ~Impl() = default;
304
305 // Convert joint degrees to loop-shaft counts for 0x607A, using the configured
306 // position-loop source (Enc1/Enc2) and mount (Motor/Joint).
307 int32_t jointDegToTargetCounts(size_t j, double jointDeg) const
308 {
309 // choose source and resolution
310 uint32_t res = 0;
311 Mount m = Mount::None;
312 switch (posLoopSrc[j])
313 {
314 case SensorSrc::Enc1:
315 res = enc1Res[j];
316 m = enc1Mount[j];
317 break;
318 case SensorSrc::Enc2:
319 res = enc2Res[j];
320 m = enc2Mount[j];
321 break;
322 default:
323 if (enc1Mount[j] != Mount::None)
324 {
325 res = enc1Res[j];
326 m = enc1Mount[j];
327 } else
328 {
329 res = enc2Res[j];
330 m = enc2Mount[j];
331 }
332 break;
333 }
334 double shaftDeg = jointDeg;
335 if (m == Mount::Motor)
336 shaftDeg = jointDeg * gearRatio[j];
337 else if (m == Mount::Joint)
338 shaftDeg = jointDeg; // pass-through
339 const double cnt = (res ? (shaftDeg / 360.0) * static_cast<double>(res) : 0.0);
340 long long q = llround(cnt);
345 return static_cast<int32_t>(q);
346 }
347
348 // Convert loop-shaft counts (0x607D/0x607A domain) back to joint degrees,
349 // applying encoder mount, gear ratio, and motion-sense inversion.
350 double targetCountsToJointDeg(size_t j, int32_t counts) const
351 {
352 // Apply motion-sense inversion: counts stored in the drive follow the loop shaft.
353 // If our joint coordinate is inverted, flip the sign to get a consistent mapping.
354 const bool inv = invertedMotionSenseDirection[j];
355 const int32_t cAdj = inv ? -counts : counts;
356
357 // choose source and resolution/mount just like jointDegToTargetCounts
358 uint32_t res = 0;
359 Mount m = Mount::None;
360 switch (posLoopSrc[j])
361 {
362 case SensorSrc::Enc1:
363 res = enc1Res[j];
364 m = enc1Mount[j];
365 break;
366 case SensorSrc::Enc2:
367 res = enc2Res[j];
368 m = enc2Mount[j];
369 break;
370 default:
371 if (enc1Mount[j] != Mount::None)
372 {
373 res = enc1Res[j];
374 m = enc1Mount[j];
375 } else
376 {
377 res = enc2Res[j];
378 m = enc2Mount[j];
379 }
380 break;
381 }
382
383 // counts -> shaft degrees
384 const double shaftDeg = res ? (double(cAdj) / double(res)) * 360.0 : 0.0;
385 // shaft -> joint degrees depending on mount
386 if (m == Mount::Motor)
387 {
388 return gearRatioInv[j] * shaftDeg; // joint = motor/gearRatio
389 }
390 // Joint-mounted or unknown → pass-through
391 return shaftDeg;
392 }
393
394 bool setPositionCountsLimits(int axis, int32_t minCounts, int32_t maxCounts)
395 {
396 constexpr auto logPrefix = "[setPositionCountsLimits]";
397 auto errorCode = this->ethercatManager.writeSDO<int32_t>(this->firstSlave + axis,
398 0x607D,
399 0x01,
400 minCounts);
402 {
403 yCError(CIA402,
404 "%s: setLimits: SDO write 0x607D:01 (min) failed for axis %d",
405 Impl::kClassName.data(),
406 axis);
407 return false;
408 }
409
410 errorCode = this->ethercatManager.writeSDO<int32_t>(this->firstSlave + axis,
411 0x607D,
412 0x02,
413 maxCounts);
415 {
416 yCError(CIA402,
417 "%s: setLimits: SDO write 0x607D:02 (max) failed for axis %d",
418 Impl::kClassName.data(),
419 axis);
420 return false;
421 }
422
423 return true;
424 }
425
426 //--------------------------------------------------------------------------
427 // One-shot SDO reads – here we only fetch encoder resolutions
428 //--------------------------------------------------------------------------
430 {
431 constexpr auto logPrefix = "[readEncoderResolutions]";
432
437
438 for (size_t j = 0; j < numAxes; ++j)
439 {
440 const int s = firstSlave + int(j);
441
442 uint32_t r1 = 0;
443 auto e1 = ethercatManager.readSDO<uint32_t>(s, 0x2110, 0x03, r1);
445
446 uint32_t r2 = 0;
447 auto e2 = ethercatManager.readSDO<uint32_t>(s, 0x2112, 0x03, r2);
449 }
450 for (size_t j = 0; j < numAxes; ++j)
451 {
452 enc1ResInv[j] = enc1Res[j] ? 1.0 / double(enc1Res[j]) : 0.0;
453 enc2ResInv[j] = enc2Res[j] ? 1.0 / double(enc2Res[j]) : 0.0;
454 }
455
456 // Print encoder resolution information for all axes
457 yCInfo(CIA402, "%s successfully read encoder resolutions from SDO", logPrefix);
458 for (size_t j = 0; j < numAxes; ++j)
459 {
460 yCDebug(CIA402,
461 "%s j=%zu enc1_resolution=%u (inv=%.9f), enc2_resolution=%u (inv=%.9f)",
462 logPrefix,
463 j,
464 enc1Res[j],
465 enc1ResInv[j],
466 enc2Res[j],
467 enc2ResInv[j]);
468 }
469
470 return true;
471 }
472
474 {
475 // Known Synapticon encodings (prefix scales; middle bytes encode rev, last timebase)
476 // RPM family
477 if (v == 0x00B44700u)
478 return {6.0, 1.0 / 6.0, "1 RPM"}; // 1 rpm -> 6 deg/s
479 if (v == 0xFFB44700u)
480 return {0.6, 1.0 / 0.6, "0.1 RPM"};
481 if (v == 0xFEB44700u)
482 return {0.06, 1.0 / 0.06, "0.01 RPM"};
483 if (v == 0xFDB44700u)
484 return {0.006, 1.0 / 0.006, "0.001 RPM"};
485 // RPS family
486 if (v == 0x00B40300u)
487 return {360.0, 1.0 / 360.0, "1 RPS"};
488 if (v == 0xFFB40300u)
489 return {36.0, 1.0 / 36.0, "0.1 RPS"};
490 if (v == 0xFEB40300u)
491 return {3.6, 1.0 / 3.6, "0.01 RPS"};
492 if (v == 0xFDB40300u)
493 return {0.36, 1.0 / 0.36, "0.001 RPS"};
494
495 // Fallback (spec says default is 1 RPM). Warn & assume 1 RPM.
496 return {6.0, 1.0 / 6.0, "UNKNOWN (assume 1 RPM)"};
497 }
498
500 {
501 constexpr auto logPrefix = "[readSiVelocityUnits]";
502
503 this->velToDegS.resize(numAxes);
504 this->degSToVel.resize(numAxes);
505
506 for (size_t j = 0; j < numAxes; ++j)
507 {
508 const int s = firstSlave + int(j);
509 // default 1 RPM See
510 // https://doc.synapticon.com/circulo/sw5.1/objects_html/6xxx/60a9.html?Highlight=0x60a9
511 uint32_t raw = 0x00B44700u;
512 auto e = ethercatManager.readSDO<uint32_t>(s, 0x60A9, 0x00, raw);
513
514 auto [toDegS, toDev, name] = this->decode60A9(raw);
515 velToDegS[j] = toDegS;
516 degSToVel[j] = toDev;
517
519 yCDebug(CIA402,
520 "%s j=%zu 0x60A9=0x%08X velocity_unit=%s (1_unit=%.6f_deg/s)",
521 logPrefix,
522 j,
523 raw,
524 name,
525 toDegS);
526 else
527 yWarning("%s j=%zu failed to read 0x60A9, assuming 1_RPM (1_unit=6_deg/s)",
528 logPrefix,
529 j);
530 }
531
532 yCInfo(CIA402, "%s successfully read velocity conversion units from SDO", logPrefix);
533 return true;
534 }
535
536 // Convert loop-shaft counts to joint degrees, using the configured
537 double loopCountsToJointDeg(std::size_t j, double counts) const
538 {
539 // Pick loop sensor & mount (we already filled posLoopSrc[] in open())
540 uint32_t res = 0;
541 Mount mount = Mount::None;
542 switch (posLoopSrc[j])
543 {
544 case SensorSrc::Enc1:
545 res = enc1Res[j];
546 mount = enc1Mount[j];
547 break;
548 case SensorSrc::Enc2:
549 res = enc2Res[j];
550 mount = enc2Mount[j];
551 break;
552 default: // fallback: prefer enc1 if available
553 if (enc1Mount[j] != Mount::None && enc1Res[j] != 0)
554 {
555 res = enc1Res[j];
556 mount = enc1Mount[j];
557 } else
558 {
559 res = enc2Res[j];
560 mount = enc2Mount[j];
561 }
562 break;
563 }
564 if (res == 0 || mount == Mount::None)
565 return 0.0; // no info
566
567 const double shaftDeg = (counts / double(res)) * 360.0; // degrees on the measured shaft
568 // Convert to JOINT side depending on mount
569
570 yCDebug(CIA402,
571 "loopCountsToJointDeg j=%zu counts=%.3f res=%u mount=%d -> shaftDeg=%.9f",
572 j,
573 counts,
574 res,
575 static_cast<int>(mount),
576 shaftDeg);
577
578 if (mount == Mount::Motor)
579 return shaftDeg * gearRatioInv[j]; // motor → joint
580 /* mount == Mount::Joint */ return shaftDeg; // already joint
581 }
582
583 bool setPositionWindowDeg(int j, double winDeg, double winTime_ms)
584 {
585 if (j < 0 || j >= static_cast<int>(this->numAxes))
586 {
587 yCError(CIA402,
588 "%s: setPositionWindowDeg: invalid joint index",
589 Impl::kClassName.data());
590 return false;
591 }
592 const int s = this->firstSlave + j;
593
594 uint32_t rawWin = 0;
595 if (std::isinf(winDeg))
596 {
597 // Per doc: monitoring OFF → target reached bit stays 0.
598 rawWin = 0xFFFFFFFFu;
599 } else
600 {
601 rawWin = static_cast<uint32_t>(
602 std::round(std::abs(this->jointDegToTargetCounts(std::size_t(j), winDeg))));
603 }
604 uint32_t rawTime = static_cast<uint32_t>(std::round(std::max(0.0, winTime_ms)));
605
606 auto e1 = this->ethercatManager.writeSDO<uint32_t>(s, 0x6067, 0x00, rawWin);
608 {
609 yCError(CIA402,
610 "%s: setPositionWindowDeg: SDO 0x6067 write failed on joint %d",
611 Impl::kClassName.data(),
612 j);
613 return false;
614 }
615 auto e2 = this->ethercatManager.writeSDO<uint32_t>(s, 0x6068, 0x00, rawTime);
617 {
618 yCError(CIA402,
619 "%s: setPositionWindowDeg: SDO 0x6068 write failed on joint %d",
620 Impl::kClassName.data(),
621 j);
622 return false;
623 }
624 return true;
625 }
626
627 bool getPositionControlStrategy(uint16_t& strategyValue)
628 {
629 constexpr auto logPrefix = "[getPositionControlStrategy]";
630
631 // Read from first axis only (all should be the same)
632 const int slaveIdx = firstSlave;
633 const auto err
634 = ethercatManager.readSDO<uint16_t>(slaveIdx, 0x2002, 0x00, strategyValue);
636 {
637 yCError(CIA402,
638 "%s failed to read 0x2002:00",
639 logPrefix);
640 return false;
641 }
642
643 yCInfo(CIA402,
644 "%s read position strategy %u from first axis",
645 logPrefix,
646 static_cast<unsigned>(strategyValue));
647 return true;
648 }
649
650 bool setPositionControlStrategy(uint16_t strategyValue)
651 {
652 constexpr auto logPrefix = "[setPositionControlStrategy]";
653
654 for (size_t j = 0; j < numAxes; ++j)
655 {
656 const int slaveIdx = firstSlave + static_cast<int>(j);
657 const auto err
658 = ethercatManager.writeSDO<uint16_t>(slaveIdx, 0x2002, 0x00, strategyValue);
660 {
661 yCError(CIA402,
662 "%s j=%zu failed to set 0x2002:00 (value=%u)",
663 logPrefix,
664 j,
665 static_cast<unsigned>(strategyValue));
666 return false;
667 }
668 }
669
670 yCInfo(CIA402,
671 "%s configured %zu axes with position strategy %u",
672 logPrefix,
673 numAxes,
674 static_cast<unsigned>(strategyValue));
675 return true;
676 }
677
678
680 std::vector<double>& kdNmSecPerDeg)
681 {
682 constexpr auto logPrefix = "[readSimplePidGains]";
683
684 kpNmPerDeg.resize(numAxes);
685 kdNmSecPerDeg.resize(numAxes);
686
687 for (size_t j = 0; j < numAxes; ++j)
688 {
689 const int slaveIdx = firstSlave + static_cast<int>(j);
690 float32 kpValue = 0.0f;
691 float32 kdValue = 0.0f;
692
693 const auto errKp = ethercatManager.readSDO<float32>(slaveIdx, 0x2012, 0x01, kpValue);
694 const auto errKd = ethercatManager.readSDO<float32>(slaveIdx, 0x2012, 0x03, kdValue);
695
698 {
699 yCError(CIA402,
700 "%s j=%zu failed to read gains (errs=%d,%d)",
701 logPrefix,
702 j,
703 static_cast<int>(errKp),
704 static_cast<int>(errKd));
705 return false;
706 }
707
708 const double degPerCount = loopCountsToJointDeg(j, 1.0);
709 const double kpMotor_mNm_per_deg = static_cast<double>(kpValue) / degPerCount;
710 const double kdMotor_mNmS_per_deg = static_cast<double>(kdValue) / degPerCount;
711
712 kpNmPerDeg[j] = (kpMotor_mNm_per_deg * gearRatio[j]) / 1000.0;
713 kdNmSecPerDeg[j] = (kdMotor_mNmS_per_deg * gearRatio[j]) / 1000.0;
714
715 yCDebug(CIA402,
716 "%s j=%zu read gains: kp_device=%.3f[mNm/inc], kd_device=%.3f[mNm*s/inc] "
717 "=> kp_motor=%.6f[mNm/deg], kd_motor=%.6f[mNm*s/deg] => "
718 "kp_joint=%.6f[Nm/deg], kd_joint=%.6f[Nm*s/deg]",
719 logPrefix,
720 j,
721 kpValue,
722 kdValue,
723 kpMotor_mNm_per_deg,
724 kdMotor_mNmS_per_deg,
725 kpNmPerDeg[j],
726 kdNmSecPerDeg[j]);
727 }
728 yCInfo(CIA402, "%s read simple PID gains for %zu axes", logPrefix, numAxes);
729 return true;
730 }
731
733 const std::vector<double>& kdNmSecPerDeg)
734 {
735 constexpr auto logPrefix = "[configureSimplePidGains]";
736
737 if (kpNmPerDeg.size() != numAxes || kdNmSecPerDeg.size() != numAxes)
738 {
739 yCError(CIA402,
740 "%s mismatched gain vector sizes (kp=%zu kd=%zu expected=%zu)",
741 logPrefix,
742 kpNmPerDeg.size(),
743 kdNmSecPerDeg.size(),
744 numAxes);
745 return false;
746 }
747
748 for (size_t j = 0; j < numAxes; ++j)
749 {
750 if (gearRatio[j] == 0.0)
751 {
752 yCError(CIA402, "%s j=%zu invalid gear ratio (0)", logPrefix, j);
753 return false;
754 }
755
756 const double degPerCount = loopCountsToJointDeg(j, 1.0);
757 if (degPerCount == 0.0)
758 {
759 yCError(CIA402,
760 "%s j=%zu cannot derive counts/deg (loop source missing)",
761 logPrefix,
762 j);
763 return false;
764 }
765 const double kpMotor_mNm_per_deg = (kpNmPerDeg[j] / gearRatio[j]) * 1000.0;
766 const double kdMotor_mNmS_per_deg = (kdNmSecPerDeg[j] / gearRatio[j]) * 1000.0;
767
768 const double kpDevice = kpMotor_mNm_per_deg * degPerCount;
769 const double kdDevice = kdMotor_mNmS_per_deg * degPerCount;
770
771 const float32 kpValue = static_cast<float32>(kpDevice);
772 const float32 kdValue = static_cast<float32>(kdDevice);
773 constexpr float32 kiValue = 0.0f;
774
775
776 yCDebug(CIA402,
777 "%s j=%zu computing gains: kp_joint=%.6f[Nm/deg], kd_joint=%.6f[Nm*s/deg], "
778 "gearRatio=%.6f, degPerCount=%.9f => kp_motor=%.6f[mNm/deg], "
779 "kd_motor=%.6f[mNm*s/deg] => kp_device=%.3f[mNm/inc], kd_device=%.3f[mNm*s/inc]",
780 logPrefix,
781 j,
782 kpNmPerDeg[j],
783 kdNmSecPerDeg[j],
784 gearRatio[j],
785 degPerCount,
786 kpMotor_mNm_per_deg,
787 kdMotor_mNmS_per_deg,
788 kpDevice,
789 kdDevice);
790
791 const int slaveIdx = firstSlave + static_cast<int>(j);
792 const auto errKp = ethercatManager.writeSDO<float32>(slaveIdx, 0x2012, 0x01, kpValue);
793 const auto errKi = ethercatManager.writeSDO<float32>(slaveIdx, 0x2012, 0x02, kiValue);
794 const auto errKd = ethercatManager.writeSDO<float32>(slaveIdx, 0x2012, 0x03, kdValue);
795
799 {
800 yCError(CIA402,
801 "%s j=%zu failed to program gains (errs=%d,%d,%d). Gains "
802 "Kp=%.3f[mNm/inc]=%.3f[Nm/deg], Kd=%.3f[mNm*s/inc]=%.3f[Nm*s/deg]",
803 logPrefix,
804 j,
805 static_cast<int>(errKp),
806 static_cast<int>(errKi),
807 static_cast<int>(errKd),
808 kpValue,
809 kpNmPerDeg[j],
810 kdValue,
811 kdNmSecPerDeg[j]);
812 return false;
813 }
814
815 yCDebug(CIA402,
816 "%s j=%zu Kp=%.3f[mNm/inc] Kd=%.3f[mNm*s/inc]",
817 logPrefix,
818 j,
819 kpValue,
820 kdValue);
821 }
822
823 yCInfo(CIA402, "%s programmed simple PID gains for %zu axes", logPrefix, numAxes);
824 return true;
825 }
826
828 {
829 constexpr auto logPrefix = "[readMotorConstants]";
830
833
834 for (size_t j = 0; j < numAxes; ++j)
835 {
836 const int s = firstSlave + int(j);
837 int32_t tcMicroNmA = 0;
838 if (ethercatManager.readSDO<int32_t>(s, 0x2003, 0x02, tcMicroNmA)
840 || tcMicroNmA == 0)
841 {
842 yWarning("%s j=%zu cannot read torque constant (0x2003:02) or zero, assuming 1.0 "
843 "Nm/A",
844 logPrefix,
845 j);
846 torqueConstants[j] = 1.0;
847 } else
848 {
849 // convert from µNm/A to Nm/A
850 torqueConstants[j] = double(tcMicroNmA) * 1e-6;
851 }
852
853 // first of all we need to read the motor rated current
854 // 0x6075:00 Motor Rated Current (UNSIGNED32)
855 uint32_t ratedCurrentMilliA = 0;
856 double ratedCurrentA = 0.0;
857 if (ethercatManager.readSDO<uint32_t>(s, 0x6075, 0x00, ratedCurrentMilliA)
859 || ratedCurrentMilliA == 0)
860 {
861 yWarning("%s j=%zu cannot read motor rated current (0x6075:00) or zero, assuming "
862 "1.0 A",
863 logPrefix,
864 j);
865 ratedCurrentA = 1.0;
866 } else
867 {
868 // convert from mA to A
869 ratedCurrentA = double(ratedCurrentMilliA) * 1e-3;
870 }
871
872 // Now we can read the max current 0x6073:0 16 bit unsigned
873 uint16_t maxPermille = 0;
874 if (ethercatManager.readSDO<uint16_t>(s, 0x6073, 0x00, maxPermille)
876 {
877 yWarning("%s j=%zu cannot read max current (0x6073:00), assuming 1000 per_mille",
878 logPrefix,
879 j);
880 maxPermille = 1000;
881 }
882
883 yCDebug(CIA402,
884 "%s j=%zu max_current=%u_permille (%.3fA), torque_constant=%.6f_Nm/A",
885 logPrefix,
886 j,
887 maxPermille,
888 (double(maxPermille) / 1000.0) * ratedCurrentA,
889 this->torqueConstants[j]);
890
891 maxCurrentsA[j] = (double(maxPermille) / 1000.0) * ratedCurrentA;
892 }
893
894 yCInfo(CIA402, "%s successfully read motor constants from SDO", logPrefix);
895 return true;
896 }
897
898 /**
899 * Read the gear-ratio (motor-revs : load-revs) for every axis and cache both
900 * the ratio and its inverse.
901 *
902 * 0x6091:01 numerator (UNSIGNED32, default 1)
903 * 0x6091:02 denominator (UNSIGNED32, default 1)
904 *
905 * If the object is missing or invalid the code silently falls back to 1:1.
906 */
908 {
909 constexpr auto logPrefix = "[readGearRatios]";
910
913
914 for (size_t j = 0; j < numAxes; ++j)
915 {
916 const int slaveIdx = firstSlave + static_cast<int>(j);
917
918 uint32_t num = 1U; // default numerator
919 uint32_t den = 1U; // default denominator
920
921 // ---- numerator ------------------------------------------------------
922 if (ethercatManager.readSDO<uint32_t>(slaveIdx, 0x6091, 0x01, num)
924 {
925 yWarning("%s j=%zu gear_ratio_numerator not available (0x6091:01), assuming 1",
926 logPrefix,
927 j);
928 num = 1U;
929 }
930
931 // ---- denominator ----------------------------------------------------
932 if (ethercatManager.readSDO<uint32_t>(slaveIdx, 0x6091, 0x02, den)
934 || den == 0U)
935 {
936 yWarning("%s j=%zu gear_ratio_denominator not available/zero (0x6091:02), assuming "
937 "1",
938 logPrefix,
939 j);
940 den = 1U;
941 }
942
943 yCDebug(CIA402,
944 "%s j=%zu gear_ratio=%u:%u (ratio=%.6f)",
945 logPrefix,
946 j,
947 num,
948 den,
949 static_cast<double>(num) / static_cast<double>(den));
950
951 // ---- cache value ----------------------------------------------------
952 gearRatio[j] = static_cast<double>(num) / static_cast<double>(den);
953 }
954
955 // Pre‑compute the inverse for fast use elsewhere -------------------------
956 for (size_t j = 0; j < numAxes; ++j)
957 {
958 gearRatioInv[j] = (gearRatio[j] != 0.0) ? (1.0 / gearRatio[j]) : 0.0;
959 }
960
961 yCInfo(CIA402, "%s successfully read gear ratios from SDO", logPrefix);
962 return true;
963 }
964
966 {
967 constexpr auto logPrefix = "[readTorqueValues]";
968
971
972 for (size_t j = 0; j < numAxes; ++j)
973 {
974 const int s = firstSlave + int(j);
975 uint32_t rated_mNm = 0;
976 if (ethercatManager.readSDO<uint32_t>(s, 0x6076, 0x00, rated_mNm)
978 {
979 yCError(CIA402, "%s j=%zu cannot read rated torque (0x6076:00)", logPrefix, j);
980 return false;
981 }
982 ratedMotorTorqueNm[j] = double(rated_mNm) / 1000.0; // motor Nm
983 }
984 for (size_t j = 0; j < numAxes; ++j)
985 {
986 const int s = firstSlave + int(j);
987 uint16_t maxPerm = 0;
988 if (ethercatManager.readSDO<uint16_t>(s, 0x6072, 0x00, maxPerm)
990 {
991 yCError(CIA402, "%s j=%zu cannot read max torque (0x6072:00)", logPrefix, j);
992 return false;
993 }
994 maxMotorTorqueNm[j] = (double(maxPerm) / 1000.0) * ratedMotorTorqueNm[j];
995 yCDebug(CIA402,
996 "%s j=%zu motor_rated_torque=%.3fNm max_torque=%.3fNm",
997 logPrefix,
998 j,
1000 maxMotorTorqueNm[j]);
1001 }
1002
1003 yCInfo(CIA402, "%s successfully read torque values from SDO", logPrefix);
1004 return true;
1005 }
1006
1008 {
1009 constexpr auto logPrefix = "[configureMaxTorqueFromJointNm]";
1010
1011 if (maxJointTorqueNm.size() != numAxes)
1012 {
1013 yCError(CIA402,
1014 "%s invalid vector size (%zu), expected %zu",
1015 logPrefix,
1016 maxJointTorqueNm.size(),
1017 numAxes);
1018 return false;
1019 }
1020
1021 for (size_t j = 0; j < numAxes; ++j)
1022 {
1023 const double jointNm = maxJointTorqueNm[j];
1024 if (jointNm <= 0.0)
1025 {
1026 yCError(CIA402,
1027 "%s j=%zu invalid max joint torque %.6f Nm (must be > 0)",
1028 logPrefix,
1029 j,
1030 jointNm);
1031 return false;
1032 }
1033
1034 if (gearRatio[j] <= 0.0)
1035 {
1036 yCError(CIA402,
1037 "%s j=%zu invalid gear ratio %.6f",
1038 logPrefix,
1039 j,
1040 gearRatio[j]);
1041 return false;
1042 }
1043
1044 if (ratedMotorTorqueNm[j] <= 0.0)
1045 {
1046 yCError(CIA402,
1047 "%s j=%zu invalid rated motor torque %.6f Nm",
1048 logPrefix,
1049 j,
1051 return false;
1052 }
1053
1054 constexpr uint16_t maxTorqueAdmissibleValue = 32767; // per SDO definition (0x6072 is uint16_t)
1055 const double motorNm = jointNm / gearRatio[j];
1056 const double perThousand = (motorNm / ratedMotorTorqueNm[j]) * 1000.0;
1057 const double clamped = std::clamp(perThousand, 0.0, static_cast<double>(maxTorqueAdmissibleValue));
1058 const uint16_t maxPerm = static_cast<uint16_t>(std::llround(clamped));
1059 const int s = firstSlave + static_cast<int>(j);
1060
1061 const auto err = ethercatManager.writeSDO<uint16_t>(s, 0x6072, 0x00, maxPerm);
1063 {
1064 yCError(CIA402,
1065 "%s j=%zu failed to write 0x6072:00",
1066 logPrefix,
1067 j);
1068 return false;
1069 }
1070
1071 maxMotorTorqueNm[j] = (static_cast<double>(maxPerm) / 1000.0) * ratedMotorTorqueNm[j];
1072
1073 yCInfo(CIA402,
1074 "%s j=%zu configured 0x6072 to %u permille (joint=%.6f Nm, motor=%.6f Nm)",
1075 logPrefix,
1076 j,
1077 static_cast<unsigned>(maxPerm),
1078 jointNm,
1079 maxMotorTorqueNm[j]);
1080 }
1081
1082 return true;
1083 }
1084
1085 void setSDORefSpeed(int j, double spDegS)
1086 {
1087 // ---- map JOINT deg/s -> LOOP SHAFT deg/s (based on pos loop source + mount) ----
1088 double shaft_deg_s = spDegS; // default assume joint shaft
1089 switch (this->posLoopSrc[j])
1090 {
1092 if (this->enc1Mount[j] == Impl::Mount::Motor)
1093 shaft_deg_s = spDegS * this->gearRatio[j];
1094 else if (this->enc1Mount[j] == Impl::Mount::Joint)
1095 shaft_deg_s = spDegS;
1096 break;
1098 if (this->enc2Mount[j] == Impl::Mount::Motor)
1099 shaft_deg_s = spDegS * this->gearRatio[j];
1100 else if (this->enc2Mount[j] == Impl::Mount::Joint)
1101 shaft_deg_s = spDegS;
1102 break;
1104 default:
1105 // Fallback: if we know which encoder is motor-mounted, assume that one; otherwise leave
1106 // as joint.
1107 if (this->enc1Mount[j] == Impl::Mount::Motor
1108 || this->enc2Mount[j] == Impl::Mount::Motor)
1109 shaft_deg_s = spDegS * this->gearRatio[j];
1110 break;
1111 }
1112
1113 // Convert deg/s on the loop shaft -> device velocity units using 0x60A9
1114 const int s = this->firstSlave + j;
1115 const int32_t vel = static_cast<int32_t>(std::llround(shaft_deg_s * this->degSToVel[j]));
1116 (void)this->ethercatManager.writeSDO<int32_t>(s, 0x6081, 0x00, vel);
1117 }
1118
1120 {
1121 std::lock_guard<std::mutex> lock(this->setPoints.mutex);
1122
1123 /**
1124 * Push user setpoints into RxPDOs according to the active control mode.
1125 * - Torque (CST): joint Nm → motor Nm → per‑thousand of rated motor torque (0x6071)
1126 * - Velocity (CSV): joint deg/s → loop‑shaft deg/s (mount aware) → rpm (0x60FF)
1127 * First‑cycle latches (velLatched/trqLatched) zero the command once when entering.
1128 */
1129 for (size_t j = 0; j < this->numAxes; ++j)
1130 {
1131 const int s = firstSlave + int(j);
1132 auto rx = this->ethercatManager.getRxPDO(s);
1133 const int opMode = this->controlModeState.active[j];
1134
1135 // clean rx targets
1136 rx->TargetPosition = 0;
1137 rx->TargetTorque = 0;
1138 rx->TargetVelocity = 0;
1139
1140 // ---------- TORQUE (CST) ----------
1141 if (opMode == VOCAB_CM_TORQUE)
1142 {
1143 if (!this->trqLatched[j])
1144 {
1145 rx->TargetTorque = 0;
1146 this->trqLatched[j] = true;
1147 } else
1148 {
1149 // YARP gives joint torque [Nm] → convert to MOTOR torque before 0x6071
1150 const double jointNm = setPoints.hasTorqueSP[j] ? setPoints.jointTorques[j]
1151 : 0.0;
1152 const double motorNm = (gearRatio[j] != 0.0) ? (jointNm / gearRatio[j]) : 0.0;
1153
1154 // 0x6071 is per-thousand of rated MOTOR torque (0x6076 in Nm)
1155 const int16_t tq_thousand = static_cast<int16_t>(std::llround(
1156 (ratedMotorTorqueNm[j] != 0.0 ? motorNm / ratedMotorTorqueNm[j] : 0.0)
1157 * 1000.0));
1158 rx->TargetTorque = this->invertedMotionSenseDirection[j] ? -tq_thousand
1159 : tq_thousand;
1160 }
1161 }
1162
1163 // ---------- VELOCITY (CSV) ----------
1164 if (opMode == VOCAB_CM_VELOCITY)
1165 {
1166 if (!velLatched[j])
1167 {
1168 rx->TargetVelocity = 0;
1169 velLatched[j] = true;
1170 } else
1171 {
1172 // YARP gives JOINT-side velocity [deg/s]
1173 const double joint_deg_s = setPoints.hasVelSP[j] ? setPoints.jointVelocities[j]
1174 : 0.0;
1175
1176 // Command must be on the SHAFT used by the velocity loop:
1177 // - if loop sensor is motor-mounted → convert joint→motor (× gearRatio)
1178 // - if loop sensor is joint-mounted → pass through
1179 double shaft_deg_s = joint_deg_s; // default: joint shaft
1180
1181 // The desired velocity setpoint depends on which encoder is used for
1182 // the position loop and how it is mounted.
1183 switch (posLoopSrc[j])
1184 {
1186 if (enc1Mount[j] == Impl::Mount::Motor)
1187 shaft_deg_s = joint_deg_s * gearRatio[j];
1188 else if (enc1Mount[j] == Impl::Mount::Joint)
1189 shaft_deg_s = joint_deg_s;
1190 // Impl::Mount::None → leave default (best-effort)
1191 break;
1192
1194 if (enc2Mount[j] == Impl::Mount::Motor)
1195 shaft_deg_s = joint_deg_s * gearRatio[j];
1196 else if (enc2Mount[j] == Impl::Mount::Joint)
1197 shaft_deg_s = joint_deg_s;
1198 break;
1199
1201 default:
1202 // Heuristic fallback: if we *know* the configured velocity feedback
1203 // is motor-mounted, assume motor shaft; otherwise joint shaft.
1204 // (Leave as joint if you don't keep velSrc vectors here.)
1205 break;
1206 }
1207
1208 // Convert deg/s → native velocity on the selected shaft for 0x60FF
1209 const double vel = shaft_deg_s * this->degSToVel[j];
1210 rx->TargetVelocity = static_cast<int32_t>(std::llround(vel))
1211 * (this->invertedMotionSenseDirection[j] ? -1 : 1);
1212 }
1213 }
1214
1215 // ---------- POSITION (PP) ----------
1216 if (opMode == VOCAB_CM_POSITION)
1217 {
1218
1219 if (this->ppState.ppHaltRequested[j])
1220 rx->Controlword |= (1u << 8);
1221 else
1222 rx->Controlword &= ~(1u << 8);
1223 // latch on first cycle in PP → do nothing until a user set-point arrives
1224 if (!posLatched[j])
1225 {
1226 // keep bit 5 asserted in PP (single-set-point method)
1227 rx->Controlword |= (1u << 5); // Change set immediately
1228 rx->Controlword &= ~(1u << 4); // make sure New set-point is low first
1229 posLatched[j] = true;
1230
1231 // compute seed from current measured joint angle
1232 const double currentJointDeg = this->variables.jointPositions[j];
1233 const int32_t seedStoreCounts
1234 = this->jointDegToTargetCounts(j, currentJointDeg);
1235
1236 // If the user already queued a PP target before the first cycle in PP, do
1237 // not overwrite it with the seed; otherwise seed the cached target with the
1238 // current position so the drive starts from a consistent reference.
1239 if (!setPoints.ppHasPosSP[j])
1240 {
1241 setPoints.ppTargetCounts[j] = seedStoreCounts;
1242 setPoints.ppJointTargetsDeg[j] = currentJointDeg;
1243 setPoints.ppIsRelative[j] = false;
1244 }
1245
1246 // Populate 0x607A with the cached target (seeded or user provided). The
1247 // rising edge on bit4 will be generated in the next cycle.
1248 const int32_t driveTargetCounts = this->invertedMotionSenseDirection[j]
1251 rx->TargetPosition = driveTargetCounts;
1252
1253 // If no user set-point was pending, schedule a one-shot bit4 pulse to align
1254 // the drive target to the current position.
1255 if (!setPoints.ppHasPosSP[j] && !setPoints.ppPulseHi[j])
1256 {
1257 setPoints.ppPulseHi[j] = true; // sync drive target to current position
1258 }
1259 } else
1260 {
1261 // (A) Always assert bit 5 in PP
1262 rx->Controlword |= (1u << 5);
1263
1264 // (B) If the previous cycle drove bit4 high, bring it low now (one-shot pulse)
1266 {
1267 rx->Controlword &= ~(1u << 4);
1268 setPoints.ppPulseCoolDown[j] = false;
1269 }
1270
1271 // (C) New set-point pending? write 0x607A and raise bit4
1272 int32_t targetPositionCounts = 0;
1274 {
1275 // Absolute/Relative selection (CW bit 6)
1276 if (setPoints.ppIsRelative[j])
1277 rx->Controlword |= (1u << 6);
1278 else
1279 rx->Controlword &= ~(1u << 6);
1280
1281 // Target position (0x607A)
1282 targetPositionCounts = this->invertedMotionSenseDirection[j]
1285
1286 // New set-point pulse (rising edge)
1287 rx->Controlword |= (1u << 4);
1288
1289 // consume the request and arm cooldown to drop bit4 next cycle
1290 setPoints.ppHasPosSP[j] = false;
1291 setPoints.ppPulseHi[j] = false;
1292 setPoints.ppPulseCoolDown[j] = true;
1293 } else
1294 {
1295 auto tx = this->ethercatManager.getTxView(s);
1296 targetPositionCounts = this->invertedMotionSenseDirection[j]
1300 {
1301 targetPositionCounts = tx.get<int32_t>(CiA402::TxField::Position6064,
1302 targetPositionCounts);
1303 }
1304
1305 setPoints.ppTargetCounts[j] = this->invertedMotionSenseDirection[j]
1306 ? -targetPositionCounts
1307 : targetPositionCounts;
1309 = this->targetCountsToJointDeg(j, targetPositionCounts);
1310 setPoints.ppIsRelative[j] = false;
1311 }
1312
1313 rx->TargetPosition = targetPositionCounts;
1314 }
1315 }
1316
1317 // ---------- POSITION DIRECT (CSP) ----------
1318 if (opMode == VOCAB_CM_POSITION_DIRECT)
1319 {
1320 if (!posLatched[j])
1321 {
1322 const double currentJointDeg = this->variables.jointPositions[j];
1323 const int32_t seedCounts = this->jointDegToTargetCounts(j, currentJointDeg);
1324 setPoints.positionDirectJointTargetsDeg[j] = currentJointDeg;
1325 setPoints.positionDirectTargetCounts[j] = seedCounts;
1326 posLatched[j] = true;
1327 }
1328
1329 const int32_t driveCounts = this->invertedMotionSenseDirection[j]
1332 rx->TargetPosition = driveCounts;
1333 }
1334
1335 if (opMode == VOCAB_CM_CURRENT)
1336 {
1337 if (!this->currLatched[j])
1338 {
1339 // the current control is actually a torque control
1340 rx->TargetTorque = 0;
1341 this->currLatched[j] = true;
1342 } else
1343 {
1344 // YARP gives Currents [A] → convert to MOTOR torque before 0x6071
1345 const double currentA = setPoints.hasCurrentSP[j] ? setPoints.motorCurrents[j]
1346 : 0.0;
1347
1348 // convert the current in torque using the torque constant
1349 const double torqueNm = currentA * this->torqueConstants[j];
1350
1351 // 0x6071 is per-thousand of rated MOTOR torque (0x6076 in Nm)
1352 const int16_t tq_thousand = static_cast<int16_t>(std::llround(
1353 (ratedMotorTorqueNm[j] != 0.0 ? torqueNm / ratedMotorTorqueNm[j] : 0.0)
1354 * 1000.0));
1355 rx->TargetTorque = this->invertedMotionSenseDirection[j] ? -tq_thousand
1356 : tq_thousand;
1357 }
1358 }
1359 }
1360 return true;
1361 }
1362
1364 {
1365 std::lock_guard<std::mutex> lock(this->variables.mutex);
1366
1367 // =====================================================================
1368 // SHAFT TRANSFORMATION HELPERS
1369 // =====================================================================
1370 // These lambdas handle the complex coordinate transformations between
1371 // motor shaft and joint/load shaft based on encoder mounting and gear ratios
1372
1373 // Position transformation: converts degrees on a specific shaft to the requested side
1374 auto shaftFromMount_pos = [&](double deg, Mount m, size_t j, bool asMotor) -> double {
1375 // deg = input position in degrees on the physical shaft of mount 'm'
1376 // asMotor = true if we want result on motor shaft, false for joint shaft
1377
1378 if (m == Impl::Mount::Motor)
1379 {
1380 // Input is on motor shaft
1381 return asMotor ? deg // Motor->Motor: no change
1382 : deg * gearRatioInv[j]; // Motor->Joint: divide by gear ratio
1383 }
1384 if (m == Impl::Mount::Joint)
1385 {
1386 // Input is on joint/load shaft
1387 return asMotor ? deg * gearRatio[j] // Joint->Motor: multiply by gear ratio
1388 : deg; // Joint->Joint: no change
1389 }
1390 return 0.0; // Impl::Mount::None or invalid
1391 };
1392
1393 // Velocity transformation: same logic as position but for velocities
1394 auto shaftFromMount_vel = [&](double degs, Mount m, size_t j, bool asMotor) -> double {
1395 if (m == Impl::Mount::Motor)
1396 {
1397 return asMotor ? degs : degs * gearRatioInv[j];
1398 }
1399 if (m == Impl::Mount::Joint)
1400 {
1401 return asMotor ? degs * gearRatio[j] : degs;
1402 }
1403 return 0.0;
1404 };
1405
1406 for (size_t j = 0; j < this->numAxes; ++j)
1407 {
1408 const int s = this->firstSlave + int(j);
1409 auto tx = this->ethercatManager.getTxView(s);
1410
1411 // =====================================================================
1412 // Status word bits
1413 // =====================================================================
1414 const uint16_t sw = tx.get<uint16_t>(CiA402::TxField::Statusword);
1415 this->variables.targetReached[j] = (sw & (1u << 10)) != 0;
1416
1417 // =====================================================================
1418 // RAW DATA EXTRACTION FROM PDOs
1419 // =====================================================================
1420 // Read raw encoder counts and velocities from the EtherCAT PDOs
1421 // These are the fundamental data sources before any interpretation
1422
1423 // Position data (in encoder counts)
1424 const int32_t p6064 = tx.get<int32_t>(CiA402::TxField::Position6064, 0); // CiA402
1425 // standard
1426 // position
1427 const int32_t pE1 = tx.has(CiA402::TxField::Enc1Pos2111_02) // Encoder 1 position (if
1428 // mapped)
1429 ? tx.get<int32_t>(CiA402::TxField::Enc1Pos2111_02)
1430 : 0;
1431 const int32_t pE2 = tx.has(CiA402::TxField::Enc2Pos2113_02) // Encoder 2 position (if
1432 // mapped)
1433 ? tx.get<int32_t>(CiA402::TxField::Enc2Pos2113_02)
1434 : 0;
1435
1436 // Velocity data (in RPM for CiA402, encoder-specific units for others)
1437 const int32_t v606C = tx.get<int32_t>(CiA402::TxField::Velocity606C, 0); // CiA402
1438 // standard
1439 // velocity
1440 // (RPM)
1441 const int32_t vE1 = tx.has(CiA402::TxField::Enc1Vel2111_03) // Encoder 1 velocity (if
1442 // mapped)
1443 ? tx.get<int32_t>(CiA402::TxField::Enc1Vel2111_03)
1444 : 0;
1445 const int32_t vE2 = tx.has(CiA402::TxField::Enc2Vel2113_03) // Encoder 2 velocity (if
1446 // mapped)
1447 ? tx.get<int32_t>(CiA402::TxField::Enc2Vel2113_03)
1448 : 0;
1449
1450 // =====================================================================
1451 // SOURCE INTERPRETATION HELPERS
1452 // =====================================================================
1453 // These lambdas convert raw data to degrees on the encoder's own shaft,
1454 // taking into account encoder resolution and the mounting location
1455
1456 // Convert position source to degrees on its own physical shaft
1457 auto posDegOnOwnShaft = [&](PosSrc s) -> std::pair<double, Mount> {
1458 switch (s)
1459 {
1460 case Impl::PosSrc::Enc1:
1461 // Direct encoder 1 readout: counts -> degrees using enc1 resolution
1462 return {double(pE1) * enc1ResInv[j] * 360.0, enc1Mount[j]};
1463
1464 case Impl::PosSrc::Enc2:
1465 // Direct encoder 2 readout: counts -> degrees using enc2 resolution
1466 return {double(pE2) * enc2ResInv[j] * 360.0, enc2Mount[j]};
1467
1469 default: {
1470 // CiA402 standard object - interpretation depends on drive's loop source
1471 // The drive tells us which encoder it uses internally via posLoopSrc
1472 if (posLoopSrc[j] == Impl::SensorSrc::Enc1 && enc1ResInv[j] != 0.0)
1473 return {double(p6064) * enc1ResInv[j] * 360.0, enc1Mount[j]};
1474 if (posLoopSrc[j] == Impl::SensorSrc::Enc2 && enc2ResInv[j] != 0.0)
1475 return {double(p6064) * enc2ResInv[j] * 360.0, enc2Mount[j]};
1476
1477 // Fallback: if loop source unknown, prefer enc1 if available
1478 if (enc1Mount[j] != Impl::Mount::None && enc1ResInv[j] != 0.0)
1479 return {double(p6064) * enc1ResInv[j] * 360.0, enc1Mount[j]};
1480 if (enc2Mount[j] != Impl::Mount::None && enc2ResInv[j] != 0.0)
1481 return {double(p6064) * enc2ResInv[j] * 360.0, enc2Mount[j]};
1482 return {0.0, Impl::Mount::None};
1483 }
1484 }
1485 };
1486 // Convert velocity source to deg/s on its own physical shaft
1487 auto velDegSOnOwnShaft = [&](VelSrc s) -> std::pair<double, Mount> {
1488 const double k = this->velToDegS[j]; // 1 device unit -> k deg/s
1489 switch (s)
1490 {
1491 case Impl::VelSrc::Enc1:
1492 // Direct encoder 1 velocity (already in RPM from PDO)
1493 return {double(vE1) * k, enc1Mount[j]};
1494
1495 case Impl::VelSrc::Enc2:
1496 // Direct encoder 2 velocity (already in RPM from PDO)
1497 return {double(vE2) * k, enc2Mount[j]};
1498
1500 default: {
1501 // CiA402 standard velocity (0x606C)
1502 // Per Synapticon docs, 0x606C is reported in the POSITION reference frame
1503 // ("driving shaft"). That is, if a Position encoder is configured, 606C is
1504 // scaled to that shaft (typically the joint/load). Only when no position
1505 // encoder exists, it falls back to the velocity/torque encoder shaft (often
1506 // motor).
1507 // Therefore, select the mount based on the POSITION loop source (0x2012:09),
1508 // not the velocity loop source.
1509
1510 // Primary: use reported position loop source
1512 return {double(v606C) * k, enc1Mount[j]};
1514 return {double(v606C) * k, enc2Mount[j]};
1515
1516 // Fallback heuristics when 0x2012:09 is Unknown:
1517 // - If we have a joint-side encoder on enc2 (typical dual-encoder setup),
1518 // assume 606C is joint-side.
1519 if (enc2Mount[j] == Impl::Mount::Joint)
1520 return {double(v606C) * k, enc2Mount[j]};
1521 // - Else prefer enc1 if present; otherwise enc2; else unknown
1522 if (enc1Mount[j] != Impl::Mount::None)
1523 return {double(v606C) * k, enc1Mount[j]};
1524 if (enc2Mount[j] != Impl::Mount::None)
1525 return {double(v606C) * k, enc2Mount[j]};
1526 return {0.0, Impl::Mount::None};
1527 }
1528 }
1529 };
1530
1531 // =====================================================================
1532 // POSITION FEEDBACK PROCESSING
1533 // =====================================================================
1534 // Apply the configured source selection and coordinate transformations
1535 {
1536 // Get raw position data from configured sources (on their own shafts)
1537 auto [degJ_src, mountJ] = posDegOnOwnShaft(posSrcJoint[j]); // Joint position source
1538 auto [degM_src, mountM] = posDegOnOwnShaft(posSrcMotor[j]); // Motor position source
1539
1540 // Transform to the requested coordinate systems
1541 const double jointDeg = shaftFromMount_pos(degJ_src, mountJ, j, /*asMotor*/ false);
1542 const double motorDeg = shaftFromMount_pos(degM_src, mountM, j, /*asMotor*/ true);
1543
1544 // Store in output variables
1545 this->variables.jointPositions[j]
1546 = this->invertedMotionSenseDirection[j] ? -jointDeg : jointDeg;
1547 this->variables.motorEncoders[j] //
1548 = this->invertedMotionSenseDirection[j] ? -motorDeg : motorDeg;
1549 }
1550
1551 // =====================================================================
1552 // VELOCITY FEEDBACK PROCESSING
1553 // =====================================================================
1554 // Same logic as position but for velocities
1555 {
1556 // Get raw velocity data from configured sources (on their own shafts)
1557 auto [degsJ_src, mountJ] = velDegSOnOwnShaft(velSrcJoint[j]); // Joint velocity
1558 // source
1559 auto [degsM_src, mountM] = velDegSOnOwnShaft(velSrcMotor[j]); // Motor velocity
1560 // source
1561
1562 // Transform to the requested coordinate systems
1563 const double jointDegS
1564 = shaftFromMount_vel(degsJ_src, mountJ, j, /*asMotor*/ false);
1565 const double motorDegS = shaftFromMount_vel(degsM_src, mountM, j, /*asMotor*/ true);
1566
1567 // Store in output variables
1568 this->variables.jointVelocities[j]
1569 = this->invertedMotionSenseDirection[j] ? -jointDegS : jointDegS;
1570 this->variables.motorVelocities[j]
1571 = this->invertedMotionSenseDirection[j] ? -motorDegS : motorDegS;
1572 }
1573
1574 // =====================================================================
1575 // OTHER FEEDBACK PROCESSING
1576 // =====================================================================
1577
1578 // Accelerations not provided by the drives (would require differentiation)
1579 this->variables.jointAccelerations[j] = 0.0;
1580 this->variables.motorAccelerations[j] = 0.0;
1581
1582 // --------- Torque feedback (motor → joint conversion) ----------
1583 // CiA402 torque feedback (0x6077) is always motor-side, per-thousand of rated torque
1584 const double tq_per_thousand
1585 = double(tx.get<int16_t>(CiA402::TxField::Torque6077, 0)) / 1000.0;
1586 const double motorNm = tq_per_thousand * this->ratedMotorTorqueNm[j];
1587 // Convert motor torque to joint torque using gear ratio
1588 const double signedMotorNm = this->invertedMotionSenseDirection[j] ? -motorNm : motorNm;
1589 this->variables.jointTorques[j] = signedMotorNm * this->gearRatio[j];
1590 this->variables.motorCurrents[j] = signedMotorNm / this->torqueConstants[j];
1591
1592 // --------- Safety signals (if mapped into PDOs) ----------
1593 // These provide real-time status of safety functions
1594 this->variables.STO[j] = tx.has(CiA402::TxField::STO_6621_01)
1595 ? tx.get<uint8_t>(CiA402::TxField::STO_6621_01)
1596 : 0; // Safe Torque Off status
1597 this->variables.SBC[j] = tx.has(CiA402::TxField::SBC_6621_02)
1598 ? tx.get<uint8_t>(CiA402::TxField::SBC_6621_02)
1599 : 0; // Safe Brake Control status
1600
1601 // --------- Timestamp (if available) ----------
1602 // Provides drive-side timing information for synchronization
1604 {
1605 const uint32_t raw = tx.get<uint32_t>(CiA402::TxField::Timestamp20F0, 0);
1606 // Unwrap 32-bit microsecond counter with threshold to avoid false wraps
1607 // due to small, non-monotonic clock adjustments.
1608 // Consider a wrap only if the backward jump is larger than half the range.
1609 if (raw < this->tsLastRaw[j])
1610 {
1611 const uint32_t back = this->tsLastRaw[j] - raw;
1612 if (back > TIMESTAMP_WRAP_HALF_RANGE)
1613 {
1614 this->tsWraps[j] += 1u;
1615 }
1616 // else: small backward step → no wraps increment
1617 }
1618 this->tsLastRaw[j] = raw;
1619
1620 const uint64_t us_ext
1621 = this->tsWraps[j] * TIMESTAMP_WRAP_PERIOD_US + static_cast<uint64_t>(raw);
1622 this->variables.feedbackTime[j]
1623 = static_cast<double>(us_ext) * MICROSECONDS_TO_SECONDS;
1624 } else
1625 {
1626 this->variables.feedbackTime[j] = 0.0;
1627 }
1628
1629 // the temperature is given in mC we need to convert Celsius
1630 this->variables.driveTemperatures[j]
1632 ? double(tx.get<int32_t>(CiA402::TxField::TemperatureDrive, 0)) * 1e-3
1633 : 0.0;
1634 }
1635
1636 return true;
1637 }
1638
1639 //--------------------------------------------------------------------------
1640 // YARP ➜ CiA-402 (Op-mode sent in RxPDO::OpMode)
1641 //--------------------------------------------------------------------------
1642 static int yarpToCiaOp(int cm)
1643 {
1644 using namespace yarp::dev;
1645 switch (cm)
1646 {
1647 case VOCAB_CM_IDLE:
1648 case VOCAB_CM_FORCE_IDLE:
1649 return 0; // “No mode” → disables the power stage
1650 case VOCAB_CM_POSITION:
1651 return 1; // Profile-Position (PP)
1652 case VOCAB_CM_VELOCITY:
1653 return 9; // Cyclic-Synch-Velocity (CSV)
1654 case VOCAB_CM_TORQUE:
1655 case VOCAB_CM_CURRENT:
1656 return 10; // Cyclic-Synch-Torque (CST)
1657 case VOCAB_CM_POSITION_DIRECT:
1658 return 8; // Cyclic-Synch-Position (CSP)
1659 default:
1660 return -1; // not supported
1661 }
1662 }
1663
1664 //--------------------------------------------------------------------------
1665 // CiA-402 ➜ YARP (decode for diagnostics)
1666 //--------------------------------------------------------------------------
1667 int ciaOpToYarpWithFlavor(int op, int cstFlavor)
1668 {
1669 if (op == 10)
1670 {
1671 return (cstFlavor == VOCAB_CM_CURRENT) ? VOCAB_CM_CURRENT : VOCAB_CM_TORQUE;
1672 }
1673 return this->ciaOpToYarp(op);
1674 }
1675
1676 static int ciaOpToYarp(int op)
1677 {
1678 using namespace yarp::dev;
1679 switch (op)
1680 {
1681 case 0:
1682 return VOCAB_CM_IDLE;
1683 case 1:
1684 return VOCAB_CM_POSITION;
1685 case 3:
1686 return VOCAB_CM_VELOCITY; // PP-vel still possible
1687 case 8:
1688 return VOCAB_CM_POSITION_DIRECT;
1689 case 9:
1690 return VOCAB_CM_VELOCITY;
1691 case 10:
1692 return VOCAB_CM_TORQUE;
1693 default:
1694 return VOCAB_CM_UNKNOWN;
1695 }
1696 }
1697
1698 static std::string_view yarpToString(int op)
1699 {
1700 using namespace yarp::dev;
1701 switch (op)
1702 {
1703 case VOCAB_CM_IDLE:
1704 return "VOCAB_CM_IDLE";
1705 case VOCAB_CM_FORCE_IDLE:
1706 return "VOCAB_CM_FORCE_IDLE";
1707 case VOCAB_CM_POSITION:
1708 return "VOCAB_CM_POSITION";
1709 case VOCAB_CM_VELOCITY:
1710 return "VOCAB_CM_VELOCITY";
1711 case VOCAB_CM_TORQUE:
1712 return "VOCAB_CM_TORQUE";
1713 case VOCAB_CM_CURRENT:
1714 return "VOCAB_CM_CURRENT";
1715 case VOCAB_CM_POSITION_DIRECT:
1716 return "VOCAB_CM_POSITION_DIRECT";
1717 default:
1718 return "UNKNOWN";
1719 }
1720 }
1721
1722 /**
1723 * Decode CiA 402 error code (0x603F:00) into a human‑readable string.
1724 * Includes explicit vendor codes seen in the field and broader family fallbacks.
1725 */
1727 {
1728 switch (code)
1729 {
1730 case 0x0000:
1731 return "No fault";
1732
1733 // === Your explicit mappings ===
1734 case 0x2220:
1735 return "Continuous over current (device internal)";
1736 case 0x2250:
1737 return "Short circuit (device internal)";
1738 case 0x2350:
1739 return "Load level fault (I2t, thermal state)";
1740 case 0x2351:
1741 return "Load level warning (I2t, thermal state)";
1742 case 0x3130:
1743 return "Phase failure";
1744 case 0x3131:
1745 return "Phase failure L1";
1746 case 0x3132:
1747 return "Phase failure L2";
1748 case 0x3133:
1749 return "Phase failure L3";
1750 case 0x3210:
1751 return "DC link over-voltage";
1752 case 0x3220:
1753 return "DC link under-voltage";
1754 case 0x3331:
1755 return "Field circuit interrupted";
1756 case 0x4210:
1757 return "Excess temperature device";
1758 case 0x4310:
1759 return "Excess temperature drive";
1760 case 0x5200:
1761 return "Control";
1762 case 0x5300:
1763 return "Operating unit";
1764 case 0x6010:
1765 return "Software reset (watchdog)";
1766 case 0x6320:
1767 return "Parameter error";
1768 case 0x7121:
1769 return "Motor blocked";
1770 case 0x7300:
1771 return "Sensor";
1772 case 0x7303:
1773 return "Resolver 1 fault";
1774 case 0x7304:
1775 return "Resolver 2 fault";
1776 case 0x7500:
1777 return "Communication";
1778 case 0x8612:
1779 return "Positioning controller (reference limit)";
1780 case 0xF002:
1781 return "Sub-synchronous run";
1782
1783 default:
1784 // === Family fallbacks (upper byte) ===
1785 switch (code & 0xFF00)
1786 {
1787 case 0x2200:
1788 return "Current/device-internal fault";
1789 case 0x2300:
1790 return "Motor/output circuit fault";
1791 case 0x3100:
1792 return "Phase/mains supply issue";
1793 case 0x3200:
1794 return "DC link voltage issue";
1795 case 0x3300:
1796 return "Field/armature circuit issue";
1797 case 0x4200:
1798 return "Excess temperature (device)";
1799 case 0x4300:
1800 return "Excess temperature (drive)";
1801 case 0x5200:
1802 return "Control device hardware / limits";
1803 case 0x5300:
1804 return "Operating unit / safety";
1805 case 0x6000:
1806 return "Software reset / watchdog";
1807 case 0x6300:
1808 return "Parameter/configuration error";
1809 case 0x7100:
1810 return "Motor blocked / mechanical issue";
1811 case 0x7300:
1812 return "Sensor/encoder fault";
1813 case 0x7500:
1814 return "Communication/internal";
1815 case 0x8600:
1816 return "Positioning controller (vendor specific)";
1817 case 0xF000:
1818 return "Timing/performance warning";
1819 default: {
1820 char buf[64];
1821 std::snprintf(buf, sizeof(buf), "Unknown 0x603F error: 0x%04X", code);
1822 return std::string(buf);
1823 }
1824 }
1825 }
1826 }
1827
1828}; // struct Impl
1829
1830// CiA402MotionControl — ctor / dtor
1831
1832CiA402MotionControl::CiA402MotionControl(double period, yarp::os::ShouldUseSystemClock useSysClock)
1833 : yarp::os::PeriodicThread(period, useSysClock, yarp::os::PeriodicThreadClock::Absolute)
1834 , m_impl(std::make_unique<Impl>())
1835{
1836}
1837
1839 : yarp::os::PeriodicThread(0.001 /*1 kHz*/,
1840 yarp::os::ShouldUseSystemClock::Yes,
1841 yarp::os::PeriodicThreadClock::Absolute)
1842 , m_impl(std::make_unique<Impl>())
1843{
1844}
1845
1847
1848// open() — bring the ring to OPERATIONAL and start the cyclic thread
1849
1850bool CiA402MotionControl::open(yarp::os::Searchable& cfg)
1851{
1852 constexpr auto logPrefix = "[open]";
1853
1854 // ---------------------------------------------------------------------
1855 // Parse driver parameters
1856 // ---------------------------------------------------------------------
1857 if (!cfg.check("ifname") || !cfg.find("ifname").isString())
1858 {
1859 yCError(CIA402, "%s: 'ifname' parameter is not a string", Impl::kClassName.data());
1860 return false;
1861 }
1862 if (!cfg.check("num_axes") || !cfg.find("num_axes").isInt32())
1863 {
1864 yCError(CIA402, "%s: 'num_axes' parameter is not an integer", Impl::kClassName.data());
1865 return false;
1866 }
1867
1868 if (!cfg.check("period") || !cfg.find("period").isFloat64())
1869 {
1870 yCError(CIA402, "%s: 'period' parameter is not a float64", Impl::kClassName.data());
1871 return false;
1872 }
1873 const double period = cfg.find("period").asFloat64();
1874 if (period <= 0.0)
1875 {
1876 yCError(CIA402, "%s: 'period' parameter must be positive", Impl::kClassName.data());
1877 return false;
1878 }
1879 this->setPeriod(period);
1880 yCDebug(CIA402, "%s: using period = %.6f s", logPrefix, period);
1881
1882 m_impl->numAxes = static_cast<size_t>(cfg.find("num_axes").asInt32());
1883 m_impl->firstSlave = cfg.check("first_slave", yarp::os::Value(1)).asInt32();
1884 if (cfg.check("expected_slave_name"))
1885 m_impl->expectedName = cfg.find("expected_slave_name").asString();
1886
1887 // =========================================================================
1888 // ENCODER CONFIGURATION PARSING
1889 // =========================================================================
1890 // This system supports dual encoders per axis with flexible source selection:
1891 // - Enc1: Typically motor-mounted (high resolution, motor shaft feedback)
1892 // - Enc2: Typically joint-mounted (load-side feedback after gearbox)
1893 // - 6064/606C: Standard CiA402 objects that follow the configured loop sources
1894 //
1895 // Each feedback type (position/velocity for joint/motor) can independently
1896 // choose its source, allowing configurations like:
1897 // - Joint position from load encoder, motor position from motor encoder
1898 // - Joint velocity from load encoder, motor velocity from 606C
1899
1900 // Parse helper functions for configuration strings
1901 auto parsePos = [&](const std::string& s) -> Impl::PosSrc {
1902 if (s == "enc1")
1903 return Impl::PosSrc::Enc1; // Use encoder 1 directly
1904 if (s == "enc2")
1905 return Impl::PosSrc::Enc2; // Use encoder 2 directly
1906 return Impl::PosSrc::S6064; // Use CiA402 standard object (follows loop source)
1907 };
1908 auto parseVel = [&](const std::string& s) -> Impl::VelSrc {
1909 if (s == "enc1")
1910 return Impl::VelSrc::Enc1; // Use encoder 1 velocity directly
1911 if (s == "enc2")
1912 return Impl::VelSrc::Enc2; // Use encoder 2 velocity directly
1913 return Impl::VelSrc::S606C; // Use CiA402 standard object (follows loop source)
1914 };
1915 auto parseMount = [&](const std::string& s) -> Impl::Mount {
1916 if (s == "motor")
1917 return Impl::Mount::Motor; // Encoder measures motor shaft (pre-gearbox)
1918 if (s == "joint")
1919 return Impl::Mount::Joint; // Encoder measures joint/load shaft (post-gearbox)
1920 if (s == "none")
1921 return Impl::Mount::None; // Encoder not present/not used
1922 yWarning("%s: invalid mount '%s' (allowed: none|motor|joint) → 'none'",
1923 Impl::kClassName.data(),
1924 s.c_str());
1925 return Impl::Mount::None;
1926 };
1927
1928 auto extractListOfStringFromSearchable = [this](const yarp::os::Searchable& cfg,
1929 const char* key,
1930 const std::vector<std::string>& acceptedKeys,
1931 std::vector<std::string>& result) -> bool {
1932 result.clear();
1933
1934 if (!cfg.check(key))
1935 {
1936 yCError(CIA402, "%s: missing key '%s'", Impl::kClassName.data(), key);
1937 return false;
1938 }
1939
1940 const yarp::os::Value& v = cfg.find(key);
1941 if (!v.isList())
1942 {
1943 yCError(CIA402, "%s: key '%s' is not a list", Impl::kClassName.data(), key);
1944 return false;
1945 }
1946
1947 const yarp::os::Bottle* lst = v.asList();
1948 if (!lst)
1949 {
1950 yCError(CIA402,
1951 "%s: internal error: list for key '%s' is null",
1952 Impl::kClassName.data(),
1953 key);
1954 return false;
1955 }
1956
1957 const size_t expected = static_cast<size_t>(m_impl->numAxes);
1958 const size_t actual = static_cast<size_t>(lst->size());
1959 if (actual != expected)
1960 {
1961 yCError(CIA402,
1962 "%s: list for key '%s' has incorrect size (%zu), expected (%zu)",
1963 Impl::kClassName.data(),
1964 key,
1965 actual,
1966 expected);
1967 return false;
1968 }
1969
1970 result.reserve(expected);
1971 for (int i = 0; i < lst->size(); ++i)
1972 {
1973 const yarp::os::Value& elem = lst->get(i);
1974
1975 if (!elem.isString())
1976 {
1977 yCError(CIA402,
1978 "%s: element %d in list for key '%s' is not a string",
1979 Impl::kClassName.data(),
1980 i,
1981 key);
1982 result.clear();
1983 return false;
1984 }
1985
1986 const std::string val = elem.asString();
1987
1988 // if acceptedKeys is non-empty, validate the value
1989 if (!acceptedKeys.empty())
1990 {
1991 if (std::find(acceptedKeys.begin(), acceptedKeys.end(), val) == acceptedKeys.end())
1992 {
1993 yCError(CIA402,
1994 "%s: invalid value '%s' in list for key '%s'",
1995 Impl::kClassName.data(),
1996 val.c_str(),
1997 key);
1998 result.clear();
1999 return false;
2000 }
2001 }
2002 result.push_back(val);
2003 }
2004
2005 return true;
2006 };
2007
2008 auto extractListOfDoubleFromSearchable = [this](const yarp::os::Searchable& cfg,
2009 const char* key,
2010 std::vector<double>& result) -> bool {
2011 result.clear();
2012
2013 if (!cfg.check(key))
2014 {
2015 yCError(CIA402, "%s: missing key '%s'", Impl::kClassName.data(), key);
2016 return false;
2017 }
2018
2019 const yarp::os::Value& v = cfg.find(key);
2020 if (!v.isList())
2021 {
2022 yCError(CIA402, "%s: key '%s' is not a list", Impl::kClassName.data(), key);
2023 return false;
2024 }
2025
2026 const yarp::os::Bottle* lst = v.asList();
2027 if (!lst)
2028 {
2029 yCError(CIA402,
2030 "%s: internal error: list for key '%s' is null",
2031 Impl::kClassName.data(),
2032 key);
2033 return false;
2034 }
2035
2036 const size_t expected = static_cast<size_t>(m_impl->numAxes);
2037 const size_t actual = static_cast<size_t>(lst->size());
2038 if (actual != expected)
2039 {
2040 yCError(CIA402,
2041 "%s: list for key '%s' has incorrect size (%zu), expected (%zu)",
2042 Impl::kClassName.data(),
2043 key,
2044 actual,
2045 expected);
2046 return false;
2047 }
2048
2049 result.reserve(expected);
2050 for (int i = 0; i < lst->size(); ++i)
2051 {
2052 const yarp::os::Value& elem = lst->get(i);
2053
2054 if (!elem.isFloat64() && !elem.isInt32() && !elem.isInt64() && !elem.isFloat32())
2055 {
2056 yCError(CIA402,
2057 "%s: element %d in list for key '%s' is not a number",
2058 Impl::kClassName.data(),
2059 i,
2060 key);
2061 result.clear();
2062 return false;
2063 }
2064
2065 result.push_back(elem.asFloat64());
2066 }
2067
2068 return true;
2069 };
2070
2071 auto extractListOfBoolFromSearchable = [this](const yarp::os::Searchable& cfg,
2072 const char* key,
2073 std::vector<bool>& result) -> bool {
2074 result.clear();
2075
2076 if (!cfg.check(key))
2077 {
2078 yCError(CIA402, "%s: missing key '%s'", Impl::kClassName.data(), key);
2079 return false;
2080 }
2081
2082 const yarp::os::Value& v = cfg.find(key);
2083 if (!v.isList())
2084 {
2085 yCError(CIA402, "%s: key '%s' is not a list", Impl::kClassName.data(), key);
2086 return false;
2087 }
2088
2089 const yarp::os::Bottle* lst = v.asList();
2090 if (!lst)
2091 {
2092 yCError(CIA402,
2093 "%s: internal error: list for key '%s' is null",
2094 Impl::kClassName.data(),
2095 key);
2096 return false;
2097 }
2098
2099 const size_t expected = static_cast<size_t>(m_impl->numAxes);
2100 const size_t actual = static_cast<size_t>(lst->size());
2101 if (actual != expected)
2102 {
2103 yCError(CIA402,
2104 "%s: list for key '%s' has incorrect size (%zu), expected (%zu)",
2105 Impl::kClassName.data(),
2106 key,
2107 actual,
2108 expected);
2109 return false;
2110 }
2111
2112 result.reserve(expected);
2113 for (int i = 0; i < lst->size(); ++i)
2114 {
2115 const yarp::os::Value& elem = lst->get(i);
2116
2117 if (!elem.isBool())
2118 {
2119 yCError(CIA402,
2120 "%s: element %d in list for key '%s' is not a boolean",
2121 Impl::kClassName.data(),
2122 i,
2123 key);
2124 result.clear();
2125 return false;
2126 }
2127
2128 result.push_back(elem.asBool());
2129 }
2130
2131 return true;
2132 };
2133
2134 // Encoder mounting configuration (where each encoder is physically located)
2135 // enc1_mount must be list of "motor" or "joint"
2136 // enc2_mount must be list of "motor", "joint" or "none"
2137 std::vector<std::string> enc1MStr; // encoder 1 mount per axis
2138 std::vector<std::string> enc2MStr; // encoder 2 mount per axis
2139
2140 if (!extractListOfStringFromSearchable(cfg, "enc1_mount", {"motor", "joint"}, enc1MStr))
2141 return false;
2142 if (!extractListOfStringFromSearchable(cfg, "enc2_mount", {"motor", "joint", "none"}, enc2MStr))
2143 return false;
2144
2145 std::vector<std::string> posSrcJointStr;
2146 std::vector<std::string> posSrcMotorStr;
2147 std::vector<std::string> velSrcJointStr;
2148 std::vector<std::string> velSrcMotorStr;
2149 if (!extractListOfStringFromSearchable(cfg,
2150 "position_feedback_joint",
2151 {"6064", "enc1", "enc2"},
2152 posSrcJointStr))
2153 return false;
2154 if (!extractListOfStringFromSearchable(cfg,
2155 "position_feedback_motor",
2156 {"6064", "enc1", "enc2"},
2157 posSrcMotorStr))
2158 return false;
2159 if (!extractListOfStringFromSearchable(cfg,
2160 "velocity_feedback_joint",
2161 {"606C", "enc1", "enc2"},
2162 velSrcJointStr))
2163 return false;
2164 if (!extractListOfStringFromSearchable(cfg,
2165 "velocity_feedback_motor",
2166 {"606C", "enc1", "enc2"},
2167 velSrcMotorStr))
2168 return false;
2169
2170 std::vector<double> positionWindowDeg; // position window for targetReached
2171 std::vector<double> timingWindowMs; // timing window for targetReached
2172 std::vector<double> maxJointTorqueNmFromConfig; // optional max torque on joint side [Nm]
2173 std::vector<double> simplePidKpNmPerDeg; // optional simple PID gains
2174 std::vector<double> simplePidKdNmSecPerDeg;
2175
2176 constexpr uint16_t kPositionStrategySimplePid = 1u;
2177 constexpr uint16_t kPositionStrategyCascadedPid = 2u;
2178 const bool useSimplePidMode
2179 = cfg.check("use_simple_pid_mode") ? cfg.find("use_simple_pid_mode").asBool() : false;
2180 const uint16_t desiredPositionStrategy
2181 = useSimplePidMode ? kPositionStrategySimplePid : kPositionStrategyCascadedPid;
2182
2183 if (!extractListOfDoubleFromSearchable(cfg, "position_window_deg", positionWindowDeg))
2184 return false;
2185 if (!extractListOfDoubleFromSearchable(cfg, "timing_window_ms", timingWindowMs))
2186 return false;
2187
2188 const bool hasMaxJointTorqueCfg = cfg.check("max_torque_joint_nm");
2189 if (hasMaxJointTorqueCfg
2190 && !extractListOfDoubleFromSearchable(cfg,
2191 "max_torque_joint_nm",
2192 maxJointTorqueNmFromConfig))
2193 {
2194 return false;
2195 }
2196
2197 const bool hasSimplePidKpCfg = cfg.check("simple_pid_kp_nm_per_deg");
2198 const bool hasSimplePidKdCfg = cfg.check("simple_pid_kd_nm_s_per_deg");
2199 const bool programSimplePidGains = hasSimplePidKpCfg || hasSimplePidKdCfg;
2200 if (hasSimplePidKpCfg != hasSimplePidKdCfg)
2201 {
2202 yCError(CIA402,
2203 "%s configuration must provide both simple_pid_kp_nm_per_deg and "
2204 "simple_pid_kd_nm_s_per_deg",
2205 logPrefix);
2206 return false;
2207 }
2208 if (programSimplePidGains)
2209 {
2210 if (!extractListOfDoubleFromSearchable(cfg, "simple_pid_kp_nm_per_deg", simplePidKpNmPerDeg))
2211 return false;
2212 if (!extractListOfDoubleFromSearchable(cfg,
2213 "simple_pid_kd_nm_s_per_deg",
2214 simplePidKdNmSecPerDeg))
2215 return false;
2216 }
2217
2218 for (size_t j = 0; j < m_impl->numAxes; ++j)
2219 {
2220 m_impl->enc1Mount.push_back(parseMount(enc1MStr[j]));
2221 m_impl->enc2Mount.push_back(parseMount(enc2MStr[j]));
2222 m_impl->posSrcJoint.push_back(parsePos(posSrcJointStr[j]));
2223 m_impl->posSrcMotor.push_back(parsePos(posSrcMotorStr[j]));
2224 m_impl->velSrcJoint.push_back(parseVel(velSrcJointStr[j]));
2225 m_impl->velSrcMotor.push_back(parseVel(velSrcMotorStr[j]));
2226 }
2227
2228 const std::string ifname = cfg.find("ifname").asString();
2229 // Optional runtime knobs
2230 const int pdoTimeoutUs = cfg.check("pdo_timeout_us") ? cfg.find("pdo_timeout_us").asInt32()
2231 : -1;
2232 const bool enableDc = cfg.check("enable_dc") ? cfg.find("enable_dc").asBool() : true;
2233 const int dcShiftNs = cfg.check("dc_shift_ns") ? cfg.find("dc_shift_ns").asInt32() : 0;
2234 yCInfo(CIA402, "%s opening EtherCAT manager on interface %s", logPrefix, ifname.c_str());
2235
2236 if (!extractListOfBoolFromSearchable(cfg,
2237 "inverted_motion_sense_direction",
2238 m_impl->invertedMotionSenseDirection))
2239 return false;
2240
2241 auto vecBoolToString = [](const std::vector<bool>& v) -> std::string {
2242 std::string s;
2243 for (size_t i = 0; i < v.size(); ++i)
2244 {
2245 s += (v[i] ? "true" : "false");
2246 if (i + 1 < v.size())
2247 s += ", ";
2248 }
2249 return s;
2250 };
2251
2252 yCDebug(CIA402,
2253 "%s: inverted_motion_sense_direction = [%s]",
2254 logPrefix,
2255 vecBoolToString(m_impl->invertedMotionSenseDirection).c_str());
2256
2257 // ---------------------------------------------------------------------
2258 // Initialize the EtherCAT manager (ring in SAFE‑OP)
2259 // ---------------------------------------------------------------------
2260
2261 const auto ecErr = m_impl->ethercatManager.init(ifname);
2263 {
2264 yCError(CIA402,
2265 "%s EtherCAT initialization failed with error code %d",
2266 logPrefix,
2267 static_cast<int>(ecErr));
2268 return false;
2269 }
2270
2271 if (pdoTimeoutUs > 0)
2272 {
2273 m_impl->ethercatManager.setPdoTimeoutUs(pdoTimeoutUs);
2274 yCInfo(CIA402,
2275 "%s PDO receive timeout set to %d us",
2276 logPrefix,
2277 m_impl->ethercatManager.getPdoTimeoutUs());
2278 } else
2279 {
2280 yCInfo(CIA402,
2281 "%s using default PDO receive timeout of %d us",
2282 logPrefix,
2283 m_impl->ethercatManager.getPdoTimeoutUs());
2284 }
2285
2286 // We'll enable DC later, after going OP, using the configured period
2287 const uint32_t cycleNs = static_cast<uint32_t>(std::llround(this->getPeriod() * 1e9));
2288
2289 // =========================================================================
2290 // DRIVE LOOP SOURCE CONFIGURATION READING
2291 // =========================================================================
2292 // Read which encoders the drive uses internally for position/velocity loops
2293 // This affects how 6064/606C values should be interpreted
2294
2295 // Loop-source readers (local lambdas)
2296 auto readPosLoopSrc = [&](size_t j) -> Impl::SensorSrc {
2297 const int s = m_impl->firstSlave + int(j);
2298 uint8_t src = 0;
2299 auto e = m_impl->ethercatManager.readSDO<uint8_t>(s, 0x2012, 0x09, src);
2301 {
2302 yCError(CIA402,
2303 "%s: failed to read position loop source (joint %zu)",
2304 Impl::kClassName.data(),
2305 j);
2307 }
2308 return (src == 1) ? Impl::SensorSrc::Enc1
2309 : (src == 2) ? Impl::SensorSrc::Enc2
2311 };
2312 auto readVelLoopSrc = [&](size_t j) -> Impl::SensorSrc {
2313 const int s = m_impl->firstSlave + int(j);
2314 uint8_t src = 0;
2315 auto e = m_impl->ethercatManager.readSDO<uint8_t>(s, 0x2011, 0x05, src);
2318 return (src == 1) ? Impl::SensorSrc::Enc1
2319 : (src == 2) ? Impl::SensorSrc::Enc2
2321 };
2322
2323 // --------- PDO Mapping Availability Checks ----------
2324 // These check if encoder data was successfully mapped into the PDOs
2325 // during the EtherCAT initialization phase
2326 auto hasEnc1Pos = [&](size_t j) {
2327 const int s = m_impl->firstSlave + int(j);
2328 return m_impl->ethercatManager.getTxView(s).has(CiA402::TxField::Enc1Pos2111_02);
2329 };
2330 auto hasEnc1Vel = [&](size_t j) {
2331 const int s = m_impl->firstSlave + int(j);
2332 return m_impl->ethercatManager.getTxView(s).has(CiA402::TxField::Enc1Vel2111_03);
2333 };
2334 auto hasEnc2Pos = [&](size_t j) {
2335 const int s = m_impl->firstSlave + int(j);
2336 return m_impl->ethercatManager.getTxView(s).has(CiA402::TxField::Enc2Pos2113_02);
2337 };
2338 auto hasEnc2Vel = [&](size_t j) {
2339 const int s = m_impl->firstSlave + int(j);
2340 return m_impl->ethercatManager.getTxView(s).has(CiA402::TxField::Enc2Vel2113_03);
2341 };
2342
2343 yCInfo(CIA402,
2344 "%s using %zu axes, EtherCAT slaves %d to %d",
2345 logPrefix,
2346 m_impl->numAxes,
2347 m_impl->firstSlave,
2348 m_impl->firstSlave + int(m_impl->numAxes) - 1);
2349
2350 // --------- Read drive-internal loop sources ----------
2351 // These determine how CiA402 standard objects (6064/606C) should be interpreted
2352 m_impl->posLoopSrc.resize(m_impl->numAxes, Impl::SensorSrc::Unknown);
2353 m_impl->velLoopSrc.resize(m_impl->numAxes, Impl::SensorSrc::Unknown);
2354 for (size_t j = 0; j < m_impl->numAxes; ++j)
2355 {
2356 m_impl->posLoopSrc[j] = readPosLoopSrc(j);
2357 m_impl->velLoopSrc[j] = readVelLoopSrc(j);
2358 }
2359
2360 // =========================================================================
2361 // CONFIGURATION VALIDATION
2362 // =========================================================================
2363 // Strict validation: requested encoders must be both mapped in PDOs AND
2364 // have valid mount points. This prevents runtime errors from misconfiguration.
2365 for (size_t j = 0; j < m_impl->numAxes; ++j)
2366 {
2367 auto bad = [&](const char* what) {
2368 yCError(CIA402, "%s j=%zu invalid configuration: %s", logPrefix, j, what);
2369 return true;
2370 };
2371
2372 // --------- Position feedback validation ----------
2373 if (m_impl->posSrcJoint[j] == Impl::PosSrc::Enc1
2374 && (m_impl->enc1Mount[j] == Impl::Mount::None || !hasEnc1Pos(j)))
2375 {
2376 if (bad("pos_joint=enc1 but enc1 not mounted/mapped"))
2377 return false;
2378 }
2379 if (m_impl->posSrcJoint[j] == Impl::PosSrc::Enc2
2380 && (m_impl->enc2Mount[j] == Impl::Mount::None || !hasEnc2Pos(j)))
2381 {
2382 if (bad("pos_joint=enc2 but enc2 not mounted/mapped"))
2383 return false;
2384 }
2385
2386 if (m_impl->posSrcMotor[j] == Impl::PosSrc::Enc1
2387 && (m_impl->enc1Mount[j] == Impl::Mount::None || !hasEnc1Pos(j)))
2388 {
2389 if (bad("pos_motor=enc1 but enc1 not mounted/mapped"))
2390 return false;
2391 }
2392 if (m_impl->posSrcMotor[j] == Impl::PosSrc::Enc2
2393 && (m_impl->enc2Mount[j] == Impl::Mount::None || !hasEnc2Pos(j)))
2394 {
2395 if (bad("pos_motor=enc2 but enc2 not mounted/mapped"))
2396 return false;
2397 }
2398
2399 // --------- Velocity feedback validation ----------
2400 if (m_impl->velSrcJoint[j] == Impl::VelSrc::Enc1
2401 && (m_impl->enc1Mount[j] == Impl::Mount::None || !hasEnc1Vel(j)))
2402 {
2403 if (bad("vel_joint=enc1 but enc1 not mounted/mapped"))
2404 return false;
2405 }
2406 if (m_impl->velSrcJoint[j] == Impl::VelSrc::Enc2
2407 && (m_impl->enc2Mount[j] == Impl::Mount::None || !hasEnc2Vel(j)))
2408 {
2409 if (bad("vel_joint=enc2 but enc2 not mounted/mapped"))
2410 return false;
2411 }
2412
2413 if (m_impl->velSrcMotor[j] == Impl::VelSrc::Enc1
2414 && (m_impl->enc1Mount[j] == Impl::Mount::None || !hasEnc1Vel(j)))
2415 {
2416 if (bad("vel_motor=enc1 but enc1 not mounted/mapped"))
2417 return false;
2418 }
2419 if (m_impl->velSrcMotor[j] == Impl::VelSrc::Enc2
2420 && (m_impl->enc2Mount[j] == Impl::Mount::None || !hasEnc2Vel(j)))
2421 {
2422 if (bad("vel_motor=enc2 but enc2 not mounted/mapped"))
2423 return false;
2424 }
2425 }
2426
2427 // ---------------------------------------------------------------------
2428 // Read static SDO parameters (encoders, velocity units, gear ratios, motor limits)
2429 // ---------------------------------------------------------------------
2430 if (!m_impl->readEncoderResolutions())
2431 {
2432 yCError(CIA402, "%s failed to read encoder resolutions from SDO", logPrefix);
2433 return false;
2434 }
2435 if (!m_impl->readSiVelocityUnits())
2436 {
2437 yCError(CIA402, "%s failed to read velocity conversions from SDO", logPrefix);
2438 return false;
2439 }
2440 if (!m_impl->readGearRatios())
2441 {
2442 yCError(CIA402, "%s failed to read gear ratios from SDO", logPrefix);
2443 return false;
2444 }
2445 if (!m_impl->readMotorConstants())
2446 {
2447 yCError(CIA402, "%s failed to read motor constants from SDO", logPrefix);
2448 return false;
2449 }
2450 if (!m_impl->readTorqueValues())
2451 {
2452 yCError(CIA402, "%s failed to read torque values from SDO", logPrefix);
2453 return false;
2454 }
2455
2456 if (hasMaxJointTorqueCfg)
2457 {
2458 if (!m_impl->configureMaxTorqueFromJointNm(maxJointTorqueNmFromConfig))
2459 {
2460 yCError(CIA402,
2461 "%s failed to configure max torque (0x6072) from max_torque_joint_nm",
2462 logPrefix);
2463 return false;
2464 }
2465 } else
2466 {
2467 yCDebug(CIA402,
2468 "%s max_torque_joint_nm not provided: using drive 0x6072 values",
2469 logPrefix);
2470 }
2471
2472 // get the current control strategy
2473 uint16_t currentStrategy = 0;
2474 if (!m_impl->getPositionControlStrategy(currentStrategy))
2475 {
2476 yCError(CIA402, "%s failed to get current control strategy", logPrefix);
2477 return false;
2478 }
2479 yCInfo(CIA402,
2480 "%s current control strategy is %u",
2481 logPrefix,
2482 static_cast<unsigned>(currentStrategy));
2483
2484
2485 yCInfo(CIA402,
2486 "%s requested position strategy %u (%s)",
2487 logPrefix,
2488 static_cast<unsigned>(desiredPositionStrategy),
2489 useSimplePidMode ? "simple PID" : "cascaded PID");
2490
2491 if (!m_impl->setPositionControlStrategy(desiredPositionStrategy))
2492 {
2493 yCError(CIA402, "%s failed to configure position control strategy", logPrefix);
2494 return false;
2495 }
2496
2497 // get again the control strategy to verify
2498 if (!m_impl->getPositionControlStrategy(currentStrategy))
2499 {
2500 yCError(CIA402, "%s failed to get current control strategy", logPrefix);
2501 return false;
2502 }
2503 yCInfo(CIA402,
2504 "%s current control strategy after configuration is %u",
2505 logPrefix,
2506 static_cast<unsigned>(currentStrategy));
2507
2508 const bool enableSimplePidGainsIo = (desiredPositionStrategy == kPositionStrategySimplePid);
2509 if (!enableSimplePidGainsIo && programSimplePidGains)
2510 {
2511 yCWarning(CIA402,
2512 "%s simple PID gains provided but position strategy is not simple PID; skipping "
2513 "0x2012 gains programming",
2514 logPrefix);
2515 }
2516
2517 if (enableSimplePidGainsIo && programSimplePidGains)
2518 {
2519 if (!m_impl->configureSimplePidGains(simplePidKpNmPerDeg, simplePidKdNmSecPerDeg))
2520 {
2521 yCError(CIA402, "%s failed to program simple PID gains", logPrefix);
2522 return false;
2523 }
2524 } else if (enableSimplePidGainsIo)
2525 {
2526 yCDebug(CIA402,
2527 "%s skipping simple PID gains programming (config keys not provided)",
2528 logPrefix);
2529 }
2530
2531 std::vector<double> readKp;
2532 std::vector<double> readKd;
2533 bool simplePidGainsAvailable = false;
2534 if (enableSimplePidGainsIo)
2535 {
2536 // read the simple PID gains to verify
2537 if (!m_impl->readSimplePidGains(readKp, readKd))
2538 {
2539 yCError(CIA402, "%s failed to read back simple PID gains", logPrefix);
2540 return false;
2541 }
2542 simplePidGainsAvailable = true;
2543
2544 for (size_t j = 0; j < m_impl->numAxes; ++j)
2545 {
2546 yCDebug(CIA402,
2547 "%s j=%zu simple PID gains: Kp=%.6f Nm/deg, Kd=%.6f Nm·s/deg",
2548 logPrefix,
2549 j,
2550 readKp[j],
2551 readKd[j]);
2552 }
2553 }
2554
2555 // ---------------------------------------------------------------------
2556 // Set the position limits (SDO 607D)
2557 // ---------------------------------------------------------------------
2558 if (!extractListOfDoubleFromSearchable(cfg,
2559 "pos_limit_min_deg",
2560 m_impl->limits.minPositionLimitDeg))
2561 {
2562 yCError(CIA402, "%s failed to parse pos_limit_min_deg", logPrefix);
2563 return false;
2564 }
2565 if (!extractListOfDoubleFromSearchable(cfg,
2566 "pos_limit_max_deg",
2567 m_impl->limits.maxPositionLimitDeg))
2568 {
2569 yCError(CIA402, "%s failed to parse pos_limit_max_deg", logPrefix);
2570 return false;
2571 }
2572 if (!extractListOfBoolFromSearchable(cfg,
2573 "use_position_limits_from_config",
2574 m_impl->limits.usePositionLimitsFromConfig))
2575 {
2576 yCError(CIA402, "%s failed to parse use_position_limits_from_config", logPrefix);
2577 return false;
2578 }
2579
2580 if (m_impl->limits.minPositionLimitDeg.size() != m_impl->numAxes
2581 || m_impl->limits.maxPositionLimitDeg.size() != m_impl->numAxes
2582 || m_impl->limits.usePositionLimitsFromConfig.size() != m_impl->numAxes)
2583 {
2584 yCError(CIA402,
2585 "%s position limit lists must have exactly %zu elements",
2586 logPrefix,
2587 m_impl->numAxes);
2588 return false;
2589 }
2590
2591 for (size_t j = 0; j < m_impl->numAxes; ++j)
2592 {
2593 const bool inv = m_impl->invertedMotionSenseDirection[j];
2594
2595 if (m_impl->limits.usePositionLimitsFromConfig[j])
2596 {
2597 // Convert joint degrees to loop-shaft counts and write to SDO 0x607D
2598 const int32_t lowerCounts
2599 = m_impl->jointDegToTargetCounts(j, m_impl->limits.minPositionLimitDeg[j]);
2600 const int32_t upperCounts
2601 = m_impl->jointDegToTargetCounts(j, m_impl->limits.maxPositionLimitDeg[j]);
2602
2603 int32_t minCounts = 0;
2604 int32_t maxCounts = 0;
2605 if (!inv)
2606 {
2607 minCounts = lowerCounts;
2608 maxCounts = upperCounts;
2609 } else
2610 {
2611 // Decreasing mapping f(x) = -counts(x) → [L, U] maps to [f(U), f(L)]
2612 minCounts = -upperCounts;
2613 maxCounts = -lowerCounts;
2614 }
2615
2616 if (!m_impl->setPositionCountsLimits(j, minCounts, maxCounts))
2617 {
2618 yCError(CIA402, "%s j=%zu failed to set position limits", logPrefix, j);
2619 return false;
2620 }
2621 } else
2622 {
2623 // Read 0x607D:min/max from SDO, convert to degrees, and cache into limits vectors.
2624 const int s = m_impl->firstSlave + static_cast<int>(j);
2625 int32_t minCounts = 0;
2626 int32_t maxCounts = 0;
2627 auto e1 = m_impl->ethercatManager.readSDO<int32_t>(s, 0x607D, 0x01, minCounts);
2628 auto e2 = m_impl->ethercatManager.readSDO<int32_t>(s, 0x607D, 0x02, maxCounts);
2631 {
2632 yCError(CIA402, "%s j=%zu failed to read position limits from SDO", logPrefix, j);
2633 return false;
2634 }
2635
2636 // Convert counts back to joint-space degrees.
2637 double minDeg = 0.0;
2638 double maxDeg = 0.0;
2639 if (!inv)
2640 {
2641 minDeg = m_impl->targetCountsToJointDeg(j, minCounts);
2642 maxDeg = m_impl->targetCountsToJointDeg(j, maxCounts);
2643 } else
2644 {
2645 // When inverted, SDO holds [-U, -L]; swap to recover [L, U] in degrees.
2646 minDeg = m_impl->targetCountsToJointDeg(j, maxCounts);
2647 maxDeg = m_impl->targetCountsToJointDeg(j, minCounts);
2648 }
2649
2650 m_impl->limits.minPositionLimitDeg[j] = minDeg;
2651 m_impl->limits.maxPositionLimitDeg[j] = maxDeg;
2652 }
2653 }
2654
2655 // ---------------------------------------------------------------------
2656 // Idle all drives (switch‑on disabled, no mode selected)
2657 // ---------------------------------------------------------------------
2658 for (size_t j = 0; j < m_impl->numAxes; ++j)
2659 {
2660 const int slave = m_impl->firstSlave + static_cast<int>(j);
2661 auto* rx = m_impl->ethercatManager.getRxPDO(slave);
2662 if (!rx)
2663 {
2664 yCError(CIA402, "%s invalid slave index %d for axis %zu", logPrefix, slave, j);
2665 return false;
2666 }
2667 rx->Controlword = 0x0000;
2668 rx->OpMode = 0;
2669 }
2670
2671 // Send one frame so the outputs take effect
2672 if (m_impl->ethercatManager.sendReceive() != ::CiA402::EthercatManager::Error::NoError)
2673 {
2674 yCError(CIA402, "%s initial EtherCAT send/receive after SDO reading failed", logPrefix);
2675 return false;
2676 }
2677
2678 // ---------------------------------------------------------------------
2679 // Configure position windows (targetReached thresholds)
2680 // ---------------------------------------------------------------------
2681 for (int j = 0; j < m_impl->numAxes; ++j)
2682 {
2683 if (!m_impl->setPositionWindowDeg(j, positionWindowDeg[j], timingWindowMs[j]))
2684 {
2685 yCError(CIA402, "%s j=%d failed to set position window", logPrefix, j);
2686 return false;
2687 }
2688 }
2689
2690 // ---------------------------------------------------------------------
2691 // Allocate runtime containers and CiA‑402 state machines
2692 // ---------------------------------------------------------------------
2693
2694 m_impl->variables.resizeContainers(m_impl->numAxes);
2695 m_impl->setPoints.resize(m_impl->numAxes);
2696 m_impl->setPoints.reset();
2697 m_impl->controlModeState.resize(m_impl->numAxes);
2698 m_impl->sm.resize(m_impl->numAxes);
2699 m_impl->velLatched.assign(m_impl->numAxes, false);
2700 m_impl->trqLatched.assign(m_impl->numAxes, false);
2701 m_impl->currLatched.assign(m_impl->numAxes, false);
2702 m_impl->posLatched.assign(m_impl->numAxes, false);
2703 m_impl->torqueSeedNm.assign(m_impl->numAxes, 0.0);
2704 m_impl->tsLastRaw.assign(m_impl->numAxes, 0u);
2705 m_impl->tsWraps.assign(m_impl->numAxes, 0u);
2706 m_impl->ppState.ppRefSpeedDegS.assign(m_impl->numAxes, 0.0);
2707 m_impl->ppState.ppRefAccelerationDegSS.assign(m_impl->numAxes, 0.0);
2708 m_impl->ppState.ppHaltRequested.assign(m_impl->numAxes, false);
2709
2710 for (size_t j = 0; j < m_impl->numAxes; ++j)
2711 {
2712 m_impl->sm[j] = std::make_unique<CiA402::StateMachine>();
2713 m_impl->sm[j]->reset();
2714 }
2715
2716 // get the axes names (if available)
2717 if (!extractListOfStringFromSearchable(cfg, "axes_names", {}, m_impl->variables.jointNames))
2718 return false;
2719
2720 constexpr double initialPositionVelocityDegs = 10;
2721 for (size_t j = 0; j < m_impl->numAxes; ++j)
2722 {
2723 // Cache for getRefSpeed()
2724 {
2725 std::lock_guard<std::mutex> lock(m_impl->ppState.mutex);
2726 m_impl->ppState.ppRefSpeedDegS[j] = initialPositionVelocityDegs;
2727 }
2728 m_impl->setSDORefSpeed(j, initialPositionVelocityDegs);
2729 }
2730
2731 yCInfo(CIA402, "%s opened %zu axes, initialization complete", logPrefix, m_impl->numAxes);
2732
2733 // ---------------------------------------------------------------------
2734 // Transition to OPERATIONAL and enable DC
2735 // ---------------------------------------------------------------------
2736 {
2737 const auto opErr = m_impl->ethercatManager.goOperational();
2739 {
2740 yCError(CIA402, "%s failed to enter OPERATIONAL state", logPrefix);
2741 return false;
2742 }
2743
2744 if (enableDc)
2745 {
2746 const auto dcErr
2747 = m_impl->ethercatManager.enableDCSync0(cycleNs, /*shift_ns=*/dcShiftNs);
2749 {
2750 yCError(CIA402, "%s failed to enable DC SYNC0", logPrefix);
2751 return false;
2752 }
2753 } else
2754 {
2755 yWarning("%s DC synchronization disabled by configuration", logPrefix);
2756 }
2757 }
2758
2759 // ---------------------------------------------------------------------
2760 // Startup safety check: verify joints are within limits
2761 // ---------------------------------------------------------------------
2762 {
2763 // Refresh PDO inputs once so feedback reflects the current position
2764 if (m_impl->ethercatManager.sendReceive() != ::CiA402::EthercatManager::Error::NoError)
2765 {
2766 yCError(CIA402, "%s initial send/receive in OPERATIONAL failed", logPrefix);
2767 return false;
2768 }
2769
2770 (void)m_impl->readFeedback();
2771
2772 bool outOfLimits = false;
2773 for (size_t j = 0; j < m_impl->numAxes; ++j)
2774 {
2775 const double posDeg = m_impl->variables.jointPositions[j];
2776 const double minDeg = m_impl->limits.minPositionLimitDeg[j];
2777 const double maxDeg = m_impl->limits.maxPositionLimitDeg[j];
2778
2779 const bool belowMin = (posDeg < minDeg);
2780 const bool aboveMax = (posDeg > maxDeg);
2781
2782 if (belowMin || aboveMax)
2783 {
2784 const char* axisLabel = nullptr;
2785 if (j < m_impl->variables.jointNames.size()
2786 && !m_impl->variables.jointNames[j].empty())
2787 {
2788 axisLabel = m_impl->variables.jointNames[j].c_str();
2789 }
2790
2791 yCError(CIA402,
2792 "%s joint %zu%s%s%s out of limits: pos=%.6f deg, min=%.6f, max=%.6f. "
2793 "Move the joint within limits before starting.",
2794 logPrefix,
2795 j,
2796 axisLabel ? " (" : "",
2797 axisLabel ? axisLabel : "",
2798 axisLabel ? ")" : "",
2799 posDeg,
2800 minDeg,
2801 maxDeg);
2802 outOfLimits = true;
2803 }
2804 }
2805
2806 if (outOfLimits)
2807 {
2808 // Disable power stage before aborting
2809 for (size_t j = 0; j < m_impl->numAxes; ++j)
2810 {
2811 const int slave = m_impl->firstSlave + static_cast<int>(j);
2812 auto* rx = m_impl->ethercatManager.getRxPDO(slave);
2813 if (rx)
2814 {
2815 rx->Controlword = 0x0000;
2816 rx->OpMode = 0;
2817 }
2818 }
2819
2820 (void)m_impl->ethercatManager.sendReceive();
2821 return false;
2822 }
2823 }
2824
2825 // ---------------------------------------------------------------------
2826 // Launch the device thread
2827 // ---------------------------------------------------------------------
2828 if (!this->start())
2829 {
2830 yCError(CIA402, "%s failed to start device thread", logPrefix);
2831 return false;
2832 }
2833
2834 yCInfo(CIA402,
2835 "%s device thread started (position strategy=%u: %s)",
2836 logPrefix,
2837 static_cast<unsigned>(desiredPositionStrategy),
2838 useSimplePidMode ? "simple PID" : "cascaded PID");
2839
2840 if (simplePidGainsAvailable)
2841 {
2842 yCInfo(CIA402, "%s simple PID gains:", logPrefix);
2843 for (size_t j = 0; j < m_impl->numAxes; ++j)
2844 {
2845 const char* axisLabel = nullptr;
2846 if (j < m_impl->variables.jointNames.size() && !m_impl->variables.jointNames[j].empty())
2847 {
2848 axisLabel = m_impl->variables.jointNames[j].c_str();
2849 }
2850
2851 const char* open = axisLabel ? " (" : "";
2852 const char* label = axisLabel ? axisLabel : "";
2853 const char* close = axisLabel ? ")" : "";
2854
2855 yCInfo(CIA402,
2856 "%s j=%zu%s%s%s Kp=%.6f Nm/deg, Kd=%.6f Nm\xC2\xB7s/deg",
2857 logPrefix,
2858 j,
2859 open,
2860 label,
2861 close,
2862 readKp[j],
2863 readKd[j]);
2864 }
2865 }
2866
2867 return true;
2868}
2869
2870// close() — stop the thread & release the NIC
2872{
2873 std::lock_guard<std::mutex> closeGuard(m_impl->CiA402MotionControlMutex);
2874 this->suspend();
2875 this->stop(); // PeriodicThread → graceful stop
2876 yCInfo(CIA402, "%s: EtheCAT master closed.", Impl::kClassName.data());
2877 return true;
2878}
2879
2880// run() — gets called every period (real-time control loop)
2881/**
2882 * Control loop phases:
2883 * 1) Apply user‑requested control modes (CiA‑402 power state machine)
2884 * 2) Push user setpoints to PDOs (units and shaft conversions handled)
2885 * 3) Cyclic exchange over EtherCAT (outputs sent / inputs read)
2886 * 4) Read back feedback (encoders, torque, safety, timestamp)
2887 * 5) Diagnostics and bookkeeping (active mode tracking, latching, inhibit)
2888 */
2890{
2891 constexpr auto logPrefix = "[run]";
2892 const auto tStart = std::chrono::steady_clock::now();
2893
2894 // lock the mutex
2895 std::lock_guard<std::mutex> runGuard(m_impl->CiA402MotionControlMutex);
2896
2897 /* ------------------------------------------------------------------
2898 * 1. APPLY USER-REQUESTED CONTROL MODES (CiA-402 power machine)
2899 * ----------------------------------------------------------------*/
2900 {
2901 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
2902
2903 for (size_t j = 0; j < m_impl->numAxes; ++j)
2904 {
2905 const int slaveIdx = m_impl->firstSlave + static_cast<int>(j);
2906 ::CiA402::RxPDO* rx = m_impl->ethercatManager.getRxPDO(slaveIdx);
2907 auto tx = m_impl->ethercatManager.getTxView(slaveIdx);
2908
2909 const int tgt = m_impl->controlModeState.target[j];
2910
2911 // If in FAULT the only way to escape from the fault is to do FORCE IDLE
2912 if (m_impl->controlModeState.active[j] == VOCAB_CM_HW_FAULT
2913 && tgt == VOCAB_CM_FORCE_IDLE)
2914 {
2915 const auto cmd = m_impl->sm[j]->faultReset(); // CW=0x0080
2916 rx->Controlword = cmd.controlword;
2917 rx->OpMode = 0; // neutral
2918 // Clear user setpoints/latches immediately
2919 m_impl->setPoints.reset((int)j);
2920 m_impl->velLatched[j] = m_impl->trqLatched[j] = m_impl->currLatched[j] = false;
2921 continue; // skip normal update-path this cycle
2922 }
2923
2924 /* ------------ normal control-mode path --------------------- */
2925 const int8_t opReq = Impl::yarpToCiaOp(tgt); // −1 = unsupported
2926 if (opReq < 0)
2927 { // ignore unknown modes
2928 continue;
2929 }
2930
2931 const bool hwInhibit = (tx.has(CiA402::TxField::STO_6621_01)
2932 && tx.get<uint8_t>(CiA402::TxField::STO_6621_01))
2934 && tx.get<uint8_t>(CiA402::TxField::SBC_6621_02));
2935 const uint16_t sw = tx.get<uint16_t>(CiA402::TxField::Statusword, 0);
2936 const int8_t od = tx.get<int8_t>(CiA402::TxField::OpModeDisplay, 0);
2937 CiA402::StateMachine::Command cmd = m_impl->sm[j]->update(sw, od, opReq, hwInhibit);
2938
2939 rx->Controlword = cmd.controlword;
2940 if (cmd.writeOpMode)
2941 {
2942 rx->OpMode = cmd.opMode;
2943 }
2944 }
2945 } /* mutex unlocked – PDOs are now ready to send */
2946
2947 /* ------------------------------------------------------------------
2948 * 2. SET USER-REQUESTED SETPOINTS (torque, position, velocity)
2949 * ----------------------------------------------------------------*/
2950 m_impl->setSetPoints();
2951
2952 /* ------------------------------------------------------------------
2953 * 3. CYCLIC EXCHANGE (send outputs / read inputs)
2954 * ----------------------------------------------------------------*/
2955 if (m_impl->ethercatManager.sendReceive() != ::CiA402::EthercatManager::Error::NoError)
2956 {
2957 yCError(CIA402,
2958 "%s sendReceive() failed, expected_wkc=%d got_wkc=%d",
2959 logPrefix,
2960 m_impl->ethercatManager.getExpectedWorkingCounter(),
2961 m_impl->ethercatManager.getWorkingCounter());
2962 m_impl->ethercatManager.dumpDiagnostics();
2963 }
2964
2965 /* ------------------------------------------------------------------
2966 * 4. COPY ENCODERS & OTHER FEEDBACK
2967 * ----------------------------------------------------------------*/
2968 m_impl->readFeedback();
2969
2970 /* ------------------------------------------------------------------
2971 * 5. DIAGNOSTICS (fill active[] according to feedback)
2972 * ----------------------------------------------------------------*/
2973 {
2974 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
2975
2976 for (size_t j = 0; j < m_impl->numAxes; ++j)
2977 {
2978 const int slaveIdx = m_impl->firstSlave + static_cast<int>(j);
2979 auto tx = m_impl->ethercatManager.getTxView(slaveIdx);
2980 bool flavourChanged = false;
2981
2982 const bool hwInhibit = (tx.has(CiA402::TxField::STO_6621_01)
2983 && tx.get<uint8_t>(CiA402::TxField::STO_6621_01))
2985 && tx.get<uint8_t>(CiA402::TxField::SBC_6621_02));
2986 const bool enabled = CiA402::StateMachine::isOperationEnabled(
2987 tx.get<uint16_t>(CiA402::TxField::Statusword, 0));
2988 const bool inFault
2991 tx.get<uint16_t>(CiA402::TxField::Statusword, 0));
2992
2993 int newActive = VOCAB_CM_IDLE;
2994 if (inFault)
2995 {
2996 newActive = VOCAB_CM_HW_FAULT;
2997 } else if (!hwInhibit && enabled)
2998 {
2999 const int activeOp = m_impl->sm[j]->getActiveOpMode();
3000 // If the drive is in CST (10), reflect the user-facing label (CURRENT or TORQUE)
3001 // that was last requested for this axis. Otherwise use the generic mapping.
3002 if (activeOp == 10)
3003 {
3004 // Guarded by the same mutex we already hold
3005 int flavor = m_impl->controlModeState.cstFlavor[j];
3006 // Safety net: constrain to CURRENT/TORQUE only
3007 if (flavor != VOCAB_CM_CURRENT && flavor != VOCAB_CM_TORQUE)
3008 {
3009 flavor = VOCAB_CM_TORQUE;
3010 }
3011 newActive = flavor;
3012
3013 // detect if the CST flavor changed since last time
3014 flavourChanged
3015 = (flavor != m_impl->controlModeState.prevCstFlavor[j])
3016 || (m_impl->controlModeState.prevCstFlavor[j] == VOCAB_CM_UNKNOWN);
3017 } else
3018 {
3019 newActive = Impl::ciaOpToYarp(activeOp);
3020 }
3021 }
3022
3023 // If IDLE or FAULT or inhibited → clear SPs and latches; force target to IDLE on HW
3024 // inhibit
3025 if (newActive == VOCAB_CM_IDLE || newActive == VOCAB_CM_HW_FAULT
3026 || newActive == VOCAB_CM_FORCE_IDLE)
3027 {
3028 m_impl->setPoints.reset(j);
3029 m_impl->velLatched[j] = m_impl->trqLatched[j] = m_impl->posLatched[j]
3030 = m_impl->currLatched[j] = false;
3031 if (hwInhibit)
3032 {
3033 m_impl->controlModeState.target[j] = VOCAB_CM_IDLE;
3034 }
3035 }
3036
3037 // Detect mode entry to (re)arm first-cycle latches
3038 if (m_impl->controlModeState.active[j] != newActive || flavourChanged)
3039 {
3040 // entering a control mode: arm latches and clear "has SP" flags
3041 m_impl->velLatched[j] = m_impl->trqLatched[j] = m_impl->posLatched[j]
3042 = m_impl->currLatched[j] = false;
3043 m_impl->setPoints.reset(j);
3044 }
3045
3046 m_impl->controlModeState.active[j] = newActive;
3047 m_impl->controlModeState.prevCstFlavor[j] = m_impl->controlModeState.cstFlavor[j];
3048 }
3049 }
3050
3051 // ---- profiling: compute per-call duration and log 30s average ----
3052 constexpr double printingIntervalSec = 30.0;
3053 const auto tEnd = std::chrono::steady_clock::now();
3054 const double dtSec
3056 m_impl->runTimeAccumSec += dtSec;
3057 m_impl->runTimeSamples += 1;
3058 const auto windowSec
3059 = std::chrono::duration_cast<std::chrono::duration<double>>(tEnd - m_impl->avgWindowStart)
3060 .count();
3061 if (windowSec >= printingIntervalSec)
3062 {
3063 const double avgMs
3064 = (m_impl->runTimeSamples > 0)
3065 ? (m_impl->runTimeAccumSec / static_cast<double>(m_impl->runTimeSamples)) * 1000.0
3066 : 0.0;
3067 yCInfoThrottle(CIA402,
3068 printingIntervalSec,
3069 "%s %.1fs window: avg run() time = %.3f ms (frequency=%.1f Hz) over %zu "
3070 "cycles (window=%.1fs) - Expected period=%.3f ms (%.1f Hz)",
3071 logPrefix,
3072 printingIntervalSec,
3073 avgMs,
3074 (m_impl->runTimeSamples > 0) ? (1000.0 / avgMs) : 0.0,
3075 m_impl->runTimeSamples,
3076 windowSec,
3077 this->getPeriod() * 1000.0,
3078 1.0 / this->getPeriod());
3079 m_impl->runTimeAccumSec = 0.0;
3080 m_impl->runTimeSamples = 0;
3081 m_impl->avgWindowStart = tEnd;
3082 }
3083}
3084
3085// -----------------------------------------------
3086// ----------------- IMotorEncoders --------------
3087// -----------------------------------------------
3088
3090{
3091 if (num == nullptr)
3092 {
3093 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3094 return false;
3095 }
3096 *num = static_cast<int>(m_impl->numAxes);
3097 return true;
3098}
3099
3101{
3102 yCError(CIA402, "%s: resetMotorEncoder() not implemented", Impl::kClassName.data());
3103 return false;
3104}
3105
3107{
3108 yCError(CIA402, "%s: resetMotorEncoders() not implemented", Impl::kClassName.data());
3109 return false;
3110}
3111
3113{
3114 yCError(CIA402,
3115 "%s: setMotorEncoderCountsPerRevolution() not implemented",
3116 Impl::kClassName.data());
3117 return false;
3118}
3119
3120bool CiA402MotionControl::setMotorEncoder(int m, const double v)
3121{
3122 yCError(CIA402, "%s: setMotorEncoder() not implemented", Impl::kClassName.data());
3123 return false;
3124}
3125
3127{
3128 yCError(CIA402, "%s: setMotorEncoders() not implemented", Impl::kClassName.data());
3129 return false;
3130}
3131
3133{
3134 if (cpr == nullptr)
3135 {
3136 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3137 return false;
3138 }
3139 if (m >= static_cast<int>(m_impl->numAxes))
3140 {
3141 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), m);
3142 return false;
3143 }
3144
3145 {
3146 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3147
3148 // check which encoder is mounted on the motor side
3149 if (m_impl->enc1Mount[m] == Impl::Mount::Motor)
3150 *cpr = static_cast<double>(m_impl->enc1Res[m]);
3151 else if (m_impl->enc2Mount[m] == Impl::Mount::Motor)
3152 *cpr = static_cast<double>(m_impl->enc2Res[m]);
3153 else
3154 return false; // no encoder on motor side
3155 }
3156 return true;
3157}
3158
3160{
3161 if (v == nullptr)
3162 {
3163 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3164 return false;
3165 }
3166 if (m >= static_cast<int>(m_impl->numAxes))
3167 {
3168 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), m);
3169 return false;
3170 }
3171 {
3172 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3173 *v = m_impl->variables.motorEncoders[m];
3174 }
3175 return true;
3176}
3177
3179{
3180 if (encs == nullptr)
3181 {
3182 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3183 return false;
3184 }
3185 {
3186 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3187 std::memcpy(encs, m_impl->variables.motorEncoders.data(), m_impl->numAxes * sizeof(double));
3188 }
3189
3190 return true;
3191}
3192
3193bool CiA402MotionControl::getMotorEncodersTimed(double* encs, double* time)
3194{
3195 if (encs == nullptr || time == nullptr)
3196 {
3197 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3198 return false;
3199 }
3200 {
3201 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3202 std::memcpy(encs, m_impl->variables.motorEncoders.data(), m_impl->numAxes * sizeof(double));
3203 std::memcpy(time, m_impl->variables.feedbackTime.data(), m_impl->numAxes * sizeof(double));
3204 }
3205 return true;
3206}
3207
3208bool CiA402MotionControl::getMotorEncoderTimed(int m, double* encs, double* time)
3209{
3210 if (encs == nullptr || time == nullptr)
3211 {
3212 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3213 return false;
3214 }
3215 if (m >= static_cast<int>(m_impl->numAxes))
3216 {
3217 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), m);
3218 return false;
3219 }
3220 {
3221 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3222 *encs = m_impl->variables.motorEncoders[m];
3223 *time = m_impl->variables.feedbackTime[m];
3224 }
3225 return true;
3226}
3227
3229{
3230 if (sp == nullptr)
3231 {
3232 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3233 return false;
3234 }
3235 if (m >= static_cast<int>(m_impl->numAxes))
3236 {
3237 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), m);
3238 return false;
3239 }
3240 {
3241 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3242 *sp = m_impl->variables.motorVelocities[m];
3243 }
3244 return true;
3245}
3246
3248{
3249 if (spds == nullptr)
3250 {
3251 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3252 return false;
3253 }
3254 {
3255 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3256 std::memcpy(spds,
3257 m_impl->variables.motorVelocities.data(),
3258 m_impl->numAxes * sizeof(double));
3259 }
3260 return true;
3261}
3262
3264{
3265 if (acc == nullptr)
3266 {
3267 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3268 return false;
3269 }
3270 if (m >= static_cast<int>(m_impl->numAxes))
3271 {
3272 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), m);
3273 return false;
3274 }
3275 {
3276 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3277 *acc = m_impl->variables.motorAccelerations[m];
3278 }
3279 return true;
3280}
3281
3283{
3284 if (accs == nullptr)
3285 {
3286 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3287 return false;
3288 }
3289 {
3290 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3291 std::memcpy(accs,
3292 m_impl->variables.motorAccelerations.data(),
3293 m_impl->numAxes * sizeof(double));
3294 }
3295 return true;
3296}
3297
3298// -----------------------------------------------
3299// ----------------- IEncoders ------------------
3300// -----------------------------------------------
3301bool CiA402MotionControl::getEncodersTimed(double* encs, double* time)
3302{
3303 if (encs == nullptr || time == nullptr)
3304 {
3305 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3306 return false;
3307 }
3308 {
3309 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3310 std::memcpy(encs,
3311 m_impl->variables.jointPositions.data(),
3312 m_impl->numAxes * sizeof(double));
3313 std::memcpy(time, m_impl->variables.feedbackTime.data(), m_impl->numAxes * sizeof(double));
3314 }
3315 return true;
3316}
3317
3318bool CiA402MotionControl::getEncoderTimed(int j, double* encs, double* time)
3319{
3320 if (encs == nullptr || time == nullptr)
3321 {
3322 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3323 return false;
3324 }
3325 if (j >= static_cast<int>(m_impl->numAxes))
3326 {
3327 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), j);
3328 return false;
3329 }
3330 {
3331 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3332 *encs = m_impl->variables.jointPositions[j];
3333 *time = m_impl->variables.feedbackTime[j];
3334 }
3335 return true;
3336}
3337
3339{
3340 if (ax == nullptr)
3341 {
3342 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3343 return false;
3344 }
3345 *ax = static_cast<int>(m_impl->numAxes);
3346 return true;
3347}
3348
3350{
3351 yCError(CIA402, "%s: resetEncoder() not implemented", Impl::kClassName.data());
3352 return false;
3353}
3354
3356{
3357 yCError(CIA402, "%s: resetEncoders() not implemented", Impl::kClassName.data());
3358 return false;
3359}
3360
3361bool CiA402MotionControl::setEncoder(int j, const double val)
3362{
3363 yCError(CIA402, "%s: setEncoder() not implemented", Impl::kClassName.data());
3364 return false;
3365}
3366
3367bool CiA402MotionControl::setEncoders(const double* vals)
3368{
3369 yCError(CIA402, "%s: setEncoders() not implemented", Impl::kClassName.data());
3370 return false;
3371}
3372
3374{
3375 if (v == nullptr)
3376 {
3377 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3378 return false;
3379 }
3380 if (j >= static_cast<int>(m_impl->numAxes))
3381 {
3382 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), j);
3383 return false;
3384 }
3385 {
3386 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3387 *v = m_impl->variables.jointPositions[j];
3388 }
3389 return true;
3390}
3391
3393{
3394 if (encs == nullptr)
3395 {
3396 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3397 return false;
3398 }
3399 {
3400 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3401 std::memcpy(encs,
3402 m_impl->variables.jointPositions.data(),
3403 m_impl->numAxes * sizeof(double));
3404 }
3405 return true;
3406}
3407
3409{
3410 if (sp == nullptr)
3411 {
3412 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3413 return false;
3414 }
3415 if (j >= static_cast<int>(m_impl->numAxes))
3416 {
3417 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), j);
3418 return false;
3419 }
3420 {
3421 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3422 *sp = m_impl->variables.jointVelocities[j];
3423 }
3424 return true;
3425}
3426
3428{
3429 if (spds == nullptr)
3430 {
3431 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3432 return false;
3433 }
3434 {
3435 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3436 std::memcpy(spds,
3437 m_impl->variables.jointVelocities.data(),
3438 m_impl->numAxes * sizeof(double));
3439 }
3440 return true;
3441}
3442
3444{
3445 if (spds == nullptr)
3446 {
3447 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3448 return false;
3449 }
3450 if (j >= static_cast<int>(m_impl->numAxes))
3451 {
3452 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), j);
3453 return false;
3454 }
3455 {
3456 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3457 *spds = m_impl->variables.jointAccelerations[j];
3458 }
3459 return true;
3460}
3461
3463{
3464 if (accs == nullptr)
3465 {
3466 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3467 return false;
3468 }
3469 {
3470 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3471 std::memcpy(accs,
3472 m_impl->variables.jointAccelerations.data(),
3473 m_impl->numAxes * sizeof(double));
3474 }
3475 return true;
3476}
3477
3478/// -----------------------------------------------
3479/// ----------------- IAxisInfo ------------------
3480/// -----------------------------------------------
3481
3483{
3484 if (j >= static_cast<int>(m_impl->numAxes))
3485 {
3486 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), j);
3487 return false;
3488 }
3489
3490 // We assume that the name is already filled in the open() method and does not change
3491 // during the lifetime of the object. For this reason we do not need to lock the mutex
3492 // here.
3493 name = m_impl->variables.jointNames[j];
3494 return true;
3495}
3496
3497bool CiA402MotionControl::getJointType(int axis, yarp::dev::JointTypeEnum& type)
3498{
3499 if (axis >= static_cast<int>(m_impl->numAxes))
3500 {
3501 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), axis);
3502 return false;
3503 }
3504 type = yarp::dev::JointTypeEnum::VOCAB_JOINTTYPE_REVOLUTE; // TODO: add support for linear
3505 // joints
3506 return true;
3507}
3508
3509// -------------------------- IControlMode ------------------------------------
3511{
3512 if (mode == nullptr)
3513 {
3514 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3515 return false;
3516 }
3517 if (j >= static_cast<int>(m_impl->numAxes))
3518 {
3519 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), j);
3520 return false;
3521 }
3522
3523 {
3524 std::lock_guard<std::mutex> lock(m_impl->controlModeState.mutex);
3525 *mode = m_impl->controlModeState.active[j];
3526 }
3527 return true;
3528}
3529
3531{
3532 if (modes == nullptr)
3533 {
3534 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3535 return false;
3536 }
3537
3538 {
3539 std::lock_guard<std::mutex> l(m_impl->controlModeState.mutex);
3540 std::memcpy(modes, m_impl->controlModeState.active.data(), m_impl->numAxes * sizeof(int));
3541 }
3542 return true;
3543}
3544
3545bool CiA402MotionControl::getControlModes(const int n, const int* joints, int* modes)
3546{
3547 if (modes == nullptr || joints == nullptr)
3548 {
3549 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3550 return false;
3551 }
3552 if (n <= 0)
3553 {
3554 yCError(CIA402, "%s: invalid number of joints %d", Impl::kClassName.data(), n);
3555 return false;
3556 }
3557
3558 {
3559 std::lock_guard<std::mutex> l(m_impl->controlModeState.mutex);
3560 for (int k = 0; k < n; ++k)
3561 {
3562 if (joints[k] >= static_cast<int>(m_impl->numAxes))
3563 {
3564 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), joints[k]);
3565 return false;
3566 }
3567 modes[k] = m_impl->controlModeState.active[joints[k]];
3568 }
3569 }
3570 return true;
3571}
3572
3573bool CiA402MotionControl::setControlMode(const int j, const int mode)
3574{
3575 if (j >= static_cast<int>(m_impl->numAxes))
3576 {
3577 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), j);
3578 return false;
3579 }
3580 if (Impl::yarpToCiaOp(mode) < 0)
3581 {
3582 yCError(CIA402, "%s: control mode %d not supported", Impl::kClassName.data(), mode);
3583 return false;
3584 }
3585
3586 std::lock_guard<std::mutex> l(m_impl->controlModeState.mutex);
3587 m_impl->controlModeState.target[j] = mode;
3588 if (mode == VOCAB_CM_CURRENT || mode == VOCAB_CM_TORQUE)
3589 {
3590 m_impl->controlModeState.cstFlavor[j] = mode;
3591 }
3592
3593 return true;
3594}
3595
3596bool CiA402MotionControl::setControlModes(const int n, const int* joints, int* modes)
3597{
3598 if (modes == nullptr || joints == nullptr)
3599 {
3600 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3601 return false;
3602 }
3603 if (n <= 0)
3604 {
3605 yCError(CIA402, "%s: invalid number of joints %d", Impl::kClassName.data(), n);
3606 return false;
3607 }
3608 std::lock_guard<std::mutex> l(m_impl->controlModeState.mutex);
3609 for (int k = 0; k < n; ++k)
3610 {
3611 if (joints[k] >= static_cast<int>(m_impl->numAxes))
3612 {
3613 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), joints[k]);
3614 return false;
3615 }
3616 m_impl->controlModeState.target[joints[k]] = modes[k];
3617
3618 if (modes[k] == VOCAB_CM_CURRENT || modes[k] == VOCAB_CM_TORQUE)
3619 {
3620 m_impl->controlModeState.cstFlavor[joints[k]] = modes[k];
3621 }
3622 }
3623 return true;
3624}
3625
3627{
3628 if (modes == nullptr)
3629 {
3630 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3631 return false;
3632 }
3633 std::lock_guard<std::mutex> l(m_impl->controlModeState.mutex);
3634 std::memcpy(m_impl->controlModeState.target.data(), modes, m_impl->numAxes * sizeof(int));
3635
3636 for (size_t j = 0; j < m_impl->numAxes; ++j)
3637 {
3638 if (m_impl->controlModeState.target[j] == VOCAB_CM_CURRENT
3639 || m_impl->controlModeState.target[j] == VOCAB_CM_TORQUE)
3640 {
3641 m_impl->controlModeState.cstFlavor[j] = m_impl->controlModeState.target[j];
3642 }
3643 }
3644
3645 return true;
3646}
3647
3648//// -------------------------- ITorqueControl ------------------------------------
3650{
3651 if (t == nullptr)
3652 {
3653 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3654 return false;
3655 }
3656 if (j >= static_cast<int>(m_impl->numAxes))
3657 {
3658 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), j);
3659 return false;
3660 }
3661 {
3662 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3663 *t = m_impl->variables.jointTorques[j];
3664 }
3665 return true;
3666}
3667
3669{
3670 if (t == nullptr)
3671 {
3672 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3673 return false;
3674 }
3675 {
3676 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
3677
3678 std::memcpy(t, m_impl->variables.jointTorques.data(), m_impl->numAxes * sizeof(double));
3679 }
3680 return true;
3681}
3682
3684{
3685 if (t == nullptr)
3686 {
3687 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3688 return false;
3689 }
3690 if (j >= static_cast<int>(m_impl->numAxes))
3691 {
3692 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), j);
3693 return false;
3694 }
3695 {
3696 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
3697 *t = m_impl->setPoints.jointTorques[j];
3698 }
3699 return true;
3700}
3701
3703{
3704 if (t == nullptr)
3705 {
3706 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3707 return false;
3708 }
3709 {
3710 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
3711 std::memcpy(t, m_impl->setPoints.jointTorques.data(), m_impl->numAxes * sizeof(double));
3712 }
3713 return true;
3714}
3715
3717{
3718 if (j >= static_cast<int>(m_impl->numAxes))
3719 {
3720 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), j);
3721 return false;
3722 }
3723
3724 // (a/b) Only accept if TORQUE is ACTIVE; otherwise reject (not considered)
3725 {
3726 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
3727 if (m_impl->controlModeState.active[j] != VOCAB_CM_TORQUE)
3728 {
3729 yCError(CIA402,
3730 "%s: setRefTorque rejected: TORQUE mode is not active for the joint %d",
3731 Impl::kClassName.data(),
3732 j);
3733 return false;
3734 }
3735 }
3736
3737 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
3738 m_impl->setPoints.jointTorques[j] = t;
3739 m_impl->setPoints.hasTorqueSP[j] = true; // (b)
3740 return true;
3741}
3742
3744{
3745 if (t == nullptr)
3746 {
3747 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3748 return false;
3749 }
3750 {
3751 // check that all the joints are in TORQUE mode use std function without for loop
3752 std::lock_guard<std::mutex> lock(m_impl->controlModeState.mutex);
3753 for (size_t j = 0; j < m_impl->numAxes; ++j)
3754 {
3755 if (m_impl->controlModeState.active[j] != VOCAB_CM_TORQUE)
3756 {
3757 yCError(CIA402,
3758 "%s: setRefTorques rejected: TORQUE mode is not active for the joint "
3759 "%zu",
3760 Impl::kClassName.data(),
3761 j);
3762 return false; // reject
3763 }
3764 }
3765 }
3766
3767 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
3768 std::memcpy(m_impl->setPoints.jointTorques.data(), t, m_impl->numAxes * sizeof(double));
3769 std::fill(m_impl->setPoints.hasTorqueSP.begin(), m_impl->setPoints.hasTorqueSP.end(), true);
3770 return true;
3771}
3772
3773bool CiA402MotionControl::setRefTorques(const int n_joint, const int* joints, const double* t)
3774{
3775 if (t == nullptr || joints == nullptr)
3776 {
3777 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3778 return false;
3779 }
3780 if (n_joint <= 0)
3781 {
3782 yCError(CIA402, "%s: invalid number of joints %d", Impl::kClassName.data(), n_joint);
3783 return false;
3784 }
3785
3786 // check that all the joints are in TORQUE mode
3787 {
3788 std::lock_guard<std::mutex> lock(m_impl->controlModeState.mutex);
3789 for (int k = 0; k < n_joint; ++k)
3790 {
3791 if (joints[k] >= static_cast<int>(m_impl->numAxes))
3792 {
3793 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), joints[k]);
3794 return false;
3795 }
3796 if (m_impl->controlModeState.active[joints[k]] != VOCAB_CM_TORQUE)
3797 {
3798 yCError(CIA402,
3799 "%s: setRefTorques rejected: TORQUE mode is not active for the joint %d",
3800 Impl::kClassName.data(),
3801 joints[k]);
3802 return false; // reject
3803 }
3804 }
3805 }
3806
3807 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
3808 for (int k = 0; k < n_joint; ++k)
3809 {
3810 m_impl->setPoints.jointTorques[joints[k]] = t[k];
3811 m_impl->setPoints.hasTorqueSP[joints[k]] = true;
3812 }
3813 return true;
3814}
3815
3816bool CiA402MotionControl::getTorqueRange(int j, double* min, double* max)
3817{
3818 if (min == nullptr || max == nullptr)
3819 {
3820 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3821 return false;
3822 }
3823 if (j >= static_cast<int>(m_impl->numAxes))
3824 {
3825 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), j);
3826 return false;
3827 }
3828
3829 // multiply by the transmission ratio to convert motor torque to joint torque
3830 *min = -m_impl->maxMotorTorqueNm[j] * m_impl->gearRatio[j];
3831 *max = m_impl->maxMotorTorqueNm[j] * m_impl->gearRatio[j];
3832
3833 return true;
3834}
3835
3836bool CiA402MotionControl::getTorqueRanges(double* min, double* max)
3837{
3838 if (min == nullptr || max == nullptr)
3839 {
3840 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3841 return false;
3842 }
3843
3844 for (size_t j = 0; j < m_impl->numAxes; ++j)
3845 {
3846 min[j] = -m_impl->maxMotorTorqueNm[j] * m_impl->gearRatio[j];
3847 max[j] = m_impl->maxMotorTorqueNm[j] * m_impl->gearRatio[j];
3848 }
3849 return true;
3850}
3851
3853{
3854 if (j >= static_cast<int>(m_impl->numAxes))
3855 {
3856 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), j);
3857 return false;
3858 }
3859
3860 // (a/b) Only accept if VELOCITY is ACTIVE; otherwise reject
3861 {
3862 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
3863 if (m_impl->controlModeState.active[j] != VOCAB_CM_VELOCITY)
3864 {
3865 yCError(CIA402,
3866 "%s: velocityMove rejected: VELOCITY mode is not active for the joint %d",
3867 Impl::kClassName.data(),
3868 j);
3869
3870 // this will return true to indicate the rejection was handled
3871 return true;
3872 }
3873 }
3874
3875 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
3876 m_impl->setPoints.jointVelocities[j] = spd;
3877 m_impl->setPoints.hasVelSP[j] = true; // (b)
3878 return true;
3879}
3880
3882{
3883 if (spds == nullptr)
3884 {
3885 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3886 return false;
3887 }
3888
3889 // check that all the joints are in VELOCITY mode
3890 {
3891 std::lock_guard<std::mutex> lock(m_impl->controlModeState.mutex);
3892 for (size_t j = 0; j < m_impl->numAxes; ++j)
3893 {
3894 if (m_impl->controlModeState.active[j] != VOCAB_CM_VELOCITY)
3895 {
3896 yCError(CIA402,
3897 "%s: velocityMove rejected: VELOCITY mode is not active for the joint "
3898 "%zu",
3899 Impl::kClassName.data(),
3900 j);
3901 return false; // reject
3902 }
3903 }
3904 }
3905
3906 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
3907 std::memcpy(m_impl->setPoints.jointVelocities.data(), spds, m_impl->numAxes * sizeof(double));
3908 std::fill(m_impl->setPoints.hasVelSP.begin(), m_impl->setPoints.hasVelSP.end(), true);
3909 return true;
3910}
3911
3912bool CiA402MotionControl::getRefVelocity(const int joint, double* vel)
3913{
3914 if (vel == nullptr)
3915 {
3916 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3917 return false;
3918 }
3919 if (joint >= static_cast<int>(m_impl->numAxes))
3920 {
3921 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), joint);
3922 return false;
3923 }
3924 {
3925 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
3926 *vel = m_impl->setPoints.jointVelocities[joint];
3927 }
3928 return true;
3929}
3930
3932{
3933 if (spds == nullptr)
3934 {
3935 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3936 return false;
3937 }
3938 {
3939 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
3940 std::memcpy(spds,
3941 m_impl->setPoints.jointVelocities.data(),
3942 m_impl->numAxes * sizeof(double));
3943 }
3944 return true;
3945}
3946
3947bool CiA402MotionControl::getRefVelocities(const int n_joint, const int* joints, double* vels)
3948{
3949 if (vels == nullptr || joints == nullptr)
3950 {
3951 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
3952 return false;
3953 }
3954 if (n_joint <= 0)
3955 {
3956 yCError(CIA402, "%s: invalid number of joints %d", Impl::kClassName.data(), n_joint);
3957 return false;
3958 }
3959
3960 {
3961 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
3962 for (int k = 0; k < n_joint; ++k)
3963 {
3964 if (joints[k] >= static_cast<int>(m_impl->numAxes))
3965 {
3966 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), joints[k]);
3967 return false;
3968 }
3969 vels[k] = m_impl->setPoints.jointVelocities[joints[k]];
3970 }
3971 }
3972 return true;
3973}
3974
3975// Acceleration is expressed in YARP joint units [deg/s^2].
3976// For PP we SDO-write 0x6083/0x6084/0x6085 in rpm/s (deg/s^2 ÷ 6).
3977// For CSV we just cache the value (no standard accel SDO in CSV).
3978
3980{
3981 if (j < 0 || j >= static_cast<int>(m_impl->numAxes))
3982 {
3983 yCError(CIA402, "%s: setRefAcceleration: joint %d out of range", Impl::kClassName.data(), j);
3984 return false;
3985 }
3986
3987 // store magnitude
3988 if (accDegS2 < 0.0)
3989 {
3990 accDegS2 = -accDegS2;
3991 }
3992
3993 // saturate to maximum allowed 10 deg/s^2
3994 constexpr double maxAcc = 10.0;
3995 if (accDegS2 > maxAcc)
3996 {
3997 yCWarning(CIA402,
3998 "%s: setRefAcceleration: joint %d: acceleration %.2f deg/s^2 too high, "
3999 "saturating to %.2f deg/s^2",
4000 Impl::kClassName.data(),
4001 j,
4002 accDegS2,
4003 maxAcc);
4004 accDegS2 = maxAcc;
4005 }
4006
4007 // Only touch SDOs if PP is ACTIVE
4008 int controlMode = -1;
4009 {
4010 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
4011 controlMode = m_impl->controlModeState.active[j];
4012 }
4013
4014 if (controlMode != VOCAB_CM_POSITION)
4015 {
4016 // do nothing if not in PP
4017 return true;
4018 }
4019
4020 const int s = m_impl->firstSlave + j;
4021 const int32_t acc = static_cast<int32_t>(std::llround(accDegS2 * m_impl->degSToVel[j]));
4022 {
4023 std::lock_guard<std::mutex> lock(m_impl->ppState.mutex);
4024 m_impl->ppState.ppRefAccelerationDegSS[j] = accDegS2;
4025 }
4026
4027 // Profile acceleration / deceleration / quick-stop deceleration
4028 (void)m_impl->ethercatManager.writeSDO<int32_t>(s, 0x6083, 0x00, acc);
4029 (void)m_impl->ethercatManager.writeSDO<int32_t>(s, 0x6084, 0x00, acc);
4030 (void)m_impl->ethercatManager.writeSDO<int32_t>(s, 0x6085, 0x00, acc);
4031
4032 return true;
4033}
4034
4035bool CiA402MotionControl::setRefAccelerations(const double* accsDegS2)
4036{
4037 if (!accsDegS2)
4038 {
4039 yCError(CIA402, "%s: setRefAccelerations: null pointer", Impl::kClassName.data());
4040 return false;
4041 }
4042 bool ok = true;
4043 for (size_t j = 0; j < m_impl->numAxes; ++j)
4044 {
4045 ok = setRefAcceleration(static_cast<int>(j), accsDegS2[j]) && ok;
4046 }
4047 return ok;
4048}
4049
4051{
4052 if (acc == nullptr)
4053 {
4054 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
4055 return false;
4056 }
4057 if (j >= static_cast<int>(m_impl->numAxes))
4058 {
4059 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), j);
4060 return false;
4061 }
4062
4063 int controlMode = -1;
4064 {
4065 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
4066 controlMode = m_impl->controlModeState.active[j];
4067 }
4068
4069 if (controlMode == VOCAB_CM_POSITION)
4070 {
4071 // if in PP return the cached value
4072 std::lock_guard<std::mutex> lock(m_impl->ppState.mutex);
4073 *acc = m_impl->ppState.ppRefAccelerationDegSS[j];
4074 return true;
4075 }
4076
4077 *acc = 0.0;
4078 return true;
4079}
4080
4082{
4083 if (accs == nullptr)
4084 {
4085 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
4086 return false;
4087 }
4088
4089 for (size_t j = 0; j < m_impl->numAxes; ++j)
4090 {
4091 int controlMode = -1;
4092 {
4093 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
4094 controlMode = m_impl->controlModeState.active[j];
4095 }
4096
4097 if (controlMode == VOCAB_CM_POSITION)
4098 {
4099 // if in PP return the cached value
4100 std::lock_guard<std::mutex> lock(m_impl->ppState.mutex);
4101 accs[j] = m_impl->ppState.ppRefAccelerationDegSS[j];
4102 } else
4103 {
4104 accs[j] = 0.0;
4105 }
4106 }
4107 return true;
4108}
4109
4110// stop() semantics:
4111// • PP → set CW bit 8 (HALT), decelerating with 0x6084.
4112// • CSV/others → zero TargetVelocity (current behavior kept).
4113
4115{
4116 if (j < 0 || j >= static_cast<int>(m_impl->numAxes))
4117 {
4118 yCError(CIA402, "%s: stop: joint %d out of range", Impl::kClassName.data(), j);
4119 return false;
4120 }
4121
4122 int controlMode = -1;
4123 {
4124 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
4125 controlMode = m_impl->controlModeState.active[j];
4126 }
4127
4128 if (controlMode == VOCAB_CM_POSITION)
4129 {
4130 std::lock_guard<std::mutex> lock(m_impl->ppState.mutex);
4131 m_impl->ppState.ppHaltRequested[j] = true; // consumed in setSetPoints()
4132 return true;
4133 }
4134
4135 // CSV/others → zero velocity set-point
4136 {
4137 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4138 m_impl->setPoints.jointVelocities[j] = 0.0;
4139 m_impl->setPoints.hasVelSP[j] = true;
4140 }
4141 return true;
4142}
4143
4145{
4146 // PP axes → HALT; non-PP axes → velocity 0
4147 {
4148 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
4149 for (size_t j = 0; j < m_impl->numAxes; ++j)
4150 {
4151 if (m_impl->controlModeState.active[j] == VOCAB_CM_POSITION)
4152 {
4153 std::lock_guard<std::mutex> lock(m_impl->ppState.mutex);
4154 m_impl->ppState.ppHaltRequested[j] = true;
4155 }
4156 }
4157 }
4158 {
4159 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4160 std::fill(m_impl->setPoints.jointVelocities.begin(),
4161 m_impl->setPoints.jointVelocities.end(),
4162 0.0);
4163 std::fill(m_impl->setPoints.hasVelSP.begin(), m_impl->setPoints.hasVelSP.end(), true);
4164 }
4165 return true;
4166}
4167
4168bool CiA402MotionControl::velocityMove(const int n_joint, const int* joints, const double* spds)
4169{
4170 if (spds == nullptr || joints == nullptr)
4171 {
4172 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
4173 return false;
4174 }
4175 if (n_joint <= 0)
4176 {
4177 yCError(CIA402, "%s: invalid number of joints %d", Impl::kClassName.data(), n_joint);
4178 return false;
4179 }
4180
4181 // check that all the joints are in VELOCITY mode
4182 {
4183 std::lock_guard<std::mutex> lock(m_impl->controlModeState.mutex);
4184 for (int k = 0; k < n_joint; ++k)
4185 {
4186 if (joints[k] >= static_cast<int>(m_impl->numAxes))
4187 {
4188 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), joints[k]);
4189 return false;
4190 }
4191 if (m_impl->controlModeState.active[joints[k]] != VOCAB_CM_VELOCITY)
4192 {
4193 yCError(CIA402,
4194 "%s: velocityMove rejected: VELOCITY mode is not active for the joint "
4195 "%d",
4196 Impl::kClassName.data(),
4197 joints[k]);
4198 return false; // reject
4199 }
4200 }
4201 }
4202
4203 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4204 for (int k = 0; k < n_joint; ++k)
4205 {
4206 m_impl->setPoints.jointVelocities[joints[k]] = spds[k];
4207 m_impl->setPoints.hasVelSP[joints[k]] = true;
4208 }
4209
4210 return true;
4211}
4212
4214 const int* joints,
4215 const double* accs)
4216{
4217 if (accs == nullptr || joints == nullptr)
4218 {
4219 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
4220 return false;
4221 }
4222 if (n_joint <= 0)
4223 {
4224 yCError(CIA402, "%s: invalid number of joints %d", Impl::kClassName.data(), n_joint);
4225 return false;
4226 }
4227
4228 // no operation
4229 return true;
4230}
4231
4232bool CiA402MotionControl::getRefAccelerations(const int n_joint, const int* joints, double* accs)
4233{
4234 if (accs == nullptr || joints == nullptr)
4235 {
4236 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
4237 return false;
4238 }
4239 std::memset(accs, 0, n_joint * sizeof(double)); // CiA-402 does not support acceleration
4240 // setpoints, so we return 0.0 for all axes
4241 return true;
4242}
4243
4244bool CiA402MotionControl::stop(const int n_joint, const int* joints)
4245{
4246 if (joints == nullptr)
4247 {
4248 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
4249 return false;
4250 }
4251 if (n_joint <= 0)
4252 {
4253 yCError(CIA402, "%s: invalid number of joints %d", Impl::kClassName.data(), n_joint);
4254 return false;
4255 }
4256
4257 {
4258 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4259 for (int k = 0; k < n_joint; ++k)
4260 {
4261 if (joints[k] >= static_cast<int>(m_impl->numAxes))
4262 {
4263 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), joints[k]);
4264 return false;
4265 }
4266 m_impl->setPoints.jointVelocities[joints[k]] = 0.0;
4267 m_impl->setPoints.hasVelSP[joints[k]] = true;
4268 }
4269 }
4270 return true;
4271}
4272
4274{
4275 if (j < 0 || j >= static_cast<int>(m_impl->numAxes))
4276 {
4277 yCError(CIA402, "%s: getLastJointFault: joint %d out of range", Impl::kClassName.data(), j);
4278 return false;
4279 }
4280
4281 const int slave = m_impl->firstSlave + j;
4282
4283 // --- 0x603F:00 Error code (UINT16) ---
4284 uint16_t code = 0;
4285 auto err = m_impl->ethercatManager.readSDO<uint16_t>(slave, 0x603F, 0x00, code);
4287 {
4288 yCError(CIA402,
4289 "%s: getLastJointFault: SDO read 0x603F:00 failed (joint %d)",
4290 Impl::kClassName.data(),
4291 j);
4292 return false;
4293 }
4294
4295 fault = static_cast<int>(code);
4296 message = m_impl->describe603F(code);
4297
4298 // --- 0x203F:01 Error report (STRING(8)) ---
4299 // Use a fixed char[8] so we can call the templated readSDO<T> unmodified.
4300 char report[8] = {0}; // zero-init so partial reads are safely NUL-terminated
4301 auto err2 = m_impl->ethercatManager.readSDO(slave, 0x203F, 0x01, report);
4303 {
4304 // Trim at first NUL (STRING(8) is not guaranteed to be fully used)
4305 std::size_t len = 0;
4306 while (len < sizeof(report) && report[len] != '\0')
4307 ++len;
4308
4309 if (len > 0)
4310 {
4311 // If it's clean printable ASCII, append as text; otherwise show hex bytes.
4312 bool printable = true;
4313 for (std::size_t i = 0; i < len; ++i)
4314 {
4315 const unsigned char c = static_cast<unsigned char>(report[i]);
4316 if (c < 0x20 || c > 0x7E)
4317 {
4318 printable = false;
4319 break;
4320 }
4321 }
4322
4323 if (printable)
4324 {
4325 message += " — report: ";
4326 message.append(report, len);
4327 } else
4328 {
4329 char hex[3 * 8 + 1] = {0};
4330 int pos = 0;
4331 for (std::size_t i = 0; i < len && pos <= static_cast<int>(sizeof(hex)) - 3; ++i)
4332 pos += std::snprintf(hex + pos,
4333 sizeof(hex) - pos,
4334 "%02X%s",
4335 static_cast<unsigned char>(report[i]),
4336 (i + 1 < len) ? " " : "");
4337 message += " — report: [";
4338 message += hex;
4339 message += "]";
4340 }
4341 }
4342 }
4343 return true;
4344}
4345
4346bool CiA402MotionControl::positionMove(int j, double refDeg)
4347{
4348 if (j < 0 || j >= static_cast<int>(m_impl->numAxes))
4349 {
4350 yCError(CIA402, "%s: positionMove: joint %d out of range", Impl::kClassName.data(), j);
4351 return false;
4352 }
4353 // accept only if PP is ACTIVE (same policy as your CSV path)
4354 int controlMode = -1;
4355 {
4356 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
4357 controlMode = m_impl->controlModeState.active[j];
4358 }
4359
4360 if (controlMode != VOCAB_CM_POSITION)
4361 {
4362 yCError(CIA402,
4363 "%s: positionMove rejected: POSITION mode not active for joint %d",
4364 Impl::kClassName.data(),
4365 j);
4366 return false;
4367 }
4368
4369 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4370 m_impl->setPoints.ppJointTargetsDeg[j] = refDeg;
4371 m_impl->setPoints.ppTargetCounts[j] = m_impl->jointDegToTargetCounts(size_t(j), refDeg);
4372 m_impl->setPoints.ppIsRelative[j] = false;
4373 m_impl->setPoints.ppHasPosSP[j] = true;
4374 m_impl->setPoints.ppPulseHi[j] = true; // schedule rising edge on CW bit4
4375 return true;
4376}
4377
4378bool CiA402MotionControl::positionMove(const double* refsDeg)
4379{
4380 if (!refsDeg)
4381 {
4382 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
4383 return false;
4384 }
4385
4386 // all axes must be in PP
4387 {
4388 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
4389 for (size_t j = 0; j < m_impl->numAxes; ++j)
4390 if (m_impl->controlModeState.active[j] != VOCAB_CM_POSITION)
4391 {
4392 yCError(CIA402,
4393 "%s: positionMove rejected: POSITION mode not active on joint %zu",
4394 Impl::kClassName.data(),
4395 j);
4396 return false;
4397 }
4398 }
4399
4400 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4401 for (size_t j = 0; j < m_impl->numAxes; ++j)
4402 {
4403 m_impl->setPoints.ppJointTargetsDeg[j] = refsDeg[j];
4404 m_impl->setPoints.ppTargetCounts[j] = m_impl->jointDegToTargetCounts(j, refsDeg[j]);
4405 m_impl->setPoints.ppIsRelative[j] = false;
4406 m_impl->setPoints.ppHasPosSP[j] = true;
4407 m_impl->setPoints.ppPulseHi[j] = true;
4408 }
4409 return true;
4410}
4411
4412bool CiA402MotionControl::positionMove(const int n, const int* joints, const double* refsDeg)
4413{
4414 if (!joints || !refsDeg || n <= 0)
4415 {
4416 yCError(CIA402, "%s: invalid args", Impl::kClassName.data());
4417 return false;
4418 }
4419 {
4420 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
4421 for (int k = 0; k < n; ++k)
4422 {
4423 if (joints[k] < 0 || joints[k] >= static_cast<int>(m_impl->numAxes))
4424 return false;
4425 if (m_impl->controlModeState.active[joints[k]] != VOCAB_CM_POSITION)
4426 {
4427 yCError(CIA402,
4428 "%s: positionMove rejected: POSITION mode not active on joint %d",
4429 Impl::kClassName.data(),
4430 joints[k]);
4431 return false;
4432 }
4433 }
4434 }
4435 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4436 for (int k = 0; k < n; ++k)
4437 {
4438 const int j = joints[k];
4439 m_impl->setPoints.ppJointTargetsDeg[j] = refsDeg[k];
4440 m_impl->setPoints.ppTargetCounts[j] = m_impl->jointDegToTargetCounts(size_t(j), refsDeg[k]);
4441 m_impl->setPoints.ppIsRelative[j] = false;
4442 m_impl->setPoints.ppHasPosSP[j] = true;
4443 m_impl->setPoints.ppPulseHi[j] = true;
4444 }
4445 return true;
4446}
4447
4448bool CiA402MotionControl::relativeMove(int j, double deltaDeg)
4449{
4450 if (j < 0 || j >= static_cast<int>(m_impl->numAxes))
4451 return false;
4452 {
4453 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
4454 if (m_impl->controlModeState.active[j] != VOCAB_CM_POSITION)
4455 {
4456 yCError(CIA402,
4457 "%s: relativeMove rejected: POSITION mode not active for joint %d",
4458 Impl::kClassName.data(),
4459 j);
4460 return true;
4461 }
4462 }
4463 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4464 m_impl->setPoints.ppJointTargetsDeg[j] += deltaDeg; // cache last target in deg
4465 m_impl->setPoints.ppTargetCounts[j] = m_impl->jointDegToTargetCounts(size_t(j), deltaDeg);
4466 m_impl->setPoints.ppIsRelative[j] = true;
4467 m_impl->setPoints.ppHasPosSP[j] = true;
4468 m_impl->setPoints.ppPulseHi[j] = true;
4469 return true;
4470}
4471
4472bool CiA402MotionControl::relativeMove(const double* deltasDeg)
4473{
4474 if (!deltasDeg)
4475 return false;
4476 {
4477 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
4478 for (size_t j = 0; j < m_impl->numAxes; ++j)
4479 if (m_impl->controlModeState.active[j] != VOCAB_CM_POSITION)
4480 return false;
4481 }
4482 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4483 for (size_t j = 0; j < m_impl->numAxes; ++j)
4484 {
4485 m_impl->setPoints.ppJointTargetsDeg[j] += deltasDeg[j];
4486 m_impl->setPoints.ppTargetCounts[j] = m_impl->jointDegToTargetCounts(j, deltasDeg[j]);
4487 m_impl->setPoints.ppIsRelative[j] = true;
4488 m_impl->setPoints.ppHasPosSP[j] = true;
4489 m_impl->setPoints.ppPulseHi[j] = true;
4490 }
4491 return true;
4492}
4493
4494bool CiA402MotionControl::relativeMove(const int n, const int* joints, const double* deltasDeg)
4495{
4496 if (!joints || !deltasDeg || n <= 0)
4497 return false;
4498 {
4499 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
4500 for (int k = 0; k < n; ++k)
4501 if (m_impl->controlModeState.active[joints[k]] != VOCAB_CM_POSITION)
4502 return false;
4503 }
4504 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4505 for (int k = 0; k < n; ++k)
4506 {
4507 const int j = joints[k];
4508 m_impl->setPoints.ppJointTargetsDeg[j] += deltasDeg[k];
4509 m_impl->setPoints.ppTargetCounts[j]
4510 = m_impl->jointDegToTargetCounts(size_t(j), deltasDeg[k]);
4511 m_impl->setPoints.ppIsRelative[j] = true;
4512 m_impl->setPoints.ppHasPosSP[j] = true;
4513 m_impl->setPoints.ppPulseHi[j] = true;
4514 }
4515 return true;
4516}
4517
4519{
4520 if (flag == nullptr)
4521 {
4522 yCError(CIA402, "%s: checkMotionDone: null pointer", Impl::kClassName.data());
4523 return false;
4524 }
4525
4526 if (j < 0 || j >= static_cast<int>(m_impl->numAxes))
4527 {
4528 yCError(CIA402, "%s: checkMotionDone: joint %d out of range", Impl::kClassName.data(), j);
4529 return false;
4530 }
4531
4532 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
4533 *flag = m_impl->variables.targetReached[j];
4534 return true;
4535}
4536
4538{
4539 if (flag == nullptr)
4540 {
4541 yCError(CIA402, "%s: checkMotionDone: null pointer", Impl::kClassName.data());
4542 return false;
4543 }
4544
4545 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
4546 for (size_t j = 0; j < m_impl->numAxes; ++j)
4547 {
4548 flag[j] = m_impl->variables.targetReached[j];
4549 }
4550
4551 return true;
4552}
4553
4554bool CiA402MotionControl::checkMotionDone(const int n, const int* joints, bool* flag)
4555{
4556 if (!joints || !flag || n <= 0)
4557 return false;
4558 bool all = true;
4559 for (int k = 0; k < n; ++k)
4560 {
4561 bool f = true;
4562 checkMotionDone(joints[k], &f);
4563 all = all && f;
4564 }
4565 *flag = all;
4566 return true;
4567}
4568
4569bool CiA402MotionControl::setRefSpeed(int j, double spDegS)
4570{
4571 if (j < 0 || j >= static_cast<int>(m_impl->numAxes))
4572 {
4573 yCError(CIA402, "%s: setRefSpeed: joint %d out of range", Impl::kClassName.data(), j);
4574 return false;
4575 }
4576
4577 // Only write SDO if PP is active (current behavior)
4578 int cm = -1;
4579 {
4580 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
4581 cm = m_impl->controlModeState.active[j];
4582 }
4583 if (cm != VOCAB_CM_POSITION)
4584 {
4585 yCError(CIA402,
4586 "%s: setRefSpeed: POSITION mode not active for joint %d, not writing SDO",
4587 Impl::kClassName.data(),
4588 j);
4589 return true;
4590 }
4591
4592 // Cache for getRefSpeed()
4593 {
4594 std::lock_guard<std::mutex> lock(m_impl->ppState.mutex);
4595 m_impl->ppState.ppRefSpeedDegS[j] = spDegS;
4596 }
4597
4598 m_impl->setSDORefSpeed(j, spDegS);
4599
4600 return true;
4601}
4602
4603bool CiA402MotionControl::setRefSpeeds(const double* spDegS)
4604{
4605 if (spDegS == nullptr)
4606 {
4607 yCError(CIA402, "%s: setRefSpeeds: null pointer", Impl::kClassName.data());
4608 return false;
4609 }
4610 for (size_t j = 0; j < m_impl->numAxes; ++j)
4611 {
4612 this->setRefSpeed(static_cast<int>(j), spDegS[j]);
4613 }
4614 return true;
4615}
4616
4617bool CiA402MotionControl::setRefSpeeds(const int n, const int* joints, const double* spDegS)
4618{
4619 if (!joints || !spDegS || n <= 0)
4620 {
4621 yCError(CIA402, "%s: setRefSpeeds: invalid args", Impl::kClassName.data());
4622 return false;
4623 }
4624
4625 for (int k = 0; k < n; ++k)
4626 {
4627 this->setRefSpeed(joints[k], spDegS[k]);
4628 }
4629 return true;
4630}
4631
4632bool CiA402MotionControl::getRefSpeed(int j, double* ref)
4633{
4634 if (!ref || j < 0 || j >= static_cast<int>(m_impl->numAxes))
4635 {
4636 yCError(CIA402, "%s: getRefSpeed: invalid args", Impl::kClassName.data());
4637 return false;
4638 }
4639
4640 std::lock_guard<std::mutex> lock(m_impl->ppState.mutex);
4641 *ref = m_impl->ppState.ppRefSpeedDegS[j];
4642 return true;
4643}
4645{
4646 if (!spds)
4647 {
4648 yCError(CIA402, "%s: getRefSpeeds: null pointer", Impl::kClassName.data());
4649 return false;
4650 }
4651 std::lock_guard<std::mutex> lock(m_impl->ppState.mutex);
4652 std::memcpy(spds, m_impl->ppState.ppRefSpeedDegS.data(), m_impl->numAxes * sizeof(double));
4653 return true;
4654}
4655
4656bool CiA402MotionControl::getRefSpeeds(const int n, const int* joints, double* spds)
4657{
4658 if (!joints || !spds || n <= 0)
4659 {
4660 yCError(CIA402, "%s: getRefSpeeds: invalid args", Impl::kClassName.data());
4661 return false;
4662 }
4663 std::lock_guard<std::mutex> lock(m_impl->ppState.mutex);
4664 for (int k = 0; k < n; ++k)
4665 {
4666 spds[k] = m_impl->ppState.ppRefSpeedDegS[joints[k]];
4667 }
4668 return true;
4669}
4670
4671bool CiA402MotionControl::getTargetPosition(const int j, double* ref)
4672{
4673 if (!ref || j < 0 || j >= static_cast<int>(m_impl->numAxes))
4674 {
4675 yCError(CIA402, "%s: getTargetPosition: invalid args", Impl::kClassName.data());
4676 return false;
4677 }
4678
4679 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4680 *ref = m_impl->setPoints.ppJointTargetsDeg[j];
4681 return true;
4682}
4683
4685{
4686 if (refs == nullptr)
4687 {
4688 yCError(CIA402, "%s: getTargetPositions: null pointer", Impl::kClassName.data());
4689 return false;
4690 }
4691
4692 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4693 std::memcpy(refs, m_impl->setPoints.ppJointTargetsDeg.data(), m_impl->numAxes * sizeof(double));
4694 return true;
4695}
4696
4697bool CiA402MotionControl::getTargetPositions(const int n, const int* joints, double* refs)
4698{
4699 if (!joints || !refs || n <= 0)
4700 {
4701 yCError(CIA402, "%s: getTargetPositions: invalid args", Impl::kClassName.data());
4702 return false;
4703 }
4704 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4705 for (int k = 0; k < n; ++k)
4706 {
4707 refs[k] = m_impl->setPoints.ppJointTargetsDeg[joints[k]];
4708 }
4709 return true;
4710}
4711
4712// ---------------- IPositionDirect --------------
4713
4714bool CiA402MotionControl::setPosition(int j, double refDeg)
4715{
4716 if (j < 0 || j >= static_cast<int>(m_impl->numAxes))
4717 {
4718 yCError(CIA402, "%s: setPosition: joint %d out of range", Impl::kClassName.data(), j);
4719 return false;
4720 }
4721
4722 {
4723 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
4724 if (m_impl->controlModeState.active[j] != VOCAB_CM_POSITION_DIRECT)
4725 {
4726 yCError(CIA402,
4727 "%s: setPosition rejected: POSITION_DIRECT mode is not active for joint %d",
4728 Impl::kClassName.data(),
4729 j);
4730 return false;
4731 }
4732 }
4733
4734 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4735 m_impl->setPoints.positionDirectJointTargetsDeg[j] = refDeg;
4736 m_impl->setPoints.positionDirectTargetCounts[j]
4737 = m_impl->jointDegToTargetCounts(static_cast<size_t>(j), refDeg);
4738 return true;
4739}
4740
4742{
4743 if (refs == nullptr)
4744 {
4745 yCError(CIA402, "%s: setPositions: null pointer", Impl::kClassName.data());
4746 return false;
4747 }
4748
4749 {
4750 std::lock_guard<std::mutex> lock(m_impl->controlModeState.mutex);
4751 for (size_t j = 0; j < m_impl->numAxes; ++j)
4752 {
4753 if (m_impl->controlModeState.active[j] != VOCAB_CM_POSITION_DIRECT)
4754 {
4755 yCError(CIA402,
4756 "%s: setPositions rejected: POSITION_DIRECT mode is not active for joint "
4757 "%zu",
4758 Impl::kClassName.data(),
4759 j);
4760 return false;
4761 }
4762 }
4763 }
4764
4765 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4766 for (size_t j = 0; j < m_impl->numAxes; ++j)
4767 {
4768 m_impl->setPoints.positionDirectJointTargetsDeg[j] = refs[j];
4769 m_impl->setPoints.positionDirectTargetCounts[j]
4770 = m_impl->jointDegToTargetCounts(j, refs[j]);
4771 }
4772 return true;
4773}
4774
4775bool CiA402MotionControl::setPositions(const int n_joint, const int* joints, const double* refs)
4776{
4777 if (!joints || !refs)
4778 {
4779 yCError(CIA402, "%s: setPositions: null pointer", Impl::kClassName.data());
4780 return false;
4781 }
4782 if (n_joint <= 0)
4783 {
4784 yCError(CIA402,
4785 "%s: setPositions: invalid number of joints %d",
4786 Impl::kClassName.data(),
4787 n_joint);
4788 return false;
4789 }
4790
4791 {
4792 std::lock_guard<std::mutex> lock(m_impl->controlModeState.mutex);
4793 for (int k = 0; k < n_joint; ++k)
4794 {
4795 if (joints[k] < 0 || joints[k] >= static_cast<int>(m_impl->numAxes))
4796 {
4797 yCError(CIA402,
4798 "%s: setPositions: joint %d out of range",
4799 Impl::kClassName.data(),
4800 joints[k]);
4801 return false;
4802 }
4803 if (m_impl->controlModeState.active[joints[k]] != VOCAB_CM_POSITION_DIRECT)
4804 {
4805 yCError(CIA402,
4806 "%s: setPositions rejected: POSITION_DIRECT mode is not active for joint "
4807 "%d",
4808 Impl::kClassName.data(),
4809 joints[k]);
4810 return false;
4811 }
4812 }
4813 }
4814
4815 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4816 for (int k = 0; k < n_joint; ++k)
4817 {
4818 const int j = joints[k];
4819 m_impl->setPoints.positionDirectJointTargetsDeg[j] = refs[k];
4820 m_impl->setPoints.positionDirectTargetCounts[j]
4821 = m_impl->jointDegToTargetCounts(static_cast<size_t>(j), refs[k]);
4822 }
4823 return true;
4824}
4825
4826bool CiA402MotionControl::getRefPosition(const int joint, double* ref)
4827{
4828 if (!ref)
4829 {
4830 yCError(CIA402, "%s: getRefPosition: null pointer", Impl::kClassName.data());
4831 return false;
4832 }
4833 if (joint < 0 || joint >= static_cast<int>(m_impl->numAxes))
4834 {
4835 yCError(CIA402, "%s: getRefPosition: joint %d out of range", Impl::kClassName.data(), joint);
4836 return false;
4837 }
4838
4839 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4840 *ref = m_impl->setPoints.positionDirectJointTargetsDeg[joint];
4841 return true;
4842}
4843
4845{
4846 if (!refs)
4847 {
4848 yCError(CIA402, "%s: getRefPositions: null pointer", Impl::kClassName.data());
4849 return false;
4850 }
4851
4852 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4853 std::memcpy(refs,
4854 m_impl->setPoints.positionDirectJointTargetsDeg.data(),
4855 m_impl->numAxes * sizeof(double));
4856 return true;
4857}
4858
4859bool CiA402MotionControl::getRefPositions(const int n_joint, const int* joints, double* refs)
4860{
4861 if (!joints || !refs)
4862 {
4863 yCError(CIA402, "%s: getRefPositions: null pointer", Impl::kClassName.data());
4864 return false;
4865 }
4866 if (n_joint <= 0)
4867 {
4868 yCError(CIA402,
4869 "%s: getRefPositions: invalid number of joints %d",
4870 Impl::kClassName.data(),
4871 n_joint);
4872 return false;
4873 }
4874
4875 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
4876 for (int k = 0; k < n_joint; ++k)
4877 {
4878 if (joints[k] < 0 || joints[k] >= static_cast<int>(m_impl->numAxes))
4879 {
4880 yCError(CIA402,
4881 "%s: getRefPositions: joint %d out of range",
4882 Impl::kClassName.data(),
4883 joints[k]);
4884 return false;
4885 }
4886 refs[k] = m_impl->setPoints.positionDirectJointTargetsDeg[joints[k]];
4887 }
4888 return true;
4889}
4890
4892{
4893 if (!num)
4894 {
4895 yCError(CIA402, "%s: getNumberOfMotors: null pointer", Impl::kClassName.data());
4896 return false;
4897 }
4898 *num = m_impl->numAxes;
4899 return true;
4900}
4901
4903{
4904 if (val == nullptr)
4905 {
4906 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
4907 return false;
4908 }
4909 if (m < 0 || m >= static_cast<int>(m_impl->numAxes))
4910 {
4911 yCError(CIA402, "%s: motor %d out of range", Impl::kClassName.data(), m);
4912 return false;
4913 }
4914 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
4915 *val = m_impl->variables.driveTemperatures[m];
4916 return true;
4917}
4918
4920{
4921 if (vals == nullptr)
4922 {
4923 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
4924 return false;
4925 }
4926 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
4927 std::memcpy(vals, m_impl->variables.driveTemperatures.data(), m_impl->numAxes * sizeof(double));
4928 return true;
4929}
4930
4932{
4933 // The get temperature limit function is not implemented
4934 yCError(CIA402,
4935 "%s: The getTemperatureLimit function is not implemented",
4936 Impl::kClassName.data());
4937 return false;
4938}
4939
4940bool CiA402MotionControl::setTemperatureLimit(int m, const double temp)
4941{
4942 // The set temperature limit function is not implemented
4943 yCError(CIA402,
4944 "%s: The setTemperatureLimit function is not implemented",
4945 Impl::kClassName.data());
4946 return false;
4947}
4948
4950{
4951 if (val == nullptr)
4952 {
4953 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
4954 return false;
4955 }
4956 if (m < 0 || m >= static_cast<int>(m_impl->numAxes))
4957 {
4958 yCError(CIA402, "%s: motor %d out of range", Impl::kClassName.data(), m);
4959 return false;
4960 }
4961 *val = m_impl->gearRatio[m];
4962 return true;
4963}
4964
4965bool CiA402MotionControl::setGearboxRatio(int m, const double val)
4966{
4967 // The setGearboxRatio function is not implemented
4968 yCError(CIA402, "%s: The setGearboxRatio function is not implemented", Impl::kClassName.data());
4969 return false;
4970}
4971
4972bool CiA402MotionControl::getCurrent(int m, double* curr)
4973{
4974 if (curr == nullptr)
4975 {
4976 yCError(CIA402, "%s: getCurrent: null pointer", Impl::kClassName.data());
4977 return false;
4978 }
4979 if (m < 0 || m >= static_cast<int>(m_impl->numAxes))
4980 {
4981 yCError(CIA402, "%s: getCurrent: motor %d out of range", Impl::kClassName.data(), m);
4982 return false;
4983 }
4984 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
4985 *curr = m_impl->variables.motorCurrents[m];
4986 return true;
4987};
4988
4990{
4991 if (currs == nullptr)
4992 {
4993 yCError(CIA402, "%s: getCurrents: null pointer", Impl::kClassName.data());
4994 return false;
4995 }
4996 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
4997 std::memcpy(currs, m_impl->variables.motorCurrents.data(), m_impl->numAxes * sizeof(double));
4998 return true;
4999}
5000
5001bool CiA402MotionControl::getCurrentRange(int m, double* min, double* max)
5002{
5003 if (min == nullptr || max == nullptr)
5004 {
5005 yCError(CIA402, "%s: getCurrentRange: null pointer", Impl::kClassName.data());
5006 return false;
5007 }
5008 if (m < 0 || m >= static_cast<int>(m_impl->numAxes))
5009 {
5010 yCError(CIA402, "%s: getCurrentRange: motor %d out of range", Impl::kClassName.data(), m);
5011 return false;
5012 }
5013 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
5014 *min = -m_impl->maxCurrentsA[m];
5015 *max = m_impl->maxCurrentsA[m];
5016 return true;
5017}
5018
5019bool CiA402MotionControl::getCurrentRanges(double* min, double* max)
5020{
5021 if (min == nullptr || max == nullptr)
5022 {
5023 yCError(CIA402, "%s: getCurrentRanges: null pointer", Impl::kClassName.data());
5024 return false;
5025 }
5026 std::lock_guard<std::mutex> lock(m_impl->variables.mutex);
5027 for (size_t m = 0; m < m_impl->numAxes; ++m)
5028 {
5029 min[m] = -m_impl->maxCurrentsA[m];
5030 max[m] = m_impl->maxCurrentsA[m];
5031 }
5032 return true;
5033}
5034
5036{
5037 if (currs == nullptr)
5038 {
5039 yCError(CIA402, "%s: setRefCurrents: null pointer", Impl::kClassName.data());
5040 return false;
5041 }
5042
5043 {
5044 // check that all the joints are in CURRENT mode
5045 std::lock_guard<std::mutex> lock(m_impl->controlModeState.mutex);
5046 for (size_t j = 0; j < m_impl->numAxes; ++j)
5047 {
5048 if (m_impl->controlModeState.active[j] != VOCAB_CM_CURRENT)
5049 {
5050 yCError(CIA402,
5051 "%s: setRefCurrents rejected: CURRENT mode is not active for the joint "
5052 "%zu",
5053 Impl::kClassName.data(),
5054 j);
5055 return false; // reject
5056 }
5057 }
5058 }
5059
5060 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
5061 std::memcpy(m_impl->setPoints.motorCurrents.data(), currs, m_impl->numAxes * sizeof(double));
5062 std::fill(m_impl->setPoints.hasCurrentSP.begin(), m_impl->setPoints.hasCurrentSP.end(), true);
5063 return true;
5064}
5065
5067{
5068 if (m < 0 || m >= static_cast<int>(m_impl->numAxes))
5069 {
5070 yCError(CIA402, "%s: setRefCurrent: motor %d out of range", Impl::kClassName.data(), m);
5071 return false;
5072 }
5073
5074 // (a/b) Only accept if CURRENT is ACTIVE; otherwise reject (not considered)
5075 {
5076 std::lock_guard<std::mutex> g(m_impl->controlModeState.mutex);
5077 if (m_impl->controlModeState.active[m] != VOCAB_CM_CURRENT)
5078 {
5079 yCError(CIA402,
5080 "%s: setRefCurrent rejected: CURRENT mode is not active for the joint %d",
5081 Impl::kClassName.data(),
5082 m);
5083 return false;
5084 }
5085 }
5086
5087 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
5088 m_impl->setPoints.motorCurrents[m] = curr;
5089 m_impl->setPoints.hasCurrentSP[m] = true; // (b)
5090
5091 return true;
5092}
5093
5094bool CiA402MotionControl::setRefCurrents(const int n_motor, const int* motors, const double* currs)
5095{
5096 if (currs == nullptr || motors == nullptr)
5097 {
5098 yCError(CIA402, "%s: setRefCurrents: null pointer", Impl::kClassName.data());
5099 return false;
5100 }
5101 if (n_motor <= 0)
5102 {
5103 yCError(CIA402,
5104 "%s: setRefCurrents: invalid number of motors %d",
5105 Impl::kClassName.data(),
5106 n_motor);
5107 return false;
5108 }
5109 for (int k = 0; k < n_motor; ++k)
5110 {
5111 if (motors[k] < 0 || motors[k] >= static_cast<int>(m_impl->numAxes))
5112 {
5113 yCError(CIA402,
5114 "%s: setRefCurrents: motor %d out of range",
5115 Impl::kClassName.data(),
5116 motors[k]);
5117 return false;
5118 }
5119 }
5120
5121 // check that all the joints are in CURRENT mode
5122 {
5123 std::lock_guard<std::mutex> lock(m_impl->controlModeState.mutex);
5124 for (int k = 0; k < n_motor; ++k)
5125 {
5126 if (m_impl->controlModeState.active[motors[k]] != VOCAB_CM_CURRENT)
5127 {
5128 yCError(CIA402,
5129 "%s: setRefCurrents rejected: CURRENT mode is not active for the joint %d",
5130 Impl::kClassName.data(),
5131 motors[k]);
5132 return false; // reject
5133 }
5134 }
5135 }
5136
5137 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
5138 for (int k = 0; k < n_motor; ++k)
5139 {
5140 m_impl->setPoints.motorCurrents[motors[k]] = currs[k];
5141 m_impl->setPoints.hasCurrentSP[motors[k]] = true;
5142 }
5143 return true;
5144}
5145
5147{
5148 if (currs == nullptr)
5149 {
5150 yCError(CIA402, "%s: getRefCurrents: null pointer", Impl::kClassName.data());
5151 return false;
5152 }
5153
5154 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
5155 std::memcpy(currs, m_impl->setPoints.motorCurrents.data(), m_impl->numAxes * sizeof(double));
5156 return true;
5157}
5158
5159bool CiA402MotionControl::getRefCurrent(int m, double* curr)
5160{
5161 if (curr == nullptr)
5162 {
5163 yCError(CIA402, "%s: getRefCurrent: null pointer", Impl::kClassName.data());
5164 return false;
5165 }
5166 if (m < 0 || m >= static_cast<int>(m_impl->numAxes))
5167 {
5168 yCError(CIA402, "%s: getRefCurrent: motor %d out of range", Impl::kClassName.data(), m);
5169 return false;
5170 }
5171
5172 std::lock_guard<std::mutex> lock(m_impl->setPoints.mutex);
5173 *curr = m_impl->setPoints.motorCurrents[m];
5174 return true;
5175}
5176
5177bool CiA402MotionControl::setLimits(int axis, double min, double max)
5178{
5179 if (axis < 0 || axis >= static_cast<int>(m_impl->numAxes))
5180 {
5181 yCError(CIA402, "%s: setLimits: axis %d out of range", Impl::kClassName.data(), axis);
5182 return false;
5183 }
5184 // If both bounds are provided (non-negative), enforce min < max.
5185 // When either bound is negative, we treat that side as disabled like in open(),
5186 // and skip the ordering check.
5187 if (!(min < 0.0 || max < 0.0) && (min >= max))
5188 {
5189 yCError(CIA402,
5190 "%s: setLimits: invalid limits [min=%g, max=%g]",
5191 Impl::kClassName.data(),
5192 min,
5193 max);
5194 return false;
5195 }
5196
5197 {
5198 std::lock_guard<std::mutex> lock(m_impl->limits.mutex);
5199 m_impl->limits.maxPositionLimitDeg[axis] = max;
5200 m_impl->limits.minPositionLimitDeg[axis] = min;
5201 }
5202
5203 // set the software limits in the drive (SDO 0x607D)
5204 // convert the limits from deg to counts, honoring inversion and disabled bounds
5205 const bool inv = m_impl->invertedMotionSenseDirection[axis];
5206 const bool lowerLimitDisabled = (min < 0.0);
5207 const bool upperLimitDisabled = (max < 0.0);
5208
5209 const auto lowerLimitCounts
5210 = lowerLimitDisabled ? 0 : m_impl->jointDegToTargetCounts(size_t(axis), min);
5211 const auto upperLimitCounts
5212 = upperLimitDisabled ? 0 : m_impl->jointDegToTargetCounts(size_t(axis), max);
5213
5214 int32_t minCounts = 0;
5215 int32_t maxCounts = 0;
5216
5217 if (!inv)
5218 {
5219 minCounts = lowerLimitDisabled ? std::numeric_limits<int32_t>::min() : lowerLimitCounts;
5220 maxCounts = upperLimitDisabled ? std::numeric_limits<int32_t>::max() : upperLimitCounts;
5221 } else
5222 {
5223 // Inverted: f(x) = -counts(x), so [min,max] -> [f(max), f(min)]
5224 minCounts = upperLimitDisabled ? std::numeric_limits<int32_t>::min() : -upperLimitCounts;
5225 maxCounts = lowerLimitDisabled ? std::numeric_limits<int32_t>::max() : -lowerLimitCounts;
5226 }
5227
5228 return m_impl->setPositionCountsLimits(axis, minCounts, maxCounts);
5229}
5230
5231bool CiA402MotionControl::getLimits(int axis, double* min, double* max)
5232{
5233 if (min == nullptr || max == nullptr)
5234 {
5235 yCError(CIA402, "%s: getLimits: null pointer", Impl::kClassName.data());
5236 return false;
5237 }
5238 if (axis < 0 || axis >= static_cast<int>(m_impl->numAxes))
5239 {
5240 yCError(CIA402, "%s: getLimits: axis %d out of range", Impl::kClassName.data(), axis);
5241 return false;
5242 }
5243
5244 std::lock_guard<std::mutex> lock(m_impl->limits.mutex);
5245 *min = m_impl->limits.minPositionLimitDeg[axis];
5246 *max = m_impl->limits.maxPositionLimitDeg[axis];
5247 return true;
5248}
5249
5250bool CiA402MotionControl::setVelLimits(int axis, double min, double max)
5251{
5252 // not implemented yet
5253 constexpr auto logPrefix = "[setVelLimits] ";
5254 yCError(CIA402, "%s: The setVelLimits function is not implemented", logPrefix);
5255 return false;
5256}
5257
5258bool CiA402MotionControl::getVelLimits(int axis, double* min, double* max)
5259{
5260 // not implemented yet
5261 constexpr auto logPrefix = "[getVelLimits] ";
5262 yCError(CIA402, "%s: The getVelLimits function is not implemented", logPrefix);
5263 return false;
5264}
5265
5266bool CiA402MotionControl::getInteractionMode(int axis, yarp::dev::InteractionModeEnum* mode)
5267{
5268 if (!mode)
5269 {
5270 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
5271 return false;
5272 }
5273
5274 *mode = m_impl->dummyInteractionMode;
5275 return true;
5276}
5277
5279 int* joints,
5280 yarp::dev::InteractionModeEnum* modes)
5281{
5282 if (!joints || !modes || n_joints <= 0)
5283 {
5284 yCError(CIA402, "%s: invalid args", Impl::kClassName.data());
5285 return false;
5286 }
5287
5288 for (int k = 0; k < n_joints; ++k)
5289 {
5290 if (joints[k] < 0 || joints[k] >= static_cast<int>(m_impl->numAxes))
5291 {
5292 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), joints[k]);
5293 return false;
5294 }
5295 modes[k] = m_impl->dummyInteractionMode;
5296 }
5297 return true;
5298}
5299
5300bool CiA402MotionControl::getInteractionModes(yarp::dev::InteractionModeEnum* modes)
5301{
5302 if (modes == nullptr)
5303 {
5304 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
5305 return false;
5306 }
5307
5308 for (size_t j = 0; j < m_impl->numAxes; ++j)
5309 {
5310 modes[j] = m_impl->dummyInteractionMode;
5311 }
5312 return true;
5313}
5314
5315bool CiA402MotionControl::setInteractionMode(int axis, yarp::dev::InteractionModeEnum mode)
5316{
5317 if (axis < 0 || axis >= static_cast<int>(m_impl->numAxes))
5318 {
5319 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), axis);
5320 return false;
5321 }
5322
5323 // The interaction mode is not implemented in this driver.
5324 yCError(CIA402,
5325 "%s: The setInteractionMode function is not implemented",
5326 Impl::kClassName.data());
5327 return false;
5328}
5329
5331 int* joints,
5332 yarp::dev::InteractionModeEnum* modes)
5333{
5334 if (!joints || !modes || n_joints <= 0)
5335 {
5336 yCError(CIA402, "%s: invalid args", Impl::kClassName.data());
5337 return false;
5338 }
5339
5340 for (int k = 0; k < n_joints; ++k)
5341 {
5342 if (joints[k] < 0 || joints[k] >= static_cast<int>(m_impl->numAxes))
5343 {
5344 yCError(CIA402, "%s: joint %d out of range", Impl::kClassName.data(), joints[k]);
5345 return false;
5346 }
5347 }
5348
5349 // The interaction mode is not implemented in this driver.
5350 yCError(CIA402,
5351 "%s: The setInteractionModes function is not implemented",
5352 Impl::kClassName.data());
5353 return false;
5354}
5355
5356bool CiA402MotionControl::setInteractionModes(yarp::dev::InteractionModeEnum* modes)
5357{
5358 if (modes == nullptr)
5359 {
5360 yCError(CIA402, "%s: null pointer", Impl::kClassName.data());
5361 return false;
5362 }
5363
5364 yCError(CIA402,
5365 "%s: The setInteractionModes function is not implemented",
5366 Impl::kClassName.data());
5367 return false;
5368}
5369
5370} // namespace yarp::dev
T append(T... args)
T assign(T... args)
T begin(T... args)
T c_str(T... args)
Minimal EtherCAT master built on SOEM for CiA-402 devices.
TxView getTxView(int slaveIndex) const noexcept
Obtain a typed, bounds-checked view over the TxPDO (slave→master).
const RxPDO * getRxPDO(int slaveIndex) const noexcept
Access the RxPDO (master→slave) buffer for a given slave.
Error readSDO(int slaveIndex, uint16_t idx, uint8_t subIdx, T &out) noexcept
Read an SDO value from a slave (blocking call).
@ NoError
Operation completed successfully.
Error writeSDO(int slaveIndex, uint16_t idx, uint8_t subIdx, const T &value) noexcept
Write an SDO value to a slave (blocking call).
static bool isOperationEnabled(uint16_t sw)
static bool isFault(uint16_t sw)
static bool isFaultReactionActive(uint16_t sw)
T get(TxField f, T fallback={}) const
Read a field from the TxPDO image with a typed accessor.
bool setGearboxRatio(int m, const double val) override
Sets the gearbox ratio of a specific motor.
bool setRefAcceleration(int j, double acc) override
(Unused in CSV mode) Sets the reference acceleration for a specific joint.
bool getTargetPosition(int j, double *ref) override
Gets the target position for a specific joint.
bool getCurrentRange(int m, double *min, double *max) override
Gets the allowable current range for a specific motor.
bool resetMotorEncoders() override
Resets all motor encoders to zero.
bool setRefCurrent(int m, double curr) override
Sets the reference current for a specific motor.
bool setEncoder(int j, double val) override
Sets the value of a specific encoder.
bool getVelLimits(int axis, double *min, double *max) override
Gets the velocity limits for a specific axis.
void run() override
Runs the periodic thread.
bool setMotorEncoder(int m, const double val) override
Sets the value of a specific motor encoder.
bool getRefVelocity(const int joint, double *vel) override
Gets the reference velocity for a specific joint.
bool setMotorEncoders(const double *vals) override
Sets the values of all motor encoders.
bool getNumberOfMotors(int *num) override
Gets the number of motors controlled by the device.
bool getEncoderAcceleration(int j, double *spds) override
Gets the acceleration of a specific encoder.
bool getEncoderSpeed(int j, double *sp) override
Gets the speed of a specific encoder.
bool getEncoders(double *encs) override
Gets the values of all encoders.
bool getEncoderSpeeds(double *spds) override
Gets the speeds of all encoders.
bool setVelLimits(int axis, double min, double max) override
Sets the velocity limits for a specific axis.
bool positionMove(int j, double ref) override
Commands an absolute position move for a specific joint using Profile Position Mode (PP).
bool getMotorEncoder(int m, double *v) override
Gets the value of a specific motor encoder.
bool getEncoderTimed(int j, double *encs, double *time) override
Gets the value and timestamp of a specific encoder.
bool getAxisName(int axis, std::string &name) override
Gets the name of a specific axis.
bool setPosition(int j, double ref) override
Streams a single joint reference in Cyclic Synchronous Position mode.
bool relativeMove(int j, double delta) override
Commands a relative position move for a specific joint.
bool getLastJointFault(int j, int &fault, std::string &message) override
Gets the last joint fault for a specific joint.
bool getJointType(int axis, yarp::dev::JointTypeEnum &type) override
Gets the type of a specific axis.
bool getRefPosition(const int joint, double *ref) override
Returns the most recent position-direct command for a joint.
bool getMotorEncoderCountsPerRevolution(int m, double *cpr) override
Gets the counts per revolution for a specific motor encoder.
~CiA402MotionControl() override
Destructor.
bool resetEncoders() override
Resets all encoders to zero.
bool getTargetPositions(double *refs) override
Gets the target positions for all joints.
bool setRefCurrents(const double *currs) override
Sets the reference currents for all motors.
bool getTorques(double *t) override
Gets the measured torques for all joints.
bool getRefCurrent(int m, double *curr) override
Gets the last commanded reference current for a specific motor.
bool getRefCurrents(double *currs) override
Gets the last commanded reference currents for all motors.
bool stop() override
Stops motion for all joints.
bool setRefTorques(const double *t) override
Sets the reference torques for all joints.
bool getControlMode(int j, int *mode) override
Gets the control mode of a specific joint.
bool getEncoderAccelerations(double *accs) override
Gets the accelerations of all encoders.
bool getRefSpeed(int j, double *ref) override
Gets the current reference speed (profile velocity) for a specific joint.
bool setLimits(int axis, double min, double max) override
Sets the position limits for a specific axis.
bool setInteractionModes(int n_joints, int *joints, yarp::dev::InteractionModeEnum *modes) override
Sets the interaction modes of a subset of joints.
bool setTemperatureLimit(int m, const double temp) override
Sets the temperature limit of a specific motor.
bool getTorque(int j, double *t) override
Gets the measured torque for a specific joint.
bool getRefPositions(double *refs) override
Returns the position-direct references for all joints.
bool getLimits(int axis, double *min, double *max) override
Gets the position limits for a specific axis.
bool velocityMove(int j, double sp) override
Commands a velocity move for a specific joint.
bool setMotorEncoderCountsPerRevolution(int m, const double cpr) override
Sets the counts per revolution for a specific motor encoder.
bool getRefVelocities(double *vels) override
Gets the reference velocities for all joints.
bool getEncodersTimed(double *encs, double *time) override
Gets the values and timestamps of all encoders.
bool getTorqueRanges(double *min, double *max) override
Gets the torque ranges for all joints.
bool getControlModes(int *modes) override
Gets the control modes of all joints.
bool resetEncoder(int j) override
Resets the specified encoder to zero.
bool setControlModes(const int n, const int *joints, int *modes) override
Sets the control modes of a subset of joints.
bool getMotorEncoderSpeed(int m, double *sp) override
Gets the speed of a specific motor encoder.
bool getMotorEncoders(double *encs) override
Gets the values of all motor encoders.
bool setPositions(const int n_joint, const int *joints, const double *refs) override
Streams references for a subset of joints.
bool setRefSpeed(int j, double sp) override
Sets the reference speed (profile velocity) for a specific joint.
bool getMotorEncoderAcceleration(int m, double *acc) override
Gets the acceleration of a specific motor encoder.
bool getEncoder(int j, double *v) override
Gets the value of a specific encoder.
bool getMotorEncoderTimed(int m, double *encs, double *time) override
Gets the value and timestamp of a specific motor encoder.
bool getCurrentRanges(double *min, double *max) override
Gets the allowable current ranges for all motors.
bool setControlMode(const int j, const int mode) override
Sets the control mode of a specific joint.
bool getTemperatureLimit(int m, double *temp) override
Gets the temperature limit of a specific motor.
bool getInteractionMode(int axis, yarp::dev::InteractionModeEnum *mode) override
Gets the interaction mode of a specific axis.
bool getRefAcceleration(int j, double *acc) override
(Unused in CSV mode) Gets the reference acceleration for a specific joint.
bool getCurrents(double *currs) override
Gets the measured currents of all motors.
bool checkMotionDone(int j, bool *flag) override
Checks if a specific joint has completed its motion.
bool stop(int j) override
Stops motion for a specific joint.
bool getGearboxRatio(int m, double *val) override
Gets the gearbox ratio of a specific motor.
bool open(yarp::os::Searchable &config) override
Opens the device driver.
bool getTemperature(int m, double *val) override
Gets the temperature of a specific motor.
bool setRefSpeeds(const double *spds) override
Sets the reference speeds (profile velocities) for all joints.
bool getInteractionModes(int n_joints, int *joints, yarp::dev::InteractionModeEnum *modes) override
Gets the interaction modes of a subset of joints.
bool setRefAccelerations(const double *accs) override
(Unused in CSV mode) Sets the reference accelerations for all joints.
bool getMotorEncodersTimed(double *encs, double *time) override
Gets the values and timestamps of all motor encoders.
bool getMotorEncoderAccelerations(double *accs) override
Gets the accelerations of all motor encoders.
bool getRefTorque(int j, double *t) override
Gets the reference torque for a specific joint.
bool setEncoders(const double *vals) override
Sets the values of all encoders.
bool close() override
Closes the device driver.
bool getNumberOfMotorEncoders(int *num) override
Gets the number of motor encoders.
bool getCurrent(int m, double *curr) override
Gets the measured current of a specific motor.
bool getAxes(int *ax) override
Gets the number of axes (encoders).
bool setRefTorque(int j, double t) override
Sets the reference torque for a specific joint.
bool getTemperatures(double *vals) override
Gets the temperatures of all motors.
bool getMotorEncoderSpeeds(double *spds) override
Gets the speeds of all motor encoders.
bool resetMotorEncoder(int m) override
Resets the specified motor encoder to zero.
bool getRefTorques(double *t) override
Gets the reference torques for all joints.
bool setInteractionMode(int axis, yarp::dev::InteractionModeEnum mode) override
Sets the interaction mode of a specific axis.
bool getTorqueRange(int j, double *min, double *max) override
Gets the torque range for a specific joint.
bool getRefAccelerations(double *accs) override
(Unused in CSV mode) Gets the reference accelerations for all joints.
bool getRefSpeeds(double *spds) override
Gets the current reference speeds (profile velocities) for all joints.
T duration_cast(T... args)
T fill(T... args)
T find(T... args)
T snprintf(T... args)
T isinf(T... args)
T max(T... args)
T memcpy(T... args)
T memset(T... args)
T min(T... args)
@ Velocity606C
0x606C: Velocity actual value
@ Enc2Pos2113_02
0x2113:02 Vendor enc2 position
@ SBC_6621_02
0x6621:02 Safe Brake Control status (exposed via PDO)
@ Enc2Vel2113_03
0x2113:03 Vendor enc2 velocity
@ OpModeDisplay
0x6061: Modes of operation display
@ Timestamp20F0
0x20F0: Timestamp (if supported)
@ Statusword
0x6041: Statusword
@ TemperatureDrive
0x2031:01 Temperature (if supported)
@ Position6064
0x6064: Position actual value
@ Torque6077
0x6077: Torque actual value
@ Enc1Pos2111_02
0x2111:02 Vendor enc1 position
@ Enc1Vel2111_03
0x2111:03 Vendor enc1 velocity
@ STO_6621_01
0x6621:01 Safe Torque Off status (exposed via PDO)
STL namespace.
T push_back(T... args)
T resize(T... args)
T round(T... args)
T size(T... args)
Process Data Object written from master to slave (RxPDO).
int8_t OpMode
0x6060: Modes of operation
uint16_t Controlword
0x6040: Controlword
static constexpr std::string_view kClassName
bool setPositionControlStrategy(uint16_t strategyValue)
static std::string_view yarpToString(int op)
yarp::dev::InteractionModeEnum dummyInteractionMode
bool setPositionWindowDeg(int j, double winDeg, double winTime_ms)
static constexpr uint64_t TIMESTAMP_WRAP_PERIOD_US
static std::tuple< double, double, const char * > decode60A9(uint32_t v)
static constexpr uint32_t TIMESTAMP_WRAP_HALF_RANGE
int32_t jointDegToTargetCounts(size_t j, double jointDeg) const
std::chrono::steady_clock::time_point avgWindowStart
double loopCountsToJointDeg(std::size_t j, double counts) const
std::vector< std::unique_ptr< CiA402::StateMachine > > sm
bool readSimplePidGains(std::vector< double > &kpNmPerDeg, std::vector< double > &kdNmSecPerDeg)
struct yarp::dev::CiA402MotionControl::Impl::Limits limits
bool configureSimplePidGains(const std::vector< double > &kpNmPerDeg, const std::vector< double > &kdNmSecPerDeg)
bool configureMaxTorqueFromJointNm(const std::vector< double > &maxJointTorqueNm)
bool setPositionCountsLimits(int axis, int32_t minCounts, int32_t maxCounts)
static constexpr double MICROSECONDS_TO_SECONDS
bool getPositionControlStrategy(uint16_t &strategyValue)
int ciaOpToYarpWithFlavor(int op, int cstFlavor)
double targetCountsToJointDeg(size_t j, int32_t counts) const