feat(motor): add TCHL EtherCAT support and separate vendor operations

Add the TC600E TR motor, PDO mapping, configuration, vendor documents, and
real-motor examples for profile and cyclic position and velocity control.
Share EtherCAT motor conversion, cyclic batch commands, and feedback with
EYOU while supporting configurable CSP velocity feedforward objects and
rated-torque per-mille commands and feedback.

Keep common CiA402 state transitions, mode selection, motion commands, and
profile parameter SDO writes in Cia402Protocol. Move complete vendor limit,
zero calibration, brake, and TCHL enable timing workflows into independent
adapters, with Motor delegating each operation to its owner. Update TI5,
MuJoCo, the motor manager, and arm initialization for the revised interfaces.

Preserve the configured mode during torqueOn and use only the standard
6/7/F enable sequence. Keep PP set-point acknowledgement in position
commands and initialize EtherCAT arm modes before enabling axes.

Validation: built cmvr_es and all three affected real-motor test targets;
listed their tests without running hardware cases. Offline checks covered
CiA402 and vendor enable, calibration, failure cleanup, and PP handshakes.
Code whitespace checks passed; the vendor XML is preserved verbatim.
No real motors were operated during verification.
This commit is contained in:
lgv 2026-10-19 15:53:25 +08:00
parent 0813cad96c
commit 1e3466c1e6
39 changed files with 7986 additions and 753 deletions

View File

@ -0,0 +1,54 @@
# 同川 TC600E TR 单轴模板;未注册为活动设备。
# 当前按实机 PrD.00=0、电子齿轮1:1配置;减速比需读取实机3D06后填写。
motor {
id: "tchl_motors"
motor_groups {
id: "tchl_single_axis"
bus_type: MOTOR_BUS_ETHERCAT
vendor: MOTOR_VENDOR_TCHL
protocol: MOTOR_PROTOCOL_ETHERCAT_CIA402
ethercat {
master_index: 0
cycle_us: 1000
slave_op_timeout_ms: 12000
slave_state_poll_period_ms: 10
cia402 {
state_transition_timeout_ms: 1200
velocity_stop_timeout_ms: 2000
status_poll_period_ms: 10
stopped_velocity_tolerance_rad_s: 0.001
}
dc {
enable: false
reference_motor_id: 1
sync0_cycle_us: 1000
sync0_shift_us: 0
sync_reference_clock_period: 1
assign_activate: 768
sync_monitor_period_ms: 1000
}
slaves { motor_id: 1 alias: 0 position: 0 }
}
# 必须先填写实际行程及速度/加速度上限,再设 enable: true;0不是可运行值。
joint_limits {
enable: true
source: JOINT_LIMIT_SOURCE_CUSTOM
joints { joint_name: "TCHL_AXIS_1" q_lb: -3.14 q_ub: 3.14 qd: 10 qdd: 100 }
}
motors {
motors {
id: 1
joint_name: "TCHL_AXIS_1"
encoder_counts_per_rev: 131072
gear_ratio: 101
}
}
}
}

View File

@ -15,6 +15,7 @@ target_link_libraries(motor_robot_arm
cmvr_es::joint_trajectory_smoother
cmvr_es::collision_checker
cmvr_es::device::motor_manager
cmvr_es::device::ethercat_motor_driver
cmvr_es::device::mujoco_motor_driver
glog
)

View File

@ -23,6 +23,7 @@
#include "common/base/logging/logger.h"
#include "common/math/transform_math.h"
#include "motor/abstract_motor.h"
#include "motor/drivers/ethercat_motor/include/ethercat_motor.h"
#include "motor/manager/include/motor_manager.h"
#include "simulate/mujoco/mujoco_world/include/mujoco_world.h"
@ -135,6 +136,17 @@ bool MotorRobotArm::init()
CMVR_LOG(ERROR) << "[MotorRobotArm] failed to configure algorithms: " << id_;
return false;
}
// Choose the arm's initial position-control mode before enabling any axis.
for (const auto& joint_name : joint_names_) {
const auto motor = motor_manager_->getMotor(joint_name);
if (std::dynamic_pointer_cast<EthercatMotor>(motor) &&
motor->getMode() == msgs::RUN_MODE_UNSPECIFIED &&
!motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_POSITION)) {
CMVR_LOG(ERROR) << "[MotorRobotArm] failed to configure initial motor mode: "
<< joint_name;
return false;
}
}
CMVR_LOG(INFO) << "[MotorRobotArm] (init): Arm '" << id_ << "' init success";
return true;
}

View File

@ -84,22 +84,8 @@ namespace cmvr::device{
return protocol_->torqueOff(node_id_);
}
virtual void setLimitQ(double ub, double lb) {
std::scoped_lock lock(mtx_);
if (!protocol_) {
CMVR_LOG(ERROR) << "Protocol not set for motor";
return;
}
protocol_->setLimitQ(node_id_, ub,lb);
}
virtual void setLimitQd(double qd) {
std::scoped_lock lock(mtx_);
if (!protocol_) {
CMVR_LOG(ERROR) << "Protocol not set for motor";
return;
}
protocol_->setLimitQd(node_id_, qd);
}
virtual bool setLimitQ(double ub, double lb) = 0;
virtual bool setLimitQd(double qd) = 0;
virtual void setLimitQdd(double u_qdd,double l_qdd) {
std::scoped_lock lock(mtx_);
if (!protocol_) {
@ -110,14 +96,7 @@ namespace cmvr::device{
}
// virtual void setLimitTau(double tau) = 0;
// virtual void setLimitCurrent(double tau) = 0;
virtual bool brakeRelease() {
std::scoped_lock lock(mtx_);
if (!protocol_) {
CMVR_LOG(ERROR) << "Protocol not set for motor";
return false;
}
return protocol_->brakeRelease(node_id_);
}
virtual bool brakeRelease() = 0;
virtual bool quickStop() {
std::scoped_lock lock(mtx_);
@ -147,6 +126,16 @@ namespace cmvr::device{
return protocol_->commandProfileVelocity(node_id_, target_qd, max_qdd);
}
// target_tau: per mille of rated torque; torque_slope: per mille/s.
virtual bool commandProfileTorque(double target_tau, std::uint32_t torque_slope) {
std::scoped_lock lock(mtx_);
if (!protocol_) {
CMVR_LOG(ERROR) << "Protocol not set for motor";
return false;
}
return protocol_->commandProfileTorque(node_id_, target_tau, torque_slope);
}
virtual bool commandCyclicPosition(double target_q,
double target_qd = 0.0) {
std::scoped_lock lock(mtx_);
@ -166,6 +155,7 @@ namespace cmvr::device{
return protocol_->commandCyclicVelocity(node_id_, target_qd);
}
// target_tau: per mille of rated torque (1000 = rated torque).
virtual bool commandCyclicTorque(double target_tau) {
std::scoped_lock lock(mtx_);
if (!protocol_) {
@ -175,14 +165,7 @@ namespace cmvr::device{
return protocol_->commandCyclicTorque(node_id_, target_tau);
}
virtual bool calibrateZeroQ() {
std::scoped_lock lock(mtx_);
if (!protocol_) {
CMVR_LOG(ERROR) << "Protocol not set for motor";
return false;
}
return protocol_->calibrateZeroQ(node_id_);
}
virtual bool calibrateZeroQ() = 0;
virtual bool reachedTargetQ() {
if (!protocol_) {
@ -212,6 +195,16 @@ namespace cmvr::device{
return protocol_->getQd(node_id_);
}
// Per mille of rated torque; NaN when unavailable.
virtual double getTau() {
std::scoped_lock lock(mtx_);
if (!protocol_) {
CMVR_LOG(ERROR) << "Protocol not set for motor";
return std::numeric_limits<double>::quiet_NaN();
}
return protocol_->getTau(node_id_);
}
// 使用的通讯协议
virtual bool setProtocol(std::shared_ptr<MotorProtocolInterface> protocol) {

View File

@ -47,6 +47,7 @@ public:
const std::string& id() const { return id_; }
const config::EtherCATConfig& config() const { return config_; }
// Configure before init() and before constructing a protocol using this runtime.
void setPdoMapping(EthercatPdoMapping mapping);
const EthercatPdoMapping& pdoMapping() const { return pdo_mapping_; }
const config::EthercatSlaveConfig* slaveForMotor(int motor_id) const;

View File

@ -28,6 +28,10 @@ struct EthercatPdoMapping {
std::string name;
std::vector<EthercatPdoConfig> rx_pdos;
std::vector<EthercatPdoConfig> tx_pdos;
// CSP velocity feedforward: subindex 0, signed 32-bit RxPDO entry.
// Selects an existing entry; it does not add a PDO mapping.
std::uint16_t velocity_feedforward{0x60B1};
};
} // namespace cmvr::device

View File

@ -1,8 +1,11 @@
add_library(ethercat_motor_driver SHARED
src/ethercat_motor.cpp
src/cia402/cia402_protocol.cpp
src/cia402/cia402_status_monitor.cpp
src/vendor/eyou/eyou_motor.cpp
src/vendor/eyou/eyou_motor_adapter.cpp
src/vendor/tchl/tchl_motor.cpp
src/vendor/tchl/tchl_motor_adapter.cpp
)
target_include_directories(ethercat_motor_driver
@ -48,3 +51,17 @@ target_link_libraries(eyou_motor_device_manager_real_test
pthread
glog
)
add_executable(tchl_motor_real_test
src/vendor/tchl/tchl_motor_real_test.cpp
)
target_link_libraries(tchl_motor_real_test
PRIVATE
cmvr_es::device::motor_manager
absl::cleanup
gtest
gtest_main
pthread
glog
)

View File

@ -28,6 +28,7 @@ public:
std::uint8_t node_id{0};
double q{0.0};
double qd{0.0};
double tau{0.0}; // Per mille of rated torque.
};
struct CyclicVelocityCommand {
@ -35,18 +36,22 @@ public:
double target_qd{0.0};
};
struct CyclicTorqueCommand {
std::uint8_t node_id{0};
double target_tau{0.0}; // Per mille of rated torque.
};
// Configure the runtime's PDO mapping before constructing the protocol.
explicit Cia402Protocol(std::shared_ptr<EthercatMotorBusRuntime> bus_runtime,
const config::Cia402ProtocolConfig& config);
~Cia402Protocol() override;
// Cache actual position and register status monitoring; enable explicitly with torqueOn.
bool initNode(std::uint8_t node_id) override;
bool setMode(std::uint8_t node_id, msgs::RunMode mode) override;
msgs::RunMode getMode(std::uint8_t node_id) override;
void setLimitQdd(std::uint8_t node_id, double u_qdd, double l_qdd) override;
void setLimitQd(std::uint8_t node_id, double qd) override;
void setLimitQ(std::uint8_t node_id, double ub, double lb) override;
bool calibrateZeroQ(std::uint8_t node_id) override;
bool reachedTargetQ(std::uint8_t node_id) override;
bool commandProfilePosition(std::uint8_t node_id,
double target_q,
@ -55,14 +60,17 @@ public:
bool commandProfileVelocity(std::uint8_t node_id,
double target_qd,
double max_qdd) override;
bool commandProfileTorque(std::uint8_t node_id,
double target_tau,
std::uint32_t torque_slope) override;
bool commandCyclicPosition(std::uint8_t node_id,
double target_q,
double target_qd) override;
bool commandCyclicPositionsAtomic(const CyclicPositionCommand* commands,
std::size_t count);
bool commandCyclicVelocitiesAtomic(const CyclicVelocityCommand* commands,
std::size_t count);
bool readFeedbacksAtomic(MotorFeedback* feedbacks, std::size_t count) const;
bool commandCyclicPositionsAtomic(const std::vector<CyclicPositionCommand>& commands);
bool commandCyclicVelocitiesAtomic(const std::vector<CyclicVelocityCommand>& commands);
bool commandCyclicTorquesAtomic(const std::vector<CyclicTorqueCommand>& commands);
// Caller supplies node_id in each element; all feedback uses one PDO snapshot.
bool readFeedbacksAtomic(std::vector<MotorFeedback>& feedbacks) const;
bool commandCyclicVelocity(std::uint8_t node_id,
double target_qd) override;
bool commandCyclicTorque(std::uint8_t node_id, double target_tau) override;
@ -71,12 +79,11 @@ public:
double gear_ratio) override;
bool torqueOn(std::uint8_t node_id) override;
bool torqueOff(std::uint8_t node_id) override;
bool brakeRelease(std::uint8_t node_id) override;
bool quickStop(std::uint8_t node_id) override;
double getQ(std::uint8_t node_id) override;
double getQd(std::uint8_t node_id) override;
bool syncTargetToActualPosition(std::uint8_t node_id);
double getTau(std::uint8_t node_id) override;
private:
struct NodeState {
@ -88,9 +95,6 @@ private:
std::int32_t profile_velocity{0};
std::int32_t profile_acceleration{0};
std::int32_t profile_deceleration{0};
double limit_q_lb{0.0};
double limit_q_ub{0.0};
double limit_qd{0.0};
double limit_qdd{0.0};
double encoder_counts_per_rev{0.0};
double gear_ratio{0.0};
@ -98,9 +102,8 @@ private:
static std::int8_t toCia402Mode_(msgs::RunMode mode);
static msgs::RunMode fromCia402Mode_(std::int8_t mode);
static cia402::Controlword nextControlword_(cia402::Statusword statusword);
static bool isOperationEnabled_(cia402::Statusword statusword);
static bool targetReached_(cia402::Statusword statusword);
static bool torqueToRaw_(double target_tau, std::int16_t& raw);
std::int32_t radToCounts_(double angle_rad, const NodeState& state) const;
double countsToRad_(std::int32_t counts, const NodeState& state) const;
@ -110,11 +113,12 @@ private:
NodeState& nodeState_(std::uint8_t node_id);
const NodeState* findNodeState_(std::uint8_t node_id) const;
bool hasValidConversion_(std::uint8_t node_id, const NodeState& state) const;
bool validateNodePdos_(std::uint8_t node_id) const;
bool readStatusword_(std::uint8_t node_id, std::uint16_t& statusword) const;
bool readActualPosition_(std::uint8_t node_id, std::int32_t& actual_position) const;
bool readActualVelocity_(std::uint8_t node_id, std::int32_t& actual_velocity) const;
bool readModeDisplay_(std::uint8_t node_id, std::int8_t& mode_display) const;
bool refreshMode_(std::uint8_t node_id, NodeState& state) const;
bool readProfileAcceleration_(std::uint8_t node_id, NodeState& state) const;
bool writeControlword_(std::uint8_t node_id, cia402::Controlword controlword);
bool writeControlwordAndWait_(std::uint8_t node_id,
cia402::Controlword controlword,
@ -126,8 +130,6 @@ private:
bool waitMode_(std::uint8_t node_id, std::int8_t target_mode) const;
bool waitSetPointAcknowledged_(std::uint8_t node_id, bool acknowledged) const;
bool waitVelocityNearZero_(std::uint8_t node_id, const char* action_name) const;
bool writePositionLimitsToDictionary_(std::uint8_t node_id, const NodeState& state) const;
bool writeVelocityLimitToDictionary_(std::uint8_t node_id, const NodeState& state) const;
bool writeAccelerationLimitsToDictionary_(std::uint8_t node_id, const NodeState& state) const;
bool prepareSafeTargetsForMode_(std::uint8_t node_id, msgs::RunMode mode, NodeState& state);
bool writeTargetsForMode_(std::uint8_t node_id,
@ -141,11 +143,11 @@ private:
std::size_t capacity,
std::size_t& count) const;
bool writeProfilePositionTarget_(std::uint8_t node_id, NodeState& state);
bool writeNode_(std::uint8_t node_id, NodeState& state);
std::shared_ptr<EthercatMotorBusRuntime> bus_runtime_;
std::unique_ptr<Cia402StatusMonitor> status_monitor_;
config::Cia402ProtocolConfig config_;
const std::uint16_t velocity_feedforward_;
std::unordered_map<std::uint8_t, NodeState> nodes_;
std::mutex cyclic_command_mutex_;
std::vector<EthercatMotorBusRuntime::PdoWrite> cyclic_command_writes_;

View File

@ -23,14 +23,12 @@ public:
Cia402StatusMonitor& operator=(const Cia402StatusMonitor&) = delete;
void addNode(std::uint8_t node_id);
void setExpectedOperationEnabled(std::uint8_t node_id, bool expected);
bool isNodeOperational(std::uint8_t node_id) const;
bool isNodeOperational(std::uint8_t node_id, std::int8_t expected_mode) const;
private:
struct StatusSample {
bool read_ok{false};
bool transport_healthy{false};
bool expected_operation_enabled{false};
bool operation_enabled{false};
bool status_problem{false};
bool command_blocked{false};
@ -43,16 +41,13 @@ private:
};
struct NodeMonitorState {
bool expected_operation_enabled{false};
bool has_last_sample{false};
StatusSample last_sample;
};
void monitorLoop_();
void monitorNode_(std::uint8_t node_id, bool expected_operation_enabled);
bool readStatusSample_(std::uint8_t node_id,
bool expected_operation_enabled,
StatusSample& sample) const;
void monitorNode_(std::uint8_t node_id);
bool readStatusSample_(std::uint8_t node_id, StatusSample& sample) const;
void reportErrorCodeTransition_(std::uint8_t node_id,
bool had_previous,
const StatusSample& previous,

View File

@ -0,0 +1,54 @@
#ifndef CMVR_ES_ETHERCAT_MOTOR_H
#define CMVR_ES_ETHERCAT_MOTOR_H
#include <cstdint>
#include <memory>
#include <vector>
#include "cmvr/config/motor_config/motor_config.pb.h"
#include "devices/motor/abstract_motor.h"
#include "devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h"
namespace cmvr::device {
class EthercatMotor : public AbstractMotor {
public:
EthercatMotor(const config::MotorConfigItem& config,
std::shared_ptr<Cia402Protocol> cia402_protocol);
static bool commandCyclicPositionsAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
const std::vector<double>& positions,
const std::vector<double>& velocities);
static bool readFeedbacksAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
std::vector<double>& positions,
std::vector<double>& velocities);
// Torques are per mille of rated torque: 1000 equals rated torque.
static bool readFeedbacksAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
std::vector<double>& positions,
std::vector<double>& velocities,
std::vector<double>& torques);
static bool commandCyclicVelocitiesAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
const std::vector<double>& velocities);
// Torques are per mille of rated torque: 1000 equals rated torque.
static bool commandCyclicTorquesAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
const std::vector<double>& torques);
protected:
virtual bool hasDependencies_() const;
bool hasValidConversion_() const;
std::int32_t radToCounts_(double angle_rad) const;
std::uint32_t radPerSecToCounts_(double velocity_rad_s) const;
std::shared_ptr<Cia402Protocol> cia402_protocol_;
double encoder_counts_per_rev_{0.0};
double gear_ratio_{0.0};
};
} // namespace cmvr::device
#endif // CMVR_ES_ETHERCAT_MOTOR_H

View File

@ -37,18 +37,14 @@ inline EthercatPdoMapping createEyouCia402PdoMapping()
using namespace eyou_cia402_pdo_mapping_detail;
EthercatPdoConfig rx_pdo;
rx_pdo.index = msgs::CANOPEN_RPDO2_MAP_1601;
rx_pdo.index = msgs::CANOPEN_RPDO1_MAP_1600;
rx_pdo.sync_manager = 2;
rx_pdo.rx = true;
rx_pdo.entries = {
entry(msgs::CIA402_CONTROL_WORD_6040, 0x00, 16, "Control Word"),
entry(msgs::CIA402_TARGET_POSITION_607A, 0x00, 32, "Target Position"),
entry(msgs::CIA402_TARGET_VELOCITY_60FF, 0x00, 32, "Target Velocity"),
entry(msgs::CIA402_TARGET_TORQUE_6071, 0x00, 16, "Target Torque"),
entry(msgs::CIA402_PROFILE_ACCELERATION_6083, 0x00, 32, "Profile Acceleration"),
entry(msgs::CIA402_PROFILE_DECELERATION_6084, 0x00, 32, "Profile Deceleration"),
entry(msgs::CIA402_PROFILE_VELOCITY_6081, 0x00, 32, "Profile Velocity"),
entry(msgs::CIA402_TORQUE_SLOPE_6087, 0x00, 32, "Torque Slope"),
entry(msgs::CIA402_TARGET_TORQUE_6071, 0x00, 16, "Target Torque"), // Per mille.
entry(msgs::CIA402_OPERATION_MODE_6060, 0x00, 8, "Mode Of Operation"),
entry(0x0000, 0x00, 8, "Padding"),
};
@ -61,7 +57,7 @@ inline EthercatPdoMapping createEyouCia402PdoMapping()
entry(msgs::CIA402_STATUS_WORD_6041, 0x00, 16, "Status Word"),
entry(msgs::CIA402_ACTUAL_POSITION_6064, 0x00, 32, "Actual Position"),
entry(msgs::CIA402_ACTUAL_VELOCITY_606C, 0x00, 32, "Actual Velocity"),
entry(msgs::CIA402_ACTUAL_TORQUE_6077, 0x00, 16, "Actual Torque"),
entry(msgs::CIA402_ACTUAL_TORQUE_6077, 0x00, 16, "Actual Torque"), // Per mille.
entry(msgs::CIA402_MODE_DISPLAY_6061, 0x00, 8, "Mode Of Operation Display"),
entry(msgs::CIA402_ERROR_CODE_603F, 0x00, 16, "Error Code"),
entry(0x0000, 0x00, 8, "Padding"),
@ -71,6 +67,7 @@ inline EthercatPdoMapping createEyouCia402PdoMapping()
mapping.vendor_id = VENDOR_ID;
mapping.product_code = PRODUCT_CODE;
mapping.name = "EYOU ServoModule ECAT V145 CiA402";
mapping.velocity_feedforward = msgs::CIA402_TARGET_VELOCITY_60FF;
mapping.rx_pdos.push_back(std::move(rx_pdo));
mapping.tx_pdos.push_back(std::move(tx_pdo));
return mapping;

View File

@ -3,16 +3,13 @@
#include <cstdint>
#include <memory>
#include <vector>
#include "cmvr/config/motor_config/motor_config.pb.h"
#include "devices/motor/abstract_motor.h"
#include "devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h"
#include "devices/motor/drivers/ethercat_motor/include/ethercat_motor.h"
#include "devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor_adapter.h"
namespace cmvr::device {
class EyouMotor final : public AbstractMotor {
class EyouMotor final : public EthercatMotor {
public:
EyouMotor(const config::MotorConfigItem& config,
std::shared_ptr<Cia402Protocol> cia402_protocol,
@ -20,35 +17,17 @@ public:
std::string typeName() const override { return "EyouMotor"; }
bool init() override;
void setLimitQ(double ub, double lb) override;
void setLimitQd(double qd) override;
bool setLimitQ(double ub, double lb) override;
bool setLimitQd(double qd) override;
bool calibrateZeroQ() override;
bool brakeRelease() override;
static bool commandCyclicPositionsAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
const std::vector<double>& positions,
const std::vector<double>& velocities);
static bool readFeedbacksAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
std::vector<double>& positions,
std::vector<double>& velocities);
static bool commandCyclicVelocitiesAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
const std::vector<double>& velocities);
private:
bool hasDependencies_() const;
bool hasValidConversion_() const;
bool hasDependencies_() const override;
bool writeVendorPositionLimits_() const;
bool writeVendorVelocityLimit_() const;
std::int32_t radToCounts_(double angle_rad) const;
std::uint32_t radPerSecToCounts_(double velocity_rad_s) const;
std::shared_ptr<Cia402Protocol> cia402_protocol_;
std::unique_ptr<EyouMotorAdapter> vendor_adapter_;
double encoder_counts_per_rev_{0.0};
double gear_ratio_{0.0};
};
} // namespace cmvr::device

View File

@ -3,6 +3,8 @@
#include <cstdint>
#include <memory>
#include <optional>
#include <utility>
#include "devices/motor/bus_runtime/ethercat/include/ethercat_motor_bus_runtime.h"
#include "devices/motor/drivers/ethercat_motor/include/vendor/motor_vendor_adapter.h"
@ -26,7 +28,11 @@ public:
bool brakeRelease(std::uint8_t node_id) override;
private:
bool syncTargetToActualPosition_(std::uint8_t node_id,
std::int32_t& actual_position) const;
std::shared_ptr<EthercatMotorBusRuntime> bus_runtime_;
std::optional<std::pair<std::int32_t, std::int32_t>> position_limits_;
};
} // namespace cmvr::device

View File

@ -10,11 +10,14 @@ public:
virtual ~MotorVendorAdapter() = default;
virtual bool initNode(std::uint8_t node_id) = 0;
// Each operation owns the complete vendor sequence, including standard objects.
// Position/velocity arguments use drive counts and counts per second.
virtual bool writePositionLimits(std::uint8_t node_id,
std::int32_t lower_limit,
std::int32_t upper_limit) = 0;
virtual bool writeVelocityLimit(std::uint8_t node_id,
std::uint32_t velocity_limit) = 0;
// Also refresh targets and restore position limits before reporting success.
virtual bool calibrateZero(std::uint8_t node_id,
std::int64_t counts_per_joint_revolution,
std::int32_t& zeroed_position) = 0;

View File

@ -0,0 +1,79 @@
#ifndef CMVR_ES_TCHL_CIA402_PDO_MAPPING_H
#define CMVR_ES_TCHL_CIA402_PDO_MAPPING_H
#include <cstdint>
#include <string>
#include <utility>
#include "cmvr/msgs/canopen.pb.h"
#include "cmvr/msgs/cia402.pb.h"
#include "devices/motor/bus_runtime/ethercat/include/ethercat_pdo_mapping.h"
namespace cmvr::device {
namespace tchl_cia402_pdo_mapping_detail {
inline constexpr std::uint32_t VENDOR_ID = 0x00075500;
inline constexpr std::uint32_t PRODUCT_CODE = 0x00000002;
inline EthercatPdoEntryConfig entry(const std::uint16_t index,
const std::uint8_t subindex,
const std::uint8_t bit_len,
std::string name)
{
EthercatPdoEntryConfig cfg;
cfg.index = index;
cfg.subindex = subindex;
cfg.bit_len = bit_len;
cfg.name = std::move(name);
return cfg;
}
} // namespace tchl_cia402_pdo_mapping_detail
inline EthercatPdoMapping createTchlCia402PdoMapping()
{
using namespace tchl_cia402_pdo_mapping_detail;
// Default layout from TC-TECH_TC600E_TR_1.5.xml: 17-byte RxPDO, no padding.
EthercatPdoConfig rx_pdo;
rx_pdo.index = msgs::CANOPEN_RPDO2_MAP_1601;
rx_pdo.sync_manager = 2;
rx_pdo.rx = true;
rx_pdo.entries = {
entry(msgs::CIA402_CONTROL_WORD_6040, 0x00, 16, "Control Word"),
entry(msgs::CIA402_TARGET_POSITION_607A, 0x00, 32, "Target Position"),
entry(msgs::CIA402_TARGET_VELOCITY_60FF, 0x00, 32, "Target Velocity"),
entry(msgs::CIA402_TARGET_TORQUE_6071, 0x00, 16, "Target Torque"),
entry(msgs::CIA402_VELOCITY_OFFSET_60B1, 0x00, 32, "Velocity Offset"),
entry(msgs::CIA402_OPERATION_MODE_6060, 0x00, 8, "Mode Of Operation"),
};
// Default 19-byte TxPDO, including following error and mode display.
EthercatPdoConfig tx_pdo;
tx_pdo.index = msgs::CANOPEN_TPDO2_MAP_1A01;
tx_pdo.sync_manager = 3;
tx_pdo.rx = false;
tx_pdo.entries = {
entry(msgs::CIA402_STATUS_WORD_6041, 0x00, 16, "Status Word"),
entry(msgs::CIA402_ACTUAL_POSITION_6064, 0x00, 32, "Actual Position"),
entry(msgs::CIA402_ACTUAL_VELOCITY_606C, 0x00, 32, "Actual Velocity"),
entry(msgs::CIA402_ACTUAL_TORQUE_6077, 0x00, 16, "Actual Torque"),
entry(msgs::CIA402_FOLLOWING_ERROR_ACTUAL_VALUE_60F4, 0x00, 32, "Following Error"),
entry(msgs::CIA402_ERROR_CODE_603F, 0x00, 16, "Error Code"),
entry(msgs::CIA402_MODE_DISPLAY_6061, 0x00, 8, "Mode Of Operation Display"),
};
EthercatPdoMapping mapping;
mapping.vendor_id = VENDOR_ID;
mapping.product_code = PRODUCT_CODE;
mapping.name = "TCHL TC600E TR CiA402";
mapping.velocity_feedforward = msgs::CIA402_VELOCITY_OFFSET_60B1;
mapping.rx_pdos.push_back(std::move(rx_pdo));
mapping.tx_pdos.push_back(std::move(tx_pdo));
return mapping;
}
} // namespace cmvr::device
#endif // CMVR_ES_TCHL_CIA402_PDO_MAPPING_H

View File

@ -0,0 +1,36 @@
#ifndef CMVR_ES_TCHL_MOTOR_H
#define CMVR_ES_TCHL_MOTOR_H
#include <memory>
#include "devices/motor/drivers/ethercat_motor/include/ethercat_motor.h"
#include "devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_motor_adapter.h"
namespace cmvr::device {
class TchlMotor final : public EthercatMotor {
public:
TchlMotor(const config::MotorConfigItem& config,
std::shared_ptr<Cia402Protocol> cia402_protocol,
std::unique_ptr<TchlMotorAdapter> vendor_adapter);
std::string typeName() const override { return "TchlMotor"; }
bool init() override;
bool torqueOn() override;
bool torqueOff() override;
bool setLimitQ(double ub, double lb) override;
bool setLimitQd(double qd) override;
bool calibrateZeroQ() override;
bool brakeRelease() override;
private:
bool hasDependencies_() const override;
bool writeVendorPositionLimits_() const;
bool writeVendorVelocityLimit_() const;
std::unique_ptr<TchlMotorAdapter> vendor_adapter_;
};
} // namespace cmvr::device
#endif // CMVR_ES_TCHL_MOTOR_H

View File

@ -0,0 +1,51 @@
#ifndef CMVR_ES_TCHL_MOTOR_ADAPTER_H
#define CMVR_ES_TCHL_MOTOR_ADAPTER_H
#include <chrono>
#include <cstdint>
#include <memory>
#include "devices/motor/bus_runtime/ethercat/include/ethercat_motor_bus_runtime.h"
#include "devices/motor/drivers/ethercat_motor/include/cia402/cia402_objects.h"
#include "devices/motor/drivers/ethercat_motor/include/vendor/motor_vendor_adapter.h"
namespace cmvr::device {
class TchlMotorAdapter final : public MotorVendorAdapter {
public:
explicit TchlMotorAdapter(std::shared_ptr<EthercatMotorBusRuntime> bus_runtime);
~TchlMotorAdapter() override = default;
bool initNode(std::uint8_t node_id) override;
bool writePositionLimits(std::uint8_t node_id,
std::int32_t lower_limit,
std::int32_t upper_limit) override;
bool writeVelocityLimit(std::uint8_t node_id,
std::uint32_t velocity_limit) override;
bool calibrateZero(std::uint8_t node_id,
std::int64_t counts_per_joint_revolution,
std::int32_t& zeroed_position) override;
bool brakeRelease(std::uint8_t node_id) override;
bool torqueOn(std::uint8_t node_id, std::int64_t counts_per_joint_revolution);
bool torqueOff(std::uint8_t node_id, std::int64_t counts_per_joint_revolution);
private:
bool writeSafeTargets_(std::uint8_t node_id) const;
bool writeControlwordAndWait_(std::uint8_t node_id, std::uint16_t command,
cia402::DeviceState expected_state,
std::int8_t expected_mode = 0) const;
bool waitVelocityNearZero_(std::uint8_t node_id,
std::int64_t counts_per_joint_revolution) const;
bool waitZeroCalibration_(std::uint8_t node_id, std::int32_t& zeroed_position) const;
std::shared_ptr<EthercatMotorBusRuntime> bus_runtime_;
std::chrono::milliseconds enable_delay_{400};
std::chrono::milliseconds disable_delay_{200};
bool has_position_limits_{false};
std::int32_t lower_position_limit_{0};
std::int32_t upper_position_limit_{0};
};
} // namespace cmvr::device
#endif // CMVR_ES_TCHL_MOTOR_ADAPTER_H

View File

@ -18,7 +18,8 @@ namespace cmvr::device {
Cia402Protocol::Cia402Protocol(std::shared_ptr<EthercatMotorBusRuntime> bus_runtime,
const config::Cia402ProtocolConfig& config)
: bus_runtime_(std::move(bus_runtime)),
config_(config)
config_(config),
velocity_feedforward_(bus_runtime_ ? bus_runtime_->pdoMapping().velocity_feedforward : 0)
{
comm_proto = CommProto::ETHERCAT;
cyclic_command_writes_.reserve(512);
@ -36,17 +37,14 @@ bool Cia402Protocol::initNode(const std::uint8_t node_id)
return false;
}
if (!validateNodePdos_(node_id)) {
std::int32_t actual_position = 0;
if (!readActualPosition_(node_id, actual_position)) {
CMVR_LOG(ERROR) << "[Cia402Protocol] failed to read actual position during init, node="
<< static_cast<int>(node_id);
return false;
}
auto& state = nodeState_(node_id);
std::int32_t actual_position = 0;
if (readActualPosition_(node_id, actual_position)) {
state.target_position = actual_position;
}
if (!writeNode_(node_id, state)) {
return false;
}
state.target_position = actual_position;
status_monitor_->addNode(node_id);
return true;
}
@ -58,15 +56,29 @@ bool Cia402Protocol::commandProfilePosition(const std::uint8_t node_id,
{
auto& state = nodeState_(node_id);
if (!hasValidConversion_(node_id, state) ||
!status_monitor_->isNodeOperational(node_id)) {
!status_monitor_->isNodeOperational(node_id, 1)) {
return false;
}
state.mode = msgs::RUN_MODE_PROFILE_POSITION;
state.target_position = radToCounts_(target_q, state);
state.profile_velocity = std::abs(radPerSecToCounts_(max_qd, state));
if (max_qd > 0.0) {
state.profile_velocity = std::abs(radPerSecToCounts_(max_qd, state));
} else {
std::uint32_t profile_velocity = 0;
if (!bus_runtime_->readSdo<std::uint32_t>(
node_id, msgs::CIA402_PROFILE_VELOCITY_6081, 0x00, profile_velocity) ||
profile_velocity > static_cast<std::uint32_t>(
std::numeric_limits<std::int32_t>::max())) {
return false;
}
state.profile_velocity = static_cast<std::int32_t>(profile_velocity);
}
if (max_qdd > 0.0) {
const auto profile_acceleration = std::abs(radPerSec2ToCounts_(max_qdd, state));
state.profile_acceleration = profile_acceleration;
state.profile_deceleration = profile_acceleration;
} else if (!readProfileAcceleration_(node_id, state)) {
return false;
}
return writeProfilePositionTarget_(node_id, state);
}
@ -77,31 +89,66 @@ bool Cia402Protocol::commandProfileVelocity(const std::uint8_t node_id,
{
auto& state = nodeState_(node_id);
if (!hasValidConversion_(node_id, state) ||
!status_monitor_->isNodeOperational(node_id)) {
!status_monitor_->isNodeOperational(node_id, 3)) {
return false;
}
state.mode = msgs::RUN_MODE_PROFILE_VELOCITY;
state.target_velocity = radPerSecToCounts_(target_qd, state);
if (max_qdd > 0.0) {
const auto profile_acceleration = std::abs(radPerSec2ToCounts_(max_qdd, state));
state.profile_acceleration = profile_acceleration;
state.profile_deceleration = profile_acceleration;
} else if (!readProfileAcceleration_(node_id, state)) {
return false;
}
return writeNode_(node_id, state);
if (!bus_runtime_->writeSdo<std::uint32_t>(
node_id, msgs::CIA402_PROFILE_ACCELERATION_6083, 0x00,
static_cast<std::uint32_t>(state.profile_acceleration)) ||
!bus_runtime_->writeSdo<std::uint32_t>(
node_id, msgs::CIA402_PROFILE_DECELERATION_6084, 0x00,
static_cast<std::uint32_t>(state.profile_deceleration))) {
return false;
}
return writeTargetsForMode_(node_id, state.mode, state);
}
bool Cia402Protocol::commandProfileTorque(const std::uint8_t node_id,
const double target_tau,
const std::uint32_t torque_slope)
{
const auto* state = findNodeState_(node_id);
std::int16_t raw_torque = 0;
if (!bus_runtime_ || !state ||
!status_monitor_->isNodeOperational(node_id, 4) || torque_slope == 0 ||
!torqueToRaw_(target_tau, raw_torque)) {
return false;
}
if (!bus_runtime_->writeSdo<std::uint32_t>(
node_id, msgs::CIA402_TORQUE_SLOPE_6087, 0x00, torque_slope) ||
!bus_runtime_->writePdo<std::int16_t>(
node_id, msgs::CIA402_TARGET_TORQUE_6071, 0x00, raw_torque)) {
return false;
}
auto& current_state = nodeState_(node_id);
current_state.mode = msgs::RUN_MODE_TORQUE;
current_state.target_torque = raw_torque;
return true;
}
bool Cia402Protocol::commandCyclicPosition(const std::uint8_t node_id,
const double target_q,
const double target_qd)
{
const CyclicPositionCommand command{node_id, target_q, target_qd};
return commandCyclicPositionsAtomic(&command, 1);
thread_local std::vector<CyclicPositionCommand> commands(1);
commands.front() = {node_id, target_q, target_qd};
return commandCyclicPositionsAtomic(commands);
}
bool Cia402Protocol::commandCyclicPositionsAtomic(
const CyclicPositionCommand* commands,
const std::size_t count)
const std::vector<CyclicPositionCommand>& commands)
{
if (!bus_runtime_ || !commands || count == 0 || count > 256) {
const auto count = commands.size();
if (!bus_runtime_ || commands.empty() || count > 256) {
return false;
}
@ -113,8 +160,7 @@ bool Cia402Protocol::commandCyclicPositionsAtomic(
const auto& command = commands[i];
const auto* state = findNodeState_(command.node_id);
if (!state || !hasValidConversion_(command.node_id, *state) ||
state->mode != msgs::RUN_MODE_CYCLIC_SYNC_POSITION ||
!status_monitor_->isNodeOperational(command.node_id)) {
!status_monitor_->isNodeOperational(command.node_id, 8)) {
return false;
}
for (std::size_t previous = 0; previous < i; ++previous) {
@ -132,7 +178,7 @@ bool Cia402Protocol::commandCyclicPositionsAtomic(
cyclic_command_writes_.push_back(
EthercatMotorBusRuntime::makePdoWrite<std::int32_t>(
command.node_id,
msgs::CIA402_TARGET_VELOCITY_60FF,
velocity_feedforward_,
0x00,
radPerSecToCounts_(command.target_qd, *state)));
}
@ -144,20 +190,21 @@ bool Cia402Protocol::commandCyclicPositionsAtomic(
for (std::size_t i = 0; i < count; ++i) {
auto& state = nodeState_(commands[i].node_id);
state.mode = msgs::RUN_MODE_CYCLIC_SYNC_POSITION;
state.target_position = radToCounts_(commands[i].target_q, state);
state.target_velocity = radPerSecToCounts_(commands[i].target_qd, state);
}
return true;
}
bool Cia402Protocol::readFeedbacksAtomic(MotorFeedback* feedbacks,
const std::size_t count) const
bool Cia402Protocol::readFeedbacksAtomic(std::vector<MotorFeedback>& feedbacks) const
{
if (!bus_runtime_ || !feedbacks || count == 0 || count > 256) {
const auto count = feedbacks.size();
if (!bus_runtime_ || feedbacks.empty() || count > 256) {
return false;
}
std::array<EthercatMotorBusRuntime::PdoRead, 512> reads{};
std::array<EthercatMotorBusRuntime::PdoRead, 768> reads{};
for (std::size_t i = 0; i < count; ++i) {
const auto* state = findNodeState_(feedbacks[i].node_id);
if (!state || !hasValidConversion_(feedbacks[i].node_id, *state)) {
@ -168,13 +215,15 @@ bool Cia402Protocol::readFeedbacksAtomic(MotorFeedback* feedbacks,
return false;
}
}
reads[2 * i] = EthercatMotorBusRuntime::makePdoRead<std::int32_t>(
reads[3 * i] = EthercatMotorBusRuntime::makePdoRead<std::int32_t>(
feedbacks[i].node_id, msgs::CIA402_ACTUAL_POSITION_6064, 0x00);
reads[2 * i + 1] = EthercatMotorBusRuntime::makePdoRead<std::int32_t>(
reads[3 * i + 1] = EthercatMotorBusRuntime::makePdoRead<std::int32_t>(
feedbacks[i].node_id, msgs::CIA402_ACTUAL_VELOCITY_606C, 0x00);
reads[3 * i + 2] = EthercatMotorBusRuntime::makePdoRead<std::int16_t>(
feedbacks[i].node_id, msgs::CIA402_ACTUAL_TORQUE_6077, 0x00);
}
if (!bus_runtime_->readPdosAtomic(reads.data(), count * 2)) {
if (!bus_runtime_->readPdosAtomic(reads.data(), count * 3)) {
return false;
}
@ -183,20 +232,22 @@ bool Cia402Protocol::readFeedbacksAtomic(MotorFeedback* feedbacks,
if (!state) {
return false;
}
const auto position = EthercatMotorBusRuntime::pdoReadValue<std::int32_t>(reads[2 * i]);
const auto position = EthercatMotorBusRuntime::pdoReadValue<std::int32_t>(reads[3 * i]);
const auto velocity =
EthercatMotorBusRuntime::pdoReadValue<std::int32_t>(reads[2 * i + 1]);
EthercatMotorBusRuntime::pdoReadValue<std::int32_t>(reads[3 * i + 1]);
feedbacks[i].q = countsToRad_(position, *state);
feedbacks[i].qd = countsToRadPerSec_(velocity, *state);
feedbacks[i].tau =
EthercatMotorBusRuntime::pdoReadValue<std::int16_t>(reads[3 * i + 2]);
}
return true;
}
bool Cia402Protocol::commandCyclicVelocitiesAtomic(
const CyclicVelocityCommand* commands,
const std::size_t count)
const std::vector<CyclicVelocityCommand>& commands)
{
if (!bus_runtime_ || !commands || count == 0 || count > 256) {
const auto count = commands.size();
if (!bus_runtime_ || commands.empty() || count > 256) {
return false;
}
std::lock_guard<std::mutex> lock(cyclic_command_mutex_);
@ -207,8 +258,7 @@ bool Cia402Protocol::commandCyclicVelocitiesAtomic(
const auto* state = findNodeState_(command.node_id);
if (!std::isfinite(command.target_qd) || !state ||
!hasValidConversion_(command.node_id, *state) ||
state->mode != msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY ||
!status_monitor_->isNodeOperational(command.node_id)) {
!status_monitor_->isNodeOperational(command.node_id, 9)) {
return false;
}
for (std::size_t previous = 0; previous < i; ++previous) {
@ -234,6 +284,7 @@ bool Cia402Protocol::commandCyclicVelocitiesAtomic(
}
for (std::size_t i = 0; i < count; ++i) {
auto& state = nodeState_(commands[i].node_id);
state.mode = msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY;
state.target_velocity = radPerSecToCounts_(commands[i].target_qd, state);
}
return true;
@ -242,28 +293,74 @@ bool Cia402Protocol::commandCyclicVelocitiesAtomic(
bool Cia402Protocol::commandCyclicVelocity(const std::uint8_t node_id,
const double target_qd)
{
const CyclicVelocityCommand command{node_id, target_qd};
return commandCyclicVelocitiesAtomic(&command, 1);
thread_local std::vector<CyclicVelocityCommand> commands(1);
commands.front() = {node_id, target_qd};
return commandCyclicVelocitiesAtomic(commands);
}
bool Cia402Protocol::commandCyclicTorque(const std::uint8_t node_id,
const double target_tau)
{
(void)target_tau;
CMVR_LOG(ERROR) << "[Cia402Protocol] cyclic torque command is not implemented, node="
<< static_cast<int>(node_id);
return false;
thread_local std::vector<CyclicTorqueCommand> commands(1);
commands.front() = {node_id, target_tau};
return commandCyclicTorquesAtomic(commands);
}
bool Cia402Protocol::commandCyclicTorquesAtomic(
const std::vector<CyclicTorqueCommand>& commands)
{
if (!bus_runtime_ || commands.empty() || commands.size() > 256) {
return false;
}
std::lock_guard<std::mutex> lock(cyclic_command_mutex_);
cyclic_command_writes_.clear();
for (std::size_t i = 0; i < commands.size(); ++i) {
const auto& command = commands[i];
const auto* state = findNodeState_(command.node_id);
std::int16_t raw_torque = 0;
if (!state ||
!status_monitor_->isNodeOperational(command.node_id, 10) ||
!torqueToRaw_(command.target_tau, raw_torque)) {
return false;
}
for (std::size_t previous = 0; previous < i; ++previous) {
if (commands[previous].node_id == command.node_id) {
return false;
}
}
cyclic_command_writes_.push_back(
EthercatMotorBusRuntime::makePdoWrite<std::int16_t>(
command.node_id, msgs::CIA402_TARGET_TORQUE_6071, 0x00, raw_torque));
}
if (!bus_runtime_->writePdosAtomic(cyclic_command_writes_.data(),
cyclic_command_writes_.size())) {
return false;
}
for (const auto& command : commands) {
auto& state = nodeState_(command.node_id);
state.mode = msgs::RUN_MODE_CYCLIC_SYNC_CURRENT;
state.target_torque = static_cast<std::int16_t>(std::llround(command.target_tau));
}
return true;
}
bool Cia402Protocol::setMode(const std::uint8_t node_id, const msgs::RunMode mode)
{
auto& state = nodeState_(node_id);
if (!prepareSafeTargetsForMode_(node_id, mode, state)) {
if (mode == msgs::RUN_MODE_UNSPECIFIED ||
!refreshMode_(node_id, state) ||
!prepareSafeTargetsForMode_(node_id, mode, state)) {
return false;
}
state.mode = mode;
if (!writeNode_(node_id, state)) {
CMVR_LOG(ERROR) << "[Cia402Protocol] failed to write mode/controlword PDOs, node="
std::array<EthercatMotorBusRuntime::PdoWrite, 3> writes{};
std::size_t count = 0;
writes[count++] = EthercatMotorBusRuntime::makePdoWrite<std::int8_t>(
node_id, msgs::CIA402_OPERATION_MODE_6060, 0x00, toCia402Mode_(mode));
if (!appendTargetWritesForMode_(node_id, mode, state,
writes.data(), writes.size(), count) ||
!bus_runtime_->writePdosAtomic(writes.data(), count)) {
CMVR_LOG(ERROR) << "[Cia402Protocol] failed to write mode/target PDOs, node="
<< static_cast<int>(node_id)
<< ", mode=" << static_cast<int>(mode);
return false;
@ -275,7 +372,9 @@ msgs::RunMode Cia402Protocol::getMode(const std::uint8_t node_id)
{
std::int8_t mode_display = 0;
if (readModeDisplay_(node_id, mode_display)) {
return fromCia402Mode_(mode_display);
auto& state = nodeState_(node_id);
state.mode = fromCia402Mode_(mode_display);
return state.mode;
}
return nodeState_(node_id).mode;
}
@ -294,35 +393,6 @@ void Cia402Protocol::setLimitQdd(const std::uint8_t node_id,
}
}
void Cia402Protocol::setLimitQd(const std::uint8_t node_id, const double qd)
{
auto& state = nodeState_(node_id);
state.limit_qd = std::abs(qd);
if (hasValidConversion_(node_id, state)) {
state.profile_velocity = std::abs(radPerSecToCounts_(state.limit_qd, state));
writeVelocityLimitToDictionary_(node_id, state);
}
}
void Cia402Protocol::setLimitQ(const std::uint8_t node_id,
const double ub,
const double lb)
{
auto& state = nodeState_(node_id);
state.limit_q_ub = ub;
state.limit_q_lb = lb;
if (hasValidConversion_(node_id, state)) {
writePositionLimitsToDictionary_(node_id, state);
}
}
bool Cia402Protocol::calibrateZeroQ(const std::uint8_t node_id)
{
CMVR_LOG(ERROR) << "[Cia402Protocol] zero calibration is vendor-specific, node="
<< static_cast<int>(node_id);
return false;
}
bool Cia402Protocol::reachedTargetQ(const std::uint8_t node_id)
{
std::uint16_t statusword = 0;
@ -348,7 +418,6 @@ bool Cia402Protocol::torqueOn(const std::uint8_t node_id)
return false;
}
status_monitor_->setExpectedOperationEnabled(node_id, false);
auto& state = nodeState_(node_id);
std::uint16_t statusword = 0;
if (readStatusword_(node_id, statusword) && cia402::statusword(statusword).fault != 0) {
@ -359,17 +428,17 @@ bool Cia402Protocol::torqueOn(const std::uint8_t node_id)
std::chrono::milliseconds(config_.status_poll_period_ms()));
}
if (!prepareSafeTargetsForMode_(node_id, msgs::RUN_MODE_PROFILE_POSITION, state)) {
if (!refreshMode_(node_id, state)) {
return false;
}
state.mode = msgs::RUN_MODE_PROFILE_POSITION;
state.target_velocity = 0;
state.target_torque = 0;
if (!writeTargetsForMode_(node_id, state.mode, state)) {
if (state.mode == msgs::RUN_MODE_UNSPECIFIED) {
CMVR_LOG(ERROR) << "[Cia402Protocol] configure an operation mode before enabling, node="
<< static_cast<int>(node_id);
return false;
}
if (!bus_runtime_->writePdo<std::int8_t>(node_id, msgs::CIA402_OPERATION_MODE_6060, 0x00,
toCia402Mode_(state.mode))) {
if (!prepareSafeTargetsForMode_(node_id, state.mode, state) ||
!bus_runtime_->writePdo<std::int32_t>(node_id, velocity_feedforward_, 0x00, 0) ||
!writeTargetsForMode_(node_id, state.mode, state)) {
return false;
}
@ -383,27 +452,9 @@ bool Cia402Protocol::torqueOn(const std::uint8_t node_id)
"Switched On")) {
return false;
}
if (!writeControlwordAndWait_(node_id, cia402::enableOperationControlword(),
cia402::DeviceState::OperationEnabled,
"Operation Enabled")) {
return false;
}
if (!waitMode_(node_id, toCia402Mode_(state.mode))) {
return false;
}
std::int32_t actual_position = 0;
if (readActualPosition_(node_id, actual_position)) {
state.target_position = actual_position;
}
state.controlword = cia402::profilePositionControlword(false);
const bool enabled = writeTargetsForMode_(node_id, state.mode, state) &&
writeControlword_(node_id, state.controlword) &&
waitSetPointAcknowledged_(node_id, false);
if (enabled) {
status_monitor_->setExpectedOperationEnabled(node_id, true);
}
return enabled;
return writeControlwordAndWait_(node_id, cia402::enableOperationControlword(),
cia402::DeviceState::OperationEnabled,
"Operation Enabled");
}
bool Cia402Protocol::torqueOff(const std::uint8_t node_id)
@ -412,8 +463,10 @@ bool Cia402Protocol::torqueOff(const std::uint8_t node_id)
return false;
}
status_monitor_->setExpectedOperationEnabled(node_id, false);
auto& state = nodeState_(node_id);
if (!refreshMode_(node_id, state)) {
return false;
}
std::int32_t actual_position = 0;
if (readActualPosition_(node_id, actual_position)) {
state.target_position = actual_position;
@ -457,21 +510,16 @@ bool Cia402Protocol::torqueOff(const std::uint8_t node_id)
"Switch On Disabled");
}
bool Cia402Protocol::brakeRelease(const std::uint8_t node_id)
{
CMVR_LOG(ERROR) << "[Cia402Protocol] brake release is vendor-specific, node="
<< static_cast<int>(node_id);
return false;
}
bool Cia402Protocol::quickStop(const std::uint8_t node_id)
{
if (!bus_runtime_) {
return false;
}
status_monitor_->setExpectedOperationEnabled(node_id, false);
auto& state = nodeState_(node_id);
if (!refreshMode_(node_id, state)) {
return false;
}
state.target_velocity = 0;
state.target_torque = 0;
if (!writeTargetsForMode_(node_id, state.mode, state)) {
@ -511,20 +559,14 @@ double Cia402Protocol::getQd(const std::uint8_t node_id)
return countsToRadPerSec_(actual_velocity, state);
}
bool Cia402Protocol::syncTargetToActualPosition(const std::uint8_t node_id)
double Cia402Protocol::getTau(const std::uint8_t node_id)
{
std::int32_t actual_position = 0;
if (!readActualPosition_(node_id, actual_position)) {
CMVR_LOG(ERROR) << "[Cia402Protocol] failed to read actual position, node="
<< static_cast<int>(node_id);
return false;
std::int16_t actual_torque = 0;
if (!bus_runtime_ || !bus_runtime_->readPdo<std::int16_t>(
node_id, msgs::CIA402_ACTUAL_TORQUE_6077, 0x00, actual_torque)) {
return std::numeric_limits<double>::quiet_NaN();
}
auto& state = nodeState_(node_id);
state.target_position = actual_position;
state.target_velocity = 0;
state.target_torque = 0;
return writeTargetsForMode_(node_id, state.mode, state);
return actual_torque;
}
std::int8_t Cia402Protocol::toCia402Mode_(const msgs::RunMode mode)
@ -534,6 +576,8 @@ std::int8_t Cia402Protocol::toCia402Mode_(const msgs::RunMode mode)
return 1;
case msgs::RUN_MODE_PROFILE_VELOCITY:
return 3;
case msgs::RUN_MODE_TORQUE:
return 4;
case msgs::RUN_MODE_HOMING:
return 6;
case msgs::RUN_MODE_CYCLIC_SYNC_POSITION:
@ -554,6 +598,8 @@ msgs::RunMode Cia402Protocol::fromCia402Mode_(const std::int8_t mode)
return msgs::RUN_MODE_PROFILE_POSITION;
case 3:
return msgs::RUN_MODE_PROFILE_VELOCITY;
case 4:
return msgs::RUN_MODE_TORQUE;
case 6:
return msgs::RUN_MODE_HOMING;
case 8:
@ -567,36 +613,22 @@ msgs::RunMode Cia402Protocol::fromCia402Mode_(const std::int8_t mode)
}
}
cia402::Controlword Cia402Protocol::nextControlword_(const cia402::Statusword statusword)
{
if (statusword.fault != 0) {
return cia402::faultResetControlword();
}
if (cia402::hasState(statusword, cia402::DeviceState::SwitchOnDisabled)) {
return cia402::shutdownControlword();
}
if (cia402::hasState(statusword, cia402::DeviceState::ReadyToSwitchOn)) {
return cia402::switchOnControlword();
}
if (cia402::hasState(statusword, cia402::DeviceState::SwitchedOn)) {
return cia402::enableOperationControlword();
}
if (cia402::hasState(statusword, cia402::DeviceState::OperationEnabled)) {
return cia402::enableOperationControlword();
}
return cia402::shutdownControlword();
}
bool Cia402Protocol::isOperationEnabled_(const cia402::Statusword statusword)
{
return cia402::isOperationEnabled(statusword);
}
bool Cia402Protocol::targetReached_(const cia402::Statusword statusword)
{
return cia402::targetReached(statusword);
}
bool Cia402Protocol::torqueToRaw_(const double target_tau, std::int16_t& raw)
{
if (!std::isfinite(target_tau) ||
target_tau < std::numeric_limits<std::int16_t>::min() ||
target_tau > std::numeric_limits<std::int16_t>::max()) {
return false;
}
raw = static_cast<std::int16_t>(std::llround(target_tau));
return true;
}
std::int32_t Cia402Protocol::radToCounts_(const double angle_rad,
const NodeState& state) const
{
@ -666,46 +698,6 @@ bool Cia402Protocol::hasValidConversion_(const std::uint8_t node_id,
return false;
}
bool Cia402Protocol::validateNodePdos_(const std::uint8_t node_id) const
{
if (!bus_runtime_) {
return false;
}
struct RequiredEntry {
std::uint16_t index;
std::uint8_t subindex;
const char* name;
};
const RequiredEntry required[] = {
{msgs::CIA402_CONTROL_WORD_6040, 0x00, "controlword"},
{msgs::CIA402_TARGET_POSITION_607A, 0x00, "target position"},
{msgs::CIA402_TARGET_VELOCITY_60FF, 0x00, "target velocity"},
{msgs::CIA402_TARGET_TORQUE_6071, 0x00, "target torque"},
{msgs::CIA402_PROFILE_ACCELERATION_6083, 0x00, "profile acceleration"},
{msgs::CIA402_PROFILE_DECELERATION_6084, 0x00, "profile deceleration"},
{msgs::CIA402_PROFILE_VELOCITY_6081, 0x00, "profile velocity"},
{msgs::CIA402_OPERATION_MODE_6060, 0x00, "operation mode"},
{msgs::CIA402_STATUS_WORD_6041, 0x00, "statusword"},
{msgs::CIA402_ACTUAL_POSITION_6064, 0x00, "actual position"},
{msgs::CIA402_ACTUAL_VELOCITY_606C, 0x00, "actual velocity"},
{msgs::CIA402_ACTUAL_TORQUE_6077, 0x00, "actual torque"},
{msgs::CIA402_MODE_DISPLAY_6061, 0x00, "mode display"},
{msgs::CIA402_ERROR_CODE_603F, 0x00, "error code"},
};
for (const auto& entry : required) {
if (!bus_runtime_->hasPdoEntry(node_id, entry.index, entry.subindex)) {
CMVR_LOG(ERROR) << "[Cia402Protocol] missing PDO entry for node "
<< static_cast<int>(node_id)
<< ": " << entry.name
<< " 0x" << std::hex << entry.index
<< ":" << static_cast<int>(entry.subindex) << std::dec;
return false;
}
}
return true;
}
bool Cia402Protocol::readStatusword_(const std::uint8_t node_id,
std::uint16_t& statusword) const
{
@ -738,6 +730,36 @@ bool Cia402Protocol::readModeDisplay_(const std::uint8_t node_id,
mode_display);
}
bool Cia402Protocol::refreshMode_(const std::uint8_t node_id, NodeState& state) const
{
std::int8_t mode_display = 0;
if (!readModeDisplay_(node_id, mode_display)) {
return false;
}
state.mode = fromCia402Mode_(mode_display);
return true;
}
bool Cia402Protocol::readProfileAcceleration_(
const std::uint8_t node_id,
NodeState& state) const
{
std::uint32_t acceleration = 0;
std::uint32_t deceleration = 0;
if (!bus_runtime_ ||
!bus_runtime_->readSdo<std::uint32_t>(
node_id, msgs::CIA402_PROFILE_ACCELERATION_6083, 0x00, acceleration) ||
!bus_runtime_->readSdo<std::uint32_t>(
node_id, msgs::CIA402_PROFILE_DECELERATION_6084, 0x00, deceleration) ||
acceleration > static_cast<std::uint32_t>(std::numeric_limits<std::int32_t>::max()) ||
deceleration > static_cast<std::uint32_t>(std::numeric_limits<std::int32_t>::max())) {
return false;
}
state.profile_acceleration = static_cast<std::int32_t>(acceleration);
state.profile_deceleration = static_cast<std::int32_t>(deceleration);
return true;
}
bool Cia402Protocol::writeControlword_(const std::uint8_t node_id,
const cia402::Controlword controlword)
{
@ -858,59 +880,6 @@ bool Cia402Protocol::waitVelocityNearZero_(const std::uint8_t node_id,
return false;
}
bool Cia402Protocol::writePositionLimitsToDictionary_(
const std::uint8_t node_id,
const NodeState& state) const
{
if (!bus_runtime_) {
return false;
}
if (!std::isfinite(state.limit_q_lb) || !std::isfinite(state.limit_q_ub) ||
state.limit_q_ub <= state.limit_q_lb) {
return true;
}
const auto lower_limit = radToCounts_(state.limit_q_lb, state);
const auto upper_limit = radToCounts_(state.limit_q_ub, state);
const bool ok =
bus_runtime_->writeSdo<std::int32_t>(node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D,
0x01, lower_limit) &&
bus_runtime_->writeSdo<std::int32_t>(node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D,
0x02, upper_limit);
if (!ok) {
CMVR_LOG(ERROR) << "[Cia402Protocol] failed to write software position "
<< "limits to dictionary, node=" << static_cast<int>(node_id)
<< ", lower=" << lower_limit
<< ", upper=" << upper_limit;
}
return ok;
}
bool Cia402Protocol::writeVelocityLimitToDictionary_(
const std::uint8_t node_id,
const NodeState& state) const
{
if (!bus_runtime_) {
return false;
}
if (!std::isfinite(state.limit_qd) || state.limit_qd <= 0.0) {
return true;
}
const auto velocity_limit =
static_cast<std::uint32_t>(std::abs(radPerSecToCounts_(state.limit_qd, state)));
const bool ok =
bus_runtime_->writeSdo<std::uint32_t>(node_id, msgs::CIA402_MAX_PROFILE_VELOCITY_607F,
0x00, velocity_limit);
if (!ok) {
CMVR_LOG(ERROR) << "[Cia402Protocol] failed to write velocity limit "
<< "to dictionary, node=" << static_cast<int>(node_id)
<< ", velocity_limit=" << velocity_limit;
}
return ok;
}
bool Cia402Protocol::writeAccelerationLimitsToDictionary_(
const std::uint8_t node_id,
const NodeState& state) const
@ -944,13 +913,16 @@ bool Cia402Protocol::writeProfilePositionTarget_(const std::uint8_t node_id,
return false;
}
if (state.profile_velocity <= 0 && state.limit_qd > 0.0) {
state.profile_velocity = std::abs(radPerSecToCounts_(state.limit_qd, state));
}
if (state.profile_acceleration <= 0 && state.limit_qdd > 0.0) {
const auto profile_acceleration = std::abs(radPerSec2ToCounts_(state.limit_qdd, state));
state.profile_acceleration = profile_acceleration;
state.profile_deceleration = profile_acceleration;
if (!bus_runtime_->writeSdo<std::uint32_t>(
node_id, msgs::CIA402_PROFILE_VELOCITY_6081, 0x00,
static_cast<std::uint32_t>(state.profile_velocity)) ||
!bus_runtime_->writeSdo<std::uint32_t>(
node_id, msgs::CIA402_PROFILE_ACCELERATION_6083, 0x00,
static_cast<std::uint32_t>(state.profile_acceleration)) ||
!bus_runtime_->writeSdo<std::uint32_t>(
node_id, msgs::CIA402_PROFILE_DECELERATION_6084, 0x00,
static_cast<std::uint32_t>(state.profile_deceleration))) {
return false;
}
if (!writeTargetsForMode_(node_id, state.mode, state)) {
@ -1000,6 +972,7 @@ bool Cia402Protocol::prepareSafeTargetsForMode_(const std::uint8_t node_id,
case msgs::RUN_MODE_PROFILE_VELOCITY:
case msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY:
case msgs::RUN_MODE_TORQUE:
case msgs::RUN_MODE_CYCLIC_SYNC_CURRENT:
case msgs::RUN_MODE_HOMING:
case msgs::RUN_MODE_UNSPECIFIED:
@ -1007,6 +980,15 @@ bool Cia402Protocol::prepareSafeTargetsForMode_(const std::uint8_t node_id,
break;
}
// Clear the previous feedforward before publishing a different mode.
if (state.mode != mode &&
(!bus_runtime_ || !bus_runtime_->writePdo<std::int32_t>(
node_id, velocity_feedforward_, 0x00, 0))) {
CMVR_LOG(ERROR) << "[Cia402Protocol] failed to clear velocity feedforward"
<< " before switching mode, node=" << static_cast<int>(node_id);
return false;
}
return true;
}
@ -1054,27 +1036,6 @@ bool Cia402Protocol::appendTargetWritesForMode_(
0x00, state.target_position))) {
return false;
}
if (bus_runtime_->hasPdoEntry(node_id, msgs::CIA402_PROFILE_VELOCITY_6081, 0x00)) {
if (!append(EthercatMotorBusRuntime::makePdoWrite<std::int32_t>(
node_id, msgs::CIA402_PROFILE_VELOCITY_6081,
0x00, state.profile_velocity))) {
return false;
}
}
if (bus_runtime_->hasPdoEntry(node_id, msgs::CIA402_PROFILE_ACCELERATION_6083, 0x00)) {
if (!append(EthercatMotorBusRuntime::makePdoWrite<std::int32_t>(
node_id, msgs::CIA402_PROFILE_ACCELERATION_6083,
0x00, state.profile_acceleration))) {
return false;
}
}
if (bus_runtime_->hasPdoEntry(node_id, msgs::CIA402_PROFILE_DECELERATION_6084, 0x00)) {
if (!append(EthercatMotorBusRuntime::makePdoWrite<std::int32_t>(
node_id, msgs::CIA402_PROFILE_DECELERATION_6084,
0x00, state.profile_deceleration))) {
return false;
}
}
break;
case msgs::RUN_MODE_PROFILE_VELOCITY:
@ -1083,20 +1044,6 @@ bool Cia402Protocol::appendTargetWritesForMode_(
0x00, state.target_velocity))) {
return false;
}
if (bus_runtime_->hasPdoEntry(node_id, msgs::CIA402_PROFILE_ACCELERATION_6083, 0x00)) {
if (!append(EthercatMotorBusRuntime::makePdoWrite<std::int32_t>(
node_id, msgs::CIA402_PROFILE_ACCELERATION_6083,
0x00, state.profile_acceleration))) {
return false;
}
}
if (bus_runtime_->hasPdoEntry(node_id, msgs::CIA402_PROFILE_DECELERATION_6084, 0x00)) {
if (!append(EthercatMotorBusRuntime::makePdoWrite<std::int32_t>(
node_id, msgs::CIA402_PROFILE_DECELERATION_6084,
0x00, state.profile_deceleration))) {
return false;
}
}
break;
case msgs::RUN_MODE_CYCLIC_SYNC_POSITION:
@ -1104,7 +1051,7 @@ bool Cia402Protocol::appendTargetWritesForMode_(
node_id, msgs::CIA402_TARGET_POSITION_607A,
0x00, state.target_position)) ||
!append(EthercatMotorBusRuntime::makePdoWrite<std::int32_t>(
node_id, msgs::CIA402_TARGET_VELOCITY_60FF,
node_id, velocity_feedforward_,
0x00, state.target_velocity))) {
return false;
}
@ -1118,6 +1065,7 @@ bool Cia402Protocol::appendTargetWritesForMode_(
}
break;
case msgs::RUN_MODE_TORQUE:
case msgs::RUN_MODE_CYCLIC_SYNC_CURRENT:
if (!append(EthercatMotorBusRuntime::makePdoWrite<std::int16_t>(
node_id, msgs::CIA402_TARGET_TORQUE_6071,
@ -1129,38 +1077,8 @@ bool Cia402Protocol::appendTargetWritesForMode_(
default:
break;
}
return true;
}
bool Cia402Protocol::writeNode_(const std::uint8_t node_id, NodeState& state)
{
if (!bus_runtime_) {
return false;
}
std::uint16_t statusword = 0;
if (readStatusword_(node_id, statusword)) {
const auto status = cia402::statusword(statusword);
state.controlword = nextControlword_(status);
std::int32_t actual_position = 0;
if (!isOperationEnabled_(status) &&
readActualPosition_(node_id, actual_position) &&
actual_position != 0) {
state.target_position = actual_position;
}
}
std::array<EthercatMotorBusRuntime::PdoWrite, 6> writes{};
std::size_t count = 0;
writes[count++] = EthercatMotorBusRuntime::makePdoWrite<std::uint16_t>(
node_id, msgs::CIA402_CONTROL_WORD_6040, 0x00, state.controlword.value);
writes[count++] = EthercatMotorBusRuntime::makePdoWrite<std::int8_t>(
node_id, msgs::CIA402_OPERATION_MODE_6060, 0x00, toCia402Mode_(state.mode));
if (!appendTargetWritesForMode_(node_id, state.mode, state,
writes.data(), writes.size(), count)) {
return false;
}
return bus_runtime_->writePdosAtomic(writes.data(), count);
}
} // namespace cmvr::device

View File

@ -34,38 +34,22 @@ void Cia402StatusMonitor::addNode(const std::uint8_t node_id)
std::lock_guard<std::mutex> lock(states_mutex_);
states_.try_emplace(node_id);
}
monitorNode_(node_id, false);
monitorNode_(node_id);
}
void Cia402StatusMonitor::setExpectedOperationEnabled(
bool Cia402StatusMonitor::isNodeOperational(
const std::uint8_t node_id,
const bool expected)
const std::int8_t expected_mode) const
{
{
std::lock_guard<std::mutex> lock(states_mutex_);
states_[node_id].expected_operation_enabled = expected;
}
monitorNode_(node_id, expected);
}
bool Cia402StatusMonitor::isNodeOperational(const std::uint8_t node_id) const
{
if (!bus_runtime_ || !bus_runtime_->isHealthy()) {
return false;
}
std::lock_guard<std::mutex> lock(states_mutex_);
const auto it = states_.find(node_id);
return it != states_.end() && it->second.has_last_sample &&
it->second.last_sample.read_ok &&
it->second.last_sample.transport_healthy &&
it->second.last_sample.operation_enabled &&
!it->second.last_sample.command_blocked;
StatusSample sample;
return readStatusSample_(node_id, sample) && sample.operation_enabled &&
!sample.command_blocked && sample.mode_display == expected_mode;
}
void Cia402StatusMonitor::monitorLoop_()
{
while (running_.load()) {
std::array<std::pair<std::uint8_t, bool>, 256> nodes{};
std::array<std::uint8_t, 256> nodes{};
std::size_t node_count = 0;
{
std::lock_guard<std::mutex> lock(states_mutex_);
@ -73,23 +57,21 @@ void Cia402StatusMonitor::monitorLoop_()
if (node_count >= nodes.size()) {
break;
}
nodes[node_count++] = {node_id, state.expected_operation_enabled};
nodes[node_count++] = node_id;
}
}
for (std::size_t i = 0; i < node_count; ++i) {
monitorNode_(nodes[i].first, nodes[i].second);
monitorNode_(nodes[i]);
}
std::this_thread::sleep_for(poll_period_);
}
}
void Cia402StatusMonitor::monitorNode_(
const std::uint8_t node_id,
const bool expected_operation_enabled)
void Cia402StatusMonitor::monitorNode_(const std::uint8_t node_id)
{
std::lock_guard<std::mutex> monitor_lock(monitor_mutex_);
StatusSample current;
readStatusSample_(node_id, expected_operation_enabled, current);
readStatusSample_(node_id, current);
StatusSample previous;
bool had_previous = false;
@ -169,10 +151,6 @@ void Cia402StatusMonitor::reportStatuswordTransition_(
<< (status.warning != 0 ? ", warning" : "")
<< (status.internal_limit_active != 0
? ", internal limit active"
: "")
<< (current.expected_operation_enabled &&
!current.operation_enabled
? ", operation not enabled"
: "");
} else if (!current.status_problem && had_previous && previous.read_ok &&
previous.status_problem) {
@ -186,10 +164,8 @@ void Cia402StatusMonitor::reportStatuswordTransition_(
bool Cia402StatusMonitor::readStatusSample_(
const std::uint8_t node_id,
const bool expected_operation_enabled,
StatusSample& sample) const
{
sample.expected_operation_enabled = expected_operation_enabled;
sample.transport_healthy = bus_runtime_ && bus_runtime_->isHealthy();
if (!sample.transport_healthy) {
return false;
@ -224,11 +200,9 @@ bool Cia402StatusMonitor::readStatusSample_(
const auto status = cia402::statusword(sample.statusword);
sample.operation_enabled = cia402::isOperationEnabled(status);
sample.status_problem = status.fault != 0 || status.warning != 0 ||
status.internal_limit_active != 0 ||
(expected_operation_enabled && !sample.operation_enabled);
status.internal_limit_active != 0;
sample.command_blocked = status.fault != 0 || status.warning != 0 ||
sample.error_code != 0 ||
(expected_operation_enabled && !sample.operation_enabled);
sample.error_code != 0;
return true;
}

View File

@ -0,0 +1,260 @@
#include "devices/motor/drivers/ethercat_motor/include/ethercat_motor.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <functional>
#include <mutex>
#include <utility>
#include "common/base/logging/logger.h"
namespace cmvr::device {
EthercatMotor::EthercatMotor(const config::MotorConfigItem& config,
std::shared_ptr<Cia402Protocol> cia402_protocol)
: cia402_protocol_(std::move(cia402_protocol))
{
info_.id = config.id();
info_.joint_name = config.joint_name();
info_.limit_q_lb = config.limit_q_lb();
info_.limit_q_ub = config.limit_q_ub();
info_.limit_qd = config.limit_qd();
info_.limit_qdd = config.limit_qdd();
encoder_counts_per_rev_ = config.encoder_counts_per_rev();
gear_ratio_ = config.gear_ratio();
node_id_ = static_cast<std::uint8_t>(info_.id);
id_ = info_.joint_name;
protocol_ = cia402_protocol_;
}
bool EthercatMotor::commandCyclicPositionsAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
const std::vector<double>& positions,
const std::vector<double>& velocities)
{
if (motors.empty() || motors.size() != positions.size() ||
motors.size() != velocities.size() || motors.size() > 256) {
return false;
}
std::array<EthercatMotor*, 256> lock_order{};
thread_local std::vector<Cia402Protocol::CyclicPositionCommand> commands;
commands.reserve(256);
commands.resize(motors.size());
std::shared_ptr<Cia402Protocol> protocol;
for (std::size_t i = 0; i < motors.size(); ++i) {
const auto motor = std::dynamic_pointer_cast<EthercatMotor>(motors[i]);
if (!motor || !motor->hasDependencies_() || !motor->hasValidConversion_()) {
return false;
}
if (!protocol) {
protocol = motor->cia402_protocol_;
} else if (protocol.get() != motor->cia402_protocol_.get()) {
CMVR_LOG(ERROR) << "[EthercatMotor] batch target motors belong to different "
<< "CiA402 protocols";
return false;
}
for (std::size_t previous = 0; previous < i; ++previous) {
if (lock_order[previous] == motor.get()) {
return false;
}
}
lock_order[i] = motor.get();
commands[i] = Cia402Protocol::CyclicPositionCommand{
motor->node_id_, positions[i], velocities[i]};
}
std::sort(lock_order.begin(), lock_order.begin() + motors.size(),
std::less<EthercatMotor*>{});
std::array<std::unique_lock<std::mutex>, 256> locks{};
for (std::size_t i = 0; i < motors.size(); ++i) {
locks[i] = std::unique_lock<std::mutex>(lock_order[i]->mtx_);
}
return protocol && protocol->commandCyclicPositionsAtomic(commands);
}
bool EthercatMotor::commandCyclicVelocitiesAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
const std::vector<double>& velocities)
{
if (motors.empty() || motors.size() != velocities.size() || motors.size() > 256) {
return false;
}
std::array<EthercatMotor*, 256> lock_order{};
thread_local std::vector<Cia402Protocol::CyclicVelocityCommand> commands;
commands.reserve(256);
commands.resize(motors.size());
std::shared_ptr<Cia402Protocol> protocol;
for (std::size_t i = 0; i < motors.size(); ++i) {
const auto motor = std::dynamic_pointer_cast<EthercatMotor>(motors[i]);
if (!motor || !std::isfinite(velocities[i]) || !motor->hasDependencies_() ||
!motor->hasValidConversion_()) {
return false;
}
if (protocol && protocol != motor->cia402_protocol_) {
return false;
}
protocol = motor->cia402_protocol_;
for (std::size_t previous = 0; previous < i; ++previous) {
if (lock_order[previous] == motor.get()) {
return false;
}
}
lock_order[i] = motor.get();
commands[i] = {motor->node_id_, velocities[i]};
}
std::sort(lock_order.begin(), lock_order.begin() + motors.size(), std::less<EthercatMotor*>{});
std::array<std::unique_lock<std::mutex>, 256> locks{};
for (std::size_t i = 0; i < motors.size(); ++i) {
locks[i] = std::unique_lock<std::mutex>(lock_order[i]->mtx_);
}
return protocol->commandCyclicVelocitiesAtomic(commands);
}
bool EthercatMotor::commandCyclicTorquesAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
const std::vector<double>& torques)
{
if (motors.empty() || motors.size() != torques.size() || motors.size() > 256) {
return false;
}
std::array<EthercatMotor*, 256> lock_order{};
thread_local std::vector<Cia402Protocol::CyclicTorqueCommand> commands;
commands.reserve(256);
commands.resize(motors.size());
std::shared_ptr<Cia402Protocol> protocol;
for (std::size_t i = 0; i < motors.size(); ++i) {
const auto motor = std::dynamic_pointer_cast<EthercatMotor>(motors[i]);
if (!motor || !std::isfinite(torques[i]) || !motor->hasDependencies_() ||
!motor->hasValidConversion_()) {
return false;
}
if (protocol && protocol != motor->cia402_protocol_) {
return false;
}
protocol = motor->cia402_protocol_;
for (std::size_t previous = 0; previous < i; ++previous) {
if (lock_order[previous] == motor.get()) {
return false;
}
}
lock_order[i] = motor.get();
commands[i] = {motor->node_id_, torques[i]};
}
std::sort(lock_order.begin(), lock_order.begin() + motors.size(), std::less<EthercatMotor*>{});
std::array<std::unique_lock<std::mutex>, 256> locks{};
for (std::size_t i = 0; i < motors.size(); ++i) {
locks[i] = std::unique_lock<std::mutex>(lock_order[i]->mtx_);
}
return protocol->commandCyclicTorquesAtomic(commands);
}
bool EthercatMotor::readFeedbacksAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
std::vector<double>& positions,
std::vector<double>& velocities)
{
thread_local std::vector<double> torques;
torques.reserve(256);
return readFeedbacksAtomic(motors, positions, velocities, torques);
}
bool EthercatMotor::readFeedbacksAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
std::vector<double>& positions,
std::vector<double>& velocities,
std::vector<double>& torques)
{
if (motors.empty() || motors.size() > 256 || &positions == &velocities ||
&positions == &torques || &velocities == &torques) {
return false;
}
std::array<EthercatMotor*, 256> lock_order{};
thread_local std::vector<Cia402Protocol::MotorFeedback> feedbacks;
feedbacks.reserve(256);
feedbacks.resize(motors.size());
std::shared_ptr<Cia402Protocol> protocol;
for (std::size_t i = 0; i < motors.size(); ++i) {
const auto motor = std::dynamic_pointer_cast<EthercatMotor>(motors[i]);
if (!motor || !motor->hasDependencies_() || !motor->hasValidConversion_()) {
return false;
}
if (!protocol) {
protocol = motor->cia402_protocol_;
} else if (protocol.get() != motor->cia402_protocol_.get()) {
CMVR_LOG(ERROR) << "[EthercatMotor] batch feedback motors belong to different "
<< "CiA402 protocols";
return false;
}
for (std::size_t previous = 0; previous < i; ++previous) {
if (lock_order[previous] == motor.get()) {
return false;
}
}
lock_order[i] = motor.get();
feedbacks[i].node_id = motor->node_id_;
}
std::sort(lock_order.begin(), lock_order.begin() + motors.size(),
std::less<EthercatMotor*>{});
std::array<std::unique_lock<std::mutex>, 256> locks{};
for (std::size_t i = 0; i < motors.size(); ++i) {
locks[i] = std::unique_lock<std::mutex>(lock_order[i]->mtx_);
}
if (!protocol || !protocol->readFeedbacksAtomic(feedbacks)) {
return false;
}
positions.resize(motors.size());
velocities.resize(motors.size());
torques.resize(motors.size());
for (std::size_t i = 0; i < motors.size(); ++i) {
positions[i] = feedbacks[i].q;
velocities[i] = feedbacks[i].qd;
torques[i] = feedbacks[i].tau;
}
return true;
}
bool EthercatMotor::hasDependencies_() const
{
if (!cia402_protocol_) {
CMVR_LOG(ERROR) << "[EthercatMotor] missing CiA402 protocol: " << info_.joint_name;
return false;
}
if (cia402_protocol_->comm_proto != MotorProtocolInterface::CommProto::ETHERCAT) {
CMVR_LOG(ERROR) << "[EthercatMotor] invalid protocol for motor: " << info_.joint_name;
return false;
}
return true;
}
bool EthercatMotor::hasValidConversion_() const
{
if (encoder_counts_per_rev_ > 0.0 && gear_ratio_ > 0.0) {
return true;
}
CMVR_LOG(ERROR) << "[EthercatMotor] missing encoder conversion config: "
<< info_.joint_name
<< ", encoder_counts_per_rev=" << encoder_counts_per_rev_
<< ", gear_ratio=" << gear_ratio_;
return false;
}
std::int32_t EthercatMotor::radToCounts_(const double angle_rad) const
{
const double rev = angle_rad / (2.0 * M_PI);
return static_cast<std::int32_t>(
std::llround(rev * gear_ratio_ * encoder_counts_per_rev_));
}
std::uint32_t EthercatMotor::radPerSecToCounts_(const double velocity_rad_s) const
{
const double rev_per_sec = std::abs(velocity_rad_s) / (2.0 * M_PI);
return static_cast<std::uint32_t>(
std::llround(rev_per_sec * gear_ratio_ * encoder_counts_per_rev_));
}
} // namespace cmvr::device

View File

@ -1,10 +1,7 @@
#include "devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <functional>
#include <mutex>
#include <utility>
@ -15,20 +12,9 @@ namespace cmvr::device {
EyouMotor::EyouMotor(const config::MotorConfigItem& config,
std::shared_ptr<Cia402Protocol> cia402_protocol,
std::unique_ptr<EyouMotorAdapter> vendor_adapter)
: cia402_protocol_(std::move(cia402_protocol)),
: EthercatMotor(config, std::move(cia402_protocol)),
vendor_adapter_(std::move(vendor_adapter))
{
info_.id = config.id();
info_.joint_name = config.joint_name();
info_.limit_q_lb = config.limit_q_lb();
info_.limit_q_ub = config.limit_q_ub();
info_.limit_qd = config.limit_qd();
info_.limit_qdd = config.limit_qdd();
encoder_counts_per_rev_ = config.encoder_counts_per_rev();
gear_ratio_ = config.gear_ratio();
node_id_ = static_cast<std::uint8_t>(info_.id);
id_ = info_.joint_name;
protocol_ = cia402_protocol_;
}
bool EyouMotor::init()
@ -38,6 +24,7 @@ bool EyouMotor::init()
return false;
}
cia402_protocol_->setMotorConversion(node_id_, encoder_counts_per_rev_, gear_ratio_);
if (!cia402_protocol_->initNode(node_id_)) {
CMVR_LOG(ERROR) << "[EyouMotor] failed to init CiA402 node: " << info_.joint_name;
return false;
@ -46,9 +33,6 @@ bool EyouMotor::init()
CMVR_LOG(ERROR) << "[EyouMotor] failed to init vendor adapter: " << info_.joint_name;
return false;
}
cia402_protocol_->setMotorConversion(node_id_, encoder_counts_per_rev_, gear_ratio_);
cia402_protocol_->setLimitQd(node_id_, info_.limit_qd);
if (!writeVendorVelocityLimit_()) {
return false;
}
@ -61,26 +45,25 @@ bool EyouMotor::init()
return true;
}
void EyouMotor::setLimitQ(const double ub, const double lb)
bool EyouMotor::setLimitQ(const double ub, const double lb)
{
std::scoped_lock lock(mtx_);
info_.limit_q_ub = ub;
info_.limit_q_lb = lb;
if (!hasDependencies_() || !hasValidConversion_()) {
return;
return false;
}
writeVendorPositionLimits_();
return writeVendorPositionLimits_();
}
void EyouMotor::setLimitQd(const double qd)
bool EyouMotor::setLimitQd(const double qd)
{
std::scoped_lock lock(mtx_);
info_.limit_qd = qd;
if (!hasDependencies_() || !hasValidConversion_()) {
return;
return false;
}
cia402_protocol_->setLimitQd(node_id_, info_.limit_qd);
writeVendorVelocityLimit_();
return writeVendorVelocityLimit_();
}
bool EyouMotor::calibrateZeroQ()
@ -93,150 +76,8 @@ bool EyouMotor::calibrateZeroQ()
const auto counts_per_joint_revolution = static_cast<std::int64_t>(
std::llround(encoder_counts_per_rev_ * gear_ratio_));
std::int32_t zeroed_position = 0;
if (!vendor_adapter_->calibrateZero(node_id_, counts_per_joint_revolution,
zeroed_position)) {
CMVR_LOG(ERROR) << "[EyouMotor] zero calibration failed: " << info_.joint_name;
return false;
}
if (!cia402_protocol_->syncTargetToActualPosition(node_id_)) {
return false;
}
if (!writeVendorPositionLimits_()) {
return false;
}
return true;
}
bool EyouMotor::commandCyclicPositionsAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
const std::vector<double>& positions,
const std::vector<double>& velocities)
{
if (motors.empty() || motors.size() != positions.size() ||
motors.size() != velocities.size() || motors.size() > 256) {
return false;
}
std::array<EyouMotor*, 256> lock_order{};
std::array<Cia402Protocol::CyclicPositionCommand, 256> commands{};
std::shared_ptr<Cia402Protocol> protocol;
for (std::size_t i = 0; i < motors.size(); ++i) {
const auto motor = std::dynamic_pointer_cast<EyouMotor>(motors[i]);
if (!motor || !motor->hasDependencies_() || !motor->hasValidConversion_()) {
return false;
}
if (!protocol) {
protocol = motor->cia402_protocol_;
} else if (protocol.get() != motor->cia402_protocol_.get()) {
CMVR_LOG(ERROR) << "[EyouMotor] batch target motors belong to different "
<< "CiA402 protocols";
return false;
}
for (std::size_t previous = 0; previous < i; ++previous) {
if (lock_order[previous] == motor.get()) {
return false;
}
}
lock_order[i] = motor.get();
commands[i] = Cia402Protocol::CyclicPositionCommand{
motor->node_id_, positions[i], velocities[i]};
}
std::sort(lock_order.begin(), lock_order.begin() + motors.size(),
std::less<EyouMotor*>{});
std::array<std::unique_lock<std::mutex>, 256> locks{};
for (std::size_t i = 0; i < motors.size(); ++i) {
locks[i] = std::unique_lock<std::mutex>(lock_order[i]->mtx_);
}
return protocol && protocol->commandCyclicPositionsAtomic(commands.data(), motors.size());
}
bool EyouMotor::commandCyclicVelocitiesAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
const std::vector<double>& velocities)
{
if (motors.empty() || motors.size() != velocities.size() || motors.size() > 256) {
return false;
}
std::array<EyouMotor*, 256> lock_order{};
std::array<Cia402Protocol::CyclicVelocityCommand, 256> commands{};
std::shared_ptr<Cia402Protocol> protocol;
for (std::size_t i = 0; i < motors.size(); ++i) {
const auto motor = std::dynamic_pointer_cast<EyouMotor>(motors[i]);
if (!motor || !std::isfinite(velocities[i]) || !motor->hasDependencies_() ||
!motor->hasValidConversion_()) {
return false;
}
if (protocol && protocol != motor->cia402_protocol_) {
return false;
}
protocol = motor->cia402_protocol_;
for (std::size_t previous = 0; previous < i; ++previous) {
if (lock_order[previous] == motor.get()) {
return false;
}
}
lock_order[i] = motor.get();
commands[i] = {motor->node_id_, velocities[i]};
}
std::sort(lock_order.begin(), lock_order.begin() + motors.size(), std::less<EyouMotor*>{});
std::array<std::unique_lock<std::mutex>, 256> locks{};
for (std::size_t i = 0; i < motors.size(); ++i) {
locks[i] = std::unique_lock<std::mutex>(lock_order[i]->mtx_);
}
return protocol->commandCyclicVelocitiesAtomic(commands.data(), motors.size());
}
bool EyouMotor::readFeedbacksAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
std::vector<double>& positions,
std::vector<double>& velocities)
{
if (motors.empty() || motors.size() > 256) {
return false;
}
std::array<EyouMotor*, 256> lock_order{};
std::array<Cia402Protocol::MotorFeedback, 256> feedbacks{};
std::shared_ptr<Cia402Protocol> protocol;
for (std::size_t i = 0; i < motors.size(); ++i) {
const auto motor = std::dynamic_pointer_cast<EyouMotor>(motors[i]);
if (!motor || !motor->hasDependencies_() || !motor->hasValidConversion_()) {
return false;
}
if (!protocol) {
protocol = motor->cia402_protocol_;
} else if (protocol.get() != motor->cia402_protocol_.get()) {
CMVR_LOG(ERROR) << "[EyouMotor] batch feedback motors belong to different "
<< "CiA402 protocols";
return false;
}
for (std::size_t previous = 0; previous < i; ++previous) {
if (lock_order[previous] == motor.get()) {
return false;
}
}
lock_order[i] = motor.get();
feedbacks[i].node_id = motor->node_id_;
}
std::sort(lock_order.begin(), lock_order.begin() + motors.size(),
std::less<EyouMotor*>{});
std::array<std::unique_lock<std::mutex>, 256> locks{};
for (std::size_t i = 0; i < motors.size(); ++i) {
locks[i] = std::unique_lock<std::mutex>(lock_order[i]->mtx_);
}
if (!protocol || !protocol->readFeedbacksAtomic(feedbacks.data(), motors.size())) {
return false;
}
positions.resize(motors.size());
velocities.resize(motors.size());
for (std::size_t i = 0; i < motors.size(); ++i) {
positions[i] = feedbacks[i].q;
velocities[i] = feedbacks[i].qd;
}
return true;
return vendor_adapter_->calibrateZero(
node_id_, counts_per_joint_revolution, zeroed_position);
}
bool EyouMotor::brakeRelease()
@ -250,28 +91,11 @@ bool EyouMotor::brakeRelease()
bool EyouMotor::hasDependencies_() const
{
if (!cia402_protocol_ || !vendor_adapter_) {
CMVR_LOG(ERROR) << "[EyouMotor] missing protocol or vendor adapter: "
<< info_.joint_name;
if (!vendor_adapter_) {
CMVR_LOG(ERROR) << "[EyouMotor] missing vendor adapter: " << info_.joint_name;
return false;
}
if (cia402_protocol_->comm_proto != MotorProtocolInterface::CommProto::ETHERCAT) {
CMVR_LOG(ERROR) << "[EyouMotor] invalid protocol for motor: " << info_.joint_name;
return false;
}
return true;
}
bool EyouMotor::hasValidConversion_() const
{
if (encoder_counts_per_rev_ > 0.0 && gear_ratio_ > 0.0) {
return true;
}
CMVR_LOG(ERROR) << "[EyouMotor] missing encoder conversion config: "
<< info_.joint_name
<< ", encoder_counts_per_rev=" << encoder_counts_per_rev_
<< ", gear_ratio=" << gear_ratio_;
return false;
return EthercatMotor::hasDependencies_();
}
bool EyouMotor::writeVendorPositionLimits_() const
@ -281,7 +105,6 @@ bool EyouMotor::writeVendorPositionLimits_() const
return true;
}
cia402_protocol_->setLimitQ(node_id_, info_.limit_q_ub, info_.limit_q_lb);
return vendor_adapter_->writePositionLimits(node_id_,
radToCounts_(info_.limit_q_lb),
radToCounts_(info_.limit_q_ub));
@ -296,18 +119,4 @@ bool EyouMotor::writeVendorVelocityLimit_() const
return vendor_adapter_->writeVelocityLimit(node_id_, radPerSecToCounts_(info_.limit_qd));
}
std::int32_t EyouMotor::radToCounts_(const double angle_rad) const
{
const double rev = angle_rad / (2.0 * M_PI);
return static_cast<std::int32_t>(
std::llround(rev * gear_ratio_ * encoder_counts_per_rev_));
}
std::uint32_t EyouMotor::radPerSecToCounts_(const double velocity_rad_s) const
{
const double rev_per_sec = std::abs(velocity_rad_s) / (2.0 * M_PI);
return static_cast<std::uint32_t>(
std::llround(rev_per_sec * gear_ratio_ * encoder_counts_per_rev_));
}
} // namespace cmvr::device

View File

@ -1,5 +1,6 @@
#include "devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor_adapter.h"
#include <array>
#include <chrono>
#include <cmath>
#include <cstdlib>
@ -33,20 +34,22 @@ bool EyouMotorAdapter::writePositionLimits(const std::uint8_t node_id,
return false;
}
const auto write_limits = [&]() {
return bus_runtime_->writeSdo<std::uint32_t>(node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003,
0x00, 0) &&
bus_runtime_->writeSdo<std::int32_t>(
node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D,
0x02, upper_limit) &&
bus_runtime_->writeSdo<std::int32_t>(
node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D,
0x01, lower_limit) &&
bus_runtime_->writeSdo<std::uint32_t>(
node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003,
0x00, 0x4C494D54);
};
const auto readback_matches = [&]() {
std::uint32_t original_state = 0;
std::int32_t original_lower = 0;
std::int32_t original_upper = 0;
if (!bus_runtime_->readSdo<std::uint32_t>(
node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003, 0x00, original_state) ||
!bus_runtime_->readSdo<std::int32_t>(
node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, 0x01, original_lower) ||
!bus_runtime_->readSdo<std::int32_t>(
node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, 0x02, original_upper)) {
CMVR_LOG(ERROR) << "[EyouMotorAdapter] failed to snapshot software position limits, node="
<< static_cast<int>(node_id);
return false;
}
const auto readback_matches = [&](const std::int32_t lower,
const std::int32_t upper) {
std::int32_t actual_lower = 0;
std::int32_t actual_upper = 0;
return bus_runtime_->readSdo<std::int32_t>(
@ -55,17 +58,47 @@ bool EyouMotorAdapter::writePositionLimits(const std::uint8_t node_id,
bus_runtime_->readSdo<std::int32_t>(
node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D,
0x02, actual_upper) &&
actual_lower == lower_limit &&
actual_upper == upper_limit;
actual_lower == lower && actual_upper == upper;
};
const bool ok = write_limits() && readback_matches();
std::uint32_t actual_state = 0;
const bool ok =
bus_runtime_->writeSdo<std::uint32_t>(
node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003, 0x00, 0) &&
bus_runtime_->writeSdo<std::int32_t>(
node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, 0x02, upper_limit) &&
bus_runtime_->writeSdo<std::int32_t>(
node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, 0x01, lower_limit) &&
readback_matches(lower_limit, upper_limit) &&
bus_runtime_->writeSdo<std::uint32_t>(
node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003, 0x00, 0x4C494D54) &&
bus_runtime_->readSdo<std::uint32_t>(
node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003, 0x00, actual_state) &&
actual_state == 0x4C494D54;
if (!ok) {
const bool disabled = bus_runtime_->writeSdo<std::uint32_t>(
node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003, 0x00, 0);
const bool upper_restored = disabled && bus_runtime_->writeSdo<std::int32_t>(
node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, 0x02, original_upper);
const bool lower_restored = disabled && bus_runtime_->writeSdo<std::int32_t>(
node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, 0x01, original_lower);
const bool limits_restored = upper_restored && lower_restored &&
readback_matches(original_lower, original_upper);
// Restore the enable state even if restoring either bound failed.
const bool state_restored = bus_runtime_->writeSdo<std::uint32_t>(
node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003, 0x00, original_state) &&
bus_runtime_->readSdo<std::uint32_t>(
node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003, 0x00, actual_state) &&
actual_state == original_state;
CMVR_LOG(ERROR) << "[EyouMotorAdapter] failed to write software position "
<< "limits, node=" << static_cast<int>(node_id)
<< ", soft_limit_state=" << 0x4C494D54
<< ", lower=" << lower_limit
<< ", upper=" << upper_limit;
<< ", upper=" << upper_limit
<< ", original_limits_restored=" << limits_restored
<< ", original_enable_state_restored=" << state_restored;
} else {
position_limits_.emplace(lower_limit, upper_limit);
}
return ok;
}
@ -77,20 +110,25 @@ bool EyouMotorAdapter::writeVelocityLimit(const std::uint8_t node_id,
return false;
}
std::uint32_t actual_velocity_limit = 0;
const bool ok =
bus_runtime_->writeSdo<std::uint32_t>(node_id, eyou::EYOU_OVER_SPEED_THRESHOLD_2024,
0x00, velocity_limit) &&
bus_runtime_->readSdo<std::uint32_t>(node_id, eyou::EYOU_OVER_SPEED_THRESHOLD_2024,
0x00, actual_velocity_limit) &&
actual_velocity_limit == velocity_limit;
if (!ok) {
CMVR_LOG(ERROR) << "[EyouMotorAdapter] failed to write over speed "
<< "threshold, node=" << static_cast<int>(node_id)
<< ", expected=" << velocity_limit
<< ", actual=" << actual_velocity_limit;
const std::uint16_t entries[] = {
msgs::CIA402_MAX_PROFILE_VELOCITY_607F,
msgs::CIA402_PROFILE_VELOCITY_6081,
eyou::EYOU_OVER_SPEED_THRESHOLD_2024,
};
for (const auto index : entries) {
std::uint32_t actual_velocity_limit = 0;
if (!bus_runtime_->writeSdo<std::uint32_t>(node_id, index, 0x00, velocity_limit) ||
!bus_runtime_->readSdo<std::uint32_t>(node_id, index, 0x00, actual_velocity_limit) ||
actual_velocity_limit != velocity_limit) {
CMVR_LOG(ERROR) << "[EyouMotorAdapter] failed to write velocity limit, node="
<< static_cast<int>(node_id)
<< ", index=0x" << std::hex << index << std::dec
<< ", expected=" << velocity_limit
<< ", actual=" << actual_velocity_limit;
return false;
}
}
return ok;
return true;
}
bool EyouMotorAdapter::calibrateZero(const std::uint8_t node_id,
@ -250,9 +288,10 @@ bool EyouMotorAdapter::calibrateZero(const std::uint8_t node_id,
parameters_saved &&
wait_for_position("rollback_save_home_offset", original_home_offset,
original_position, restored_position);
const bool target_synced = syncTargetToActualPosition_(node_id, restored_position);
const bool soft_limit_restored = restore_soft_limit();
const bool rollback_ok = clear_applied && offset_applied &&
saved_state_confirmed && soft_limit_restored;
saved_state_confirmed && target_synced && soft_limit_restored;
CMVR_LOG(ERROR) << "[EyouMotorAdapter] calibration failed and original state was "
<< (rollback_ok ? "restored" : "not fully restored")
<< ", node=" << static_cast<int>(node_id)
@ -262,6 +301,7 @@ bool EyouMotorAdapter::calibrateZero(const std::uint8_t node_id,
<< ", clear_applied=" << clear_applied
<< ", offset_applied=" << offset_applied
<< ", saved_state_confirmed=" << saved_state_confirmed
<< ", target_synced=" << target_synced
<< ", soft_limit_restored=" << soft_limit_restored;
return false;
};
@ -323,7 +363,14 @@ bool EyouMotorAdapter::calibrateZero(const std::uint8_t node_id,
return rollback("wait_for_zero_after_save");
}
if (!restore_soft_limit()) {
if (!syncTargetToActualPosition_(node_id, zeroed_position)) {
return rollback("sync_target_position");
}
const bool limits_restored = position_limits_
? writePositionLimits(node_id, position_limits_->first, position_limits_->second)
: restore_soft_limit();
if (!limits_restored) {
CMVR_LOG(ERROR) << "[EyouMotorAdapter] failed to restore software position "
<< "limit after home offset calibration, node="
<< static_cast<int>(node_id)
@ -341,6 +388,39 @@ bool EyouMotorAdapter::calibrateZero(const std::uint8_t node_id,
return true;
}
bool EyouMotorAdapter::syncTargetToActualPosition_(
const std::uint8_t node_id,
std::int32_t& actual_position) const
{
if (!bus_runtime_->readSdo<std::int32_t>(
node_id, msgs::CIA402_ACTUAL_POSITION_6064, 0x00, actual_position)) {
CMVR_LOG(ERROR) << "[EyouMotorAdapter] failed to read position for target synchronization, node="
<< static_cast<int>(node_id);
return false;
}
std::array<EthercatMotorBusRuntime::PdoWrite, 4> writes{
EthercatMotorBusRuntime::makePdoWrite<std::int32_t>(
node_id, msgs::CIA402_TARGET_POSITION_607A, 0x00, actual_position),
EthercatMotorBusRuntime::makePdoWrite<std::int32_t>(
node_id, msgs::CIA402_TARGET_VELOCITY_60FF, 0x00, 0),
EthercatMotorBusRuntime::makePdoWrite<std::int16_t>(
node_id, msgs::CIA402_TARGET_TORQUE_6071, 0x00, 0),
};
std::size_t count = 3;
const auto velocity_feedforward = bus_runtime_->pdoMapping().velocity_feedforward;
if (velocity_feedforward != 0 && velocity_feedforward != msgs::CIA402_TARGET_VELOCITY_60FF) {
writes[count++] = EthercatMotorBusRuntime::makePdoWrite<std::int32_t>(
node_id, velocity_feedforward, 0x00, 0);
}
if (!bus_runtime_->writePdosAtomic(writes.data(), count)) {
CMVR_LOG(ERROR) << "[EyouMotorAdapter] failed to synchronize target position, node="
<< static_cast<int>(node_id);
return false;
}
return true;
}
bool EyouMotorAdapter::brakeRelease(const std::uint8_t node_id)
{
if (!bus_runtime_) {

View File

@ -242,10 +242,10 @@ TEST(EyouMotorDeviceManagerRealTest, CommandFourCyclicPositionRaisedCosineTrajec
}
for (const auto& motor : motors) {
ASSERT_TRUE(motor->torqueOn());
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_POSITION));
}
for (const auto& motor : motors) {
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_POSITION));
ASSERT_TRUE(motor->torqueOn());
}
std::vector<double> center_q;

View File

@ -214,6 +214,7 @@ TEST(EyouMotorRealTest, ReadMotorStateOnly)
auto motor = createMotor(runtime);
ASSERT_NE(motor, nullptr);
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_PROFILE_POSITION));
ASSERT_TRUE(motor->torqueOn());
printMotorState("motor state", *motor);
printRawEthercatFeedback("raw feedback", runtime);
@ -237,8 +238,8 @@ TEST(EyouMotorRealTest, CalibrateZeroQPrintBeforeAndAfter)
printMotorState("before calibrateZeroQ", *motor);
ASSERT_TRUE(motor->calibrateZeroQ());
printMotorState("after calibrateZeroQ", *motor);
ASSERT_TRUE(motor->torqueOn());
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_PROFILE_POSITION));
ASSERT_TRUE(motor->torqueOn());
ASSERT_TRUE(motor->commandProfilePosition(1.5,0.8,3.0));
sampleMotorState(*motor, kFeedbackSampleDuration);
}
@ -252,8 +253,8 @@ TEST(EyouMotorRealTest, CommandProfilePosition)
auto motor = createMotor(runtime);
ASSERT_NE(motor, nullptr);
ASSERT_TRUE(motor->torqueOn());
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_PROFILE_POSITION));
ASSERT_TRUE(motor->torqueOn());
ASSERT_TRUE(motor->commandProfilePosition(-3.0, 0.5, 1.0));
sampleMotorState(*motor, kFeedbackSampleDuration);
@ -270,8 +271,8 @@ TEST(EyouMotorRealTest, CommandProfileVelocity)
ASSERT_TRUE(motor->torqueOn());
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_PROFILE_VELOCITY));
ASSERT_TRUE(motor->torqueOn());
std::cout << "motor.commandProfileVelocity(0.3 rad/s, 1.0 rad/s^2)" << std::endl;
ASSERT_TRUE(motor->commandProfileVelocity(0.3, 1.0));
@ -293,8 +294,8 @@ TEST(EyouMotorRealTest, CommandCyclicPosition)
ASSERT_TRUE(motor->torqueOff());
ASSERT_TRUE(motor->calibrateZeroQ());
ASSERT_TRUE(motor->torqueOn());
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_POSITION));
ASSERT_TRUE(motor->torqueOn());
const std::chrono::milliseconds trajectory_duration{12000};
const double period_s = 6.0;
@ -342,8 +343,8 @@ TEST(EyouMotorRealTest, CommandCyclicVelocity)
ASSERT_TRUE(motor->torqueOff());
ASSERT_TRUE(motor->calibrateZeroQ());
ASSERT_TRUE(motor->torqueOn());
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY));
ASSERT_TRUE(motor->torqueOn());
const std::chrono::milliseconds trajectory_duration{12000};
const double period_s = 5.0;
@ -395,8 +396,8 @@ TEST(EyouMotorRealTest, QuickStopAfterTwoSeconds)
ASSERT_TRUE(motor->torqueOff());
ASSERT_TRUE(motor->calibrateZeroQ());
ASSERT_TRUE(motor->torqueOn());
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY));
ASSERT_TRUE(motor->torqueOn());
const std::chrono::milliseconds run_duration{2000};
const double period_s = 6.0;
@ -450,8 +451,8 @@ TEST(EyouMotorRealTest, QuickStopInProfilePosition)
ASSERT_TRUE(motor->torqueOff());
ASSERT_TRUE(motor->calibrateZeroQ());
ASSERT_TRUE(motor->torqueOn());
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_PROFILE_POSITION));
ASSERT_TRUE(motor->torqueOn());
const std::chrono::milliseconds quick_stop_time{1000};
const double start_q = motor->getQ();
@ -489,8 +490,8 @@ TEST(EyouMotorRealTest, QuickStopInProfileVelocity)
ASSERT_TRUE(motor->torqueOff());
ASSERT_TRUE(motor->calibrateZeroQ());
ASSERT_TRUE(motor->torqueOn());
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_PROFILE_VELOCITY));
ASSERT_TRUE(motor->torqueOn());
const std::chrono::milliseconds quick_stop_time{2000};
const double target_qd = motor->getQ() > 0.0 ? -2.0 : 2.0;
@ -525,8 +526,8 @@ TEST(EyouMotorRealTest, QuickStopInCyclicPosition)
ASSERT_TRUE(motor->torqueOff());
ASSERT_TRUE(motor->calibrateZeroQ());
ASSERT_TRUE(motor->torqueOn());
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_POSITION));
ASSERT_TRUE(motor->torqueOn());
const std::chrono::milliseconds run_duration{2000};
const double start_q = motor->getQ();

View File

@ -0,0 +1,126 @@
#include "devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_motor.h"
#include <cmath>
#include <mutex>
#include <utility>
#include "common/base/logging/logger.h"
namespace cmvr::device {
TchlMotor::TchlMotor(const config::MotorConfigItem& config,
std::shared_ptr<Cia402Protocol> cia402_protocol,
std::unique_ptr<TchlMotorAdapter> vendor_adapter)
: EthercatMotor(config, std::move(cia402_protocol)),
vendor_adapter_(std::move(vendor_adapter))
{
}
bool TchlMotor::init()
{
std::scoped_lock lock(mtx_);
if (!hasDependencies_() || !hasValidConversion_()) {
return false;
}
if (!vendor_adapter_->initNode(node_id_)) {
return false;
}
cia402_protocol_->setMotorConversion(node_id_, encoder_counts_per_rev_, gear_ratio_);
if (!cia402_protocol_->initNode(node_id_)) {
CMVR_LOG(ERROR) << "[TchlMotor] failed to init CiA402 node: " << info_.joint_name;
return false;
}
if (!writeVendorVelocityLimit_() || !writeVendorPositionLimits_()) {
return false;
}
if (info_.limit_qdd > 0.0) {
cia402_protocol_->setLimitQdd(node_id_, info_.limit_qdd, -info_.limit_qdd);
}
return true;
}
bool TchlMotor::torqueOn()
{
std::scoped_lock lock(mtx_);
return hasDependencies_() && hasValidConversion_() &&
vendor_adapter_->torqueOn(node_id_, static_cast<std::int64_t>(
std::llround(encoder_counts_per_rev_ * gear_ratio_)));
}
bool TchlMotor::torqueOff()
{
std::scoped_lock lock(mtx_);
return hasDependencies_() && hasValidConversion_() &&
vendor_adapter_->torqueOff(node_id_, static_cast<std::int64_t>(
std::llround(encoder_counts_per_rev_ * gear_ratio_)));
}
bool TchlMotor::setLimitQ(const double ub, const double lb)
{
std::scoped_lock lock(mtx_);
info_.limit_q_ub = ub;
info_.limit_q_lb = lb;
if (!hasDependencies_() || !hasValidConversion_()) {
return false;
}
return writeVendorPositionLimits_();
}
bool TchlMotor::setLimitQd(const double qd)
{
std::scoped_lock lock(mtx_);
info_.limit_qd = qd;
if (!hasDependencies_() || !hasValidConversion_()) {
return false;
}
return writeVendorVelocityLimit_();
}
bool TchlMotor::calibrateZeroQ()
{
std::scoped_lock lock(mtx_);
if (!hasDependencies_() || !hasValidConversion_()) {
return false;
}
const auto counts_per_joint_revolution = static_cast<std::int64_t>(
std::llround(encoder_counts_per_rev_ * gear_ratio_));
std::int32_t zeroed_position = 0;
return vendor_adapter_->calibrateZero(
node_id_, counts_per_joint_revolution, zeroed_position);
}
bool TchlMotor::brakeRelease()
{
std::scoped_lock lock(mtx_);
return hasDependencies_() && vendor_adapter_->brakeRelease(node_id_);
}
bool TchlMotor::hasDependencies_() const
{
if (!vendor_adapter_) {
CMVR_LOG(ERROR) << "[TchlMotor] missing vendor adapter: " << info_.joint_name;
return false;
}
return EthercatMotor::hasDependencies_();
}
bool TchlMotor::writeVendorPositionLimits_() const
{
if (!std::isfinite(info_.limit_q_lb) || !std::isfinite(info_.limit_q_ub) ||
info_.limit_q_ub <= info_.limit_q_lb) {
return true;
}
return vendor_adapter_->writePositionLimits(node_id_,
radToCounts_(info_.limit_q_lb),
radToCounts_(info_.limit_q_ub));
}
bool TchlMotor::writeVendorVelocityLimit_() const
{
if (!std::isfinite(info_.limit_qd) || info_.limit_qd <= 0.0) {
return true;
}
return vendor_adapter_->writeVelocityLimit(node_id_, radPerSecToCounts_(info_.limit_qd));
}
} // namespace cmvr::device

View File

@ -0,0 +1,500 @@
#include "devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_motor_adapter.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <thread>
#include <utility>
#include "cmvr/msgs/cia402.pb.h"
#include "common/base/logging/logger.h"
#include "devices/motor/drivers/ethercat_motor/include/cia402/cia402_objects.h"
namespace cmvr::device {
namespace {
constexpr std::uint16_t kEnableCommandDelay = 0x3136;
constexpr std::uint16_t kDisableDelay = 0x3137;
constexpr std::uint16_t kSoftLimitEnable = 0x3809;
constexpr std::uint16_t kForceBrakeRelease = 0x381E;
constexpr std::uint16_t kMaximumDelayMs = 500;
constexpr std::uint16_t kFixedEnableDelayMs = 200;
constexpr std::uint16_t kBrakeReleaseCommand = 128;
constexpr std::uint16_t kHomingMethod = 0x6098;
constexpr std::int8_t kHomingMode = 6;
constexpr std::uint16_t kStartHoming = 0x001F;
constexpr std::uint16_t kHomingAttained = 1U << 12U;
constexpr std::uint16_t kHomingError = 1U << 13U;
} // namespace
TchlMotorAdapter::TchlMotorAdapter(
std::shared_ptr<EthercatMotorBusRuntime> bus_runtime)
: bus_runtime_(std::move(bus_runtime))
{
}
bool TchlMotorAdapter::initNode(const std::uint8_t node_id)
{
if (!bus_runtime_ || !bus_runtime_->hasMotor(node_id)) {
CMVR_LOG(ERROR) << "[TchlMotorAdapter] missing EtherCAT motor, node="
<< static_cast<int>(node_id);
return false;
}
std::uint16_t enable_command_delay_ms = 0;
std::uint16_t disable_delay_ms = 0;
if (!bus_runtime_->readSdo<std::uint16_t>(
node_id, kEnableCommandDelay, 0x00, enable_command_delay_ms) ||
!bus_runtime_->readSdo<std::uint16_t>(
node_id, kDisableDelay, 0x00, disable_delay_ms) ||
enable_command_delay_ms > kMaximumDelayMs ||
disable_delay_ms > kMaximumDelayMs) {
CMVR_LOG(ERROR) << "[TchlMotorAdapter] failed to read valid enable/disable "
<< "delays (Pr1.54/Pr1.55 must be in [0, 500] ms), node="
<< static_cast<int>(node_id)
<< ", enable_command_delay_ms=" << enable_command_delay_ms
<< ", disable_delay_ms=" << disable_delay_ms;
return false;
}
// PrF.44 is a fixed 200 ms delay; the ESI does not expose an SDO for it.
enable_delay_ = std::chrono::milliseconds{
kFixedEnableDelayMs + enable_command_delay_ms};
disable_delay_ = std::chrono::milliseconds{disable_delay_ms};
return true;
}
bool TchlMotorAdapter::writePositionLimits(const std::uint8_t node_id,
const std::int32_t lower_limit,
const std::int32_t upper_limit)
{
if (!bus_runtime_ || lower_limit >= upper_limit) {
return false;
}
std::int32_t actual_lower = 0;
std::int32_t actual_upper = 0;
std::uint16_t soft_limit_enabled = 0;
const bool ok =
bus_runtime_->writeSdo<std::int32_t>(
node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D,
0x01, lower_limit) &&
bus_runtime_->writeSdo<std::int32_t>(
node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D,
0x02, upper_limit) &&
bus_runtime_->writeSdo<std::uint16_t>(
node_id, kSoftLimitEnable, 0x00, 1) &&
bus_runtime_->readSdo<std::int32_t>(
node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D,
0x01, actual_lower) &&
bus_runtime_->readSdo<std::int32_t>(
node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D,
0x02, actual_upper) &&
bus_runtime_->readSdo<std::uint16_t>(
node_id, kSoftLimitEnable, 0x00, soft_limit_enabled) &&
actual_lower == lower_limit && actual_upper == upper_limit &&
soft_limit_enabled == 1;
if (!ok) {
CMVR_LOG(ERROR) << "[TchlMotorAdapter] failed to write and verify software "
<< "position limits, node=" << static_cast<int>(node_id)
<< ", expected_lower=" << lower_limit
<< ", actual_lower=" << actual_lower
<< ", expected_upper=" << upper_limit
<< ", actual_upper=" << actual_upper
<< ", soft_limit_enabled=" << soft_limit_enabled;
} else {
lower_position_limit_ = lower_limit;
upper_position_limit_ = upper_limit;
has_position_limits_ = true;
}
return ok;
}
bool TchlMotorAdapter::writeVelocityLimit(const std::uint8_t node_id,
const std::uint32_t velocity_limit)
{
if (!bus_runtime_ || velocity_limit == 0) {
return false;
}
std::uint32_t actual_velocity_limit = 0;
std::uint32_t actual_profile_velocity = 0;
const bool ok = bus_runtime_->writeSdo<std::uint32_t>(
node_id, msgs::CIA402_MAX_PROFILE_VELOCITY_607F,
0x00, velocity_limit) &&
bus_runtime_->writeSdo<std::uint32_t>(
node_id, msgs::CIA402_PROFILE_VELOCITY_6081,
0x00, velocity_limit) &&
bus_runtime_->readSdo<std::uint32_t>(
node_id, msgs::CIA402_MAX_PROFILE_VELOCITY_607F,
0x00, actual_velocity_limit) &&
bus_runtime_->readSdo<std::uint32_t>(
node_id, msgs::CIA402_PROFILE_VELOCITY_6081,
0x00, actual_profile_velocity) &&
actual_velocity_limit == velocity_limit &&
actual_profile_velocity == velocity_limit;
if (!ok) {
CMVR_LOG(ERROR) << "[TchlMotorAdapter] failed to verify maximum profile "
<< "velocity, node=" << static_cast<int>(node_id)
<< ", expected=" << velocity_limit
<< ", actual=" << actual_velocity_limit
<< ", profile_velocity=" << actual_profile_velocity;
}
return ok;
}
bool TchlMotorAdapter::writeSafeTargets_(const std::uint8_t node_id) const
{
std::int32_t actual_position = 0;
if (!bus_runtime_->readPdo<std::int32_t>(
node_id, msgs::CIA402_ACTUAL_POSITION_6064, 0x00, actual_position)) {
return false;
}
const std::array writes{
EthercatMotorBusRuntime::makePdoWrite<std::int32_t>(
node_id, msgs::CIA402_TARGET_POSITION_607A, 0x00, actual_position),
EthercatMotorBusRuntime::makePdoWrite<std::int32_t>(
node_id, msgs::CIA402_TARGET_VELOCITY_60FF, 0x00, 0),
EthercatMotorBusRuntime::makePdoWrite<std::int16_t>(
node_id, msgs::CIA402_TARGET_TORQUE_6071, 0x00, 0),
EthercatMotorBusRuntime::makePdoWrite<std::int32_t>(
node_id, msgs::CIA402_VELOCITY_OFFSET_60B1, 0x00, 0),
};
return bus_runtime_->writePdosAtomic(writes.data(), writes.size());
}
bool TchlMotorAdapter::writeControlwordAndWait_(
const std::uint8_t node_id,
const std::uint16_t command,
const cia402::DeviceState expected_state,
const std::int8_t expected_mode) const
{
if (!bus_runtime_->writePdo<std::uint16_t>(
node_id, msgs::CIA402_CONTROL_WORD_6040, 0x00, command)) {
return false;
}
const auto& protocol_config = bus_runtime_->config().cia402();
const auto poll_period = std::chrono::milliseconds{
std::max<std::uint32_t>(1, protocol_config.status_poll_period_ms())};
const auto deadline = std::chrono::steady_clock::now() +
std::chrono::milliseconds{protocol_config.state_transition_timeout_ms()};
std::uint16_t last_statusword = 0;
do {
std::this_thread::sleep_for(poll_period);
std::int8_t mode = 0;
if (!bus_runtime_->isHealthy() ||
!bus_runtime_->readPdo<std::uint16_t>(
node_id, msgs::CIA402_STATUS_WORD_6041, 0x00, last_statusword) ||
cia402::statusword(last_statusword).fault) {
return false;
}
if (cia402::hasState(cia402::statusword(last_statusword), expected_state) &&
(expected_mode == 0 ||
(bus_runtime_->readPdo<std::int8_t>(
node_id, msgs::CIA402_MODE_DISPLAY_6061, 0x00, mode) &&
mode == expected_mode))) {
return true;
}
} while (std::chrono::steady_clock::now() < deadline);
CMVR_LOG(ERROR) << "[TchlMotorAdapter] state transition timed out, node="
<< static_cast<int>(node_id)
<< ", controlword=0x" << std::hex << command
<< ", statusword=0x" << last_statusword << std::dec;
return false;
}
bool TchlMotorAdapter::waitVelocityNearZero_(
const std::uint8_t node_id,
const std::int64_t counts_per_joint_revolution) const
{
const auto& protocol_config = bus_runtime_->config().cia402();
const double tolerance = std::max(
1.0, std::abs(protocol_config.stopped_velocity_tolerance_rad_s()) *
counts_per_joint_revolution / (2.0 * M_PI));
const auto poll_period = std::chrono::milliseconds{
std::max<std::uint32_t>(1, protocol_config.status_poll_period_ms())};
const auto deadline = std::chrono::steady_clock::now() +
std::chrono::milliseconds{protocol_config.velocity_stop_timeout_ms()};
std::int32_t velocity = 0;
do {
if (!bus_runtime_->isHealthy() ||
!bus_runtime_->readPdo<std::int32_t>(
node_id, msgs::CIA402_ACTUAL_VELOCITY_606C, 0x00, velocity)) {
return false;
}
if (std::abs(static_cast<double>(velocity)) <= tolerance) {
return true;
}
std::this_thread::sleep_for(poll_period);
} while (std::chrono::steady_clock::now() < deadline);
CMVR_LOG(ERROR) << "[TchlMotorAdapter] timeout waiting for stopped axis, node="
<< static_cast<int>(node_id) << ", velocity=" << velocity;
return false;
}
bool TchlMotorAdapter::torqueOn(
const std::uint8_t node_id,
const std::int64_t counts_per_joint_revolution)
{
if (!bus_runtime_ || !bus_runtime_->isHealthy() || counts_per_joint_revolution <= 0) {
return false;
}
const bool enabled = [&] {
std::int8_t mode = 0;
if (!bus_runtime_->readPdo<std::int8_t>(
node_id, msgs::CIA402_MODE_DISPLAY_6061, 0x00, mode)) {
return false;
}
switch (mode) {
case 1: // Profile position.
case 3: // Profile velocity.
case 4: // Profile torque.
case kHomingMode:
case 8: // Cyclic synchronous position.
case 9: // Cyclic synchronous velocity.
case 10: // Cyclic synchronous torque.
break;
default:
CMVR_LOG(ERROR) << "[TchlMotorAdapter] configure a supported mode before enabling, node="
<< static_cast<int>(node_id)
<< ", mode=" << static_cast<int>(mode);
return false;
}
std::uint16_t statusword = 0;
if (!bus_runtime_->readPdo<std::uint16_t>(
node_id, msgs::CIA402_STATUS_WORD_6041, 0x00, statusword)) {
return false;
}
if (cia402::statusword(statusword).fault) {
if (!bus_runtime_->writePdo<std::uint16_t>(
node_id, msgs::CIA402_CONTROL_WORD_6040, 0x00,
cia402::faultResetControlword().value)) {
return false;
}
std::this_thread::sleep_for(std::chrono::milliseconds{
std::max<std::uint32_t>(1, bus_runtime_->config().cia402().status_poll_period_ms())});
}
if (!writeSafeTargets_(node_id) ||
!writeControlwordAndWait_(node_id, cia402::shutdownControlword().value,
cia402::DeviceState::ReadyToSwitchOn) ||
!writeControlwordAndWait_(node_id, cia402::switchOnControlword().value,
cia402::DeviceState::SwitchedOn) ||
!writeControlwordAndWait_(node_id, cia402::enableOperationControlword().value,
cia402::DeviceState::OperationEnabled)) {
return false;
}
std::this_thread::sleep_for(enable_delay_);
return bus_runtime_->isHealthy() &&
bus_runtime_->readPdo<std::uint16_t>(
node_id, msgs::CIA402_STATUS_WORD_6041, 0x00, statusword) &&
cia402::isOperationEnabled(cia402::statusword(statusword)) &&
!cia402::statusword(statusword).fault;
}();
if (!enabled) {
torqueOff(node_id, counts_per_joint_revolution);
}
return enabled;
}
bool TchlMotorAdapter::torqueOff(
const std::uint8_t node_id,
const std::int64_t counts_per_joint_revolution)
{
if (!bus_runtime_ || counts_per_joint_revolution <= 0) {
return false;
}
const bool targets_written = writeSafeTargets_(node_id);
const bool stopped = targets_written &&
waitVelocityNearZero_(node_id, counts_per_joint_revolution);
// Even a stop timeout must end with a disable command.
bool disabled = false;
std::uint16_t statusword = 0;
if (bus_runtime_->readPdo<std::uint16_t>(
node_id, msgs::CIA402_STATUS_WORD_6041, 0x00, statusword)) {
const auto status = cia402::statusword(statusword);
if (cia402::isSwitchOnDisabled(status)) {
disabled = writeControlwordAndWait_(
node_id, 0, cia402::DeviceState::SwitchOnDisabled);
} else if (cia402::hasState(status, cia402::DeviceState::ReadyToSwitchOn)) {
disabled = writeControlwordAndWait_(
node_id, cia402::shutdownControlword().value, cia402::DeviceState::ReadyToSwitchOn);
} else if (cia402::isOperationEnabled(status)) {
const bool switched_on = writeControlwordAndWait_(
node_id, cia402::switchOnControlword().value, cia402::DeviceState::SwitchedOn);
const bool ready = writeControlwordAndWait_(
node_id, cia402::shutdownControlword().value, cia402::DeviceState::ReadyToSwitchOn);
disabled = switched_on && ready;
} else if (cia402::hasState(status, cia402::DeviceState::SwitchedOn)) {
disabled = writeControlwordAndWait_(
node_id, cia402::shutdownControlword().value, cia402::DeviceState::ReadyToSwitchOn);
} else {
disabled = writeControlwordAndWait_(
node_id, 0, cia402::DeviceState::SwitchOnDisabled);
}
}
if (!disabled) {
const bool voltage_disabled = writeControlwordAndWait_(
node_id, 0, cia402::DeviceState::SwitchOnDisabled);
// Failed transitions still fail the operation even if this fallback succeeds.
if (!voltage_disabled) {
bus_runtime_->writePdo<std::uint16_t>(
node_id, msgs::CIA402_CONTROL_WORD_6040, 0x00, 0);
}
}
std::this_thread::sleep_for(disable_delay_);
return targets_written && stopped && disabled;
}
bool TchlMotorAdapter::calibrateZero(
const std::uint8_t node_id,
const std::int64_t counts_per_joint_revolution,
std::int32_t& zeroed_position)
{
if (!bus_runtime_ || counts_per_joint_revolution <= 0) {
return false;
}
const bool calibrated = [&] {
if (!bus_runtime_->isHealthy() ||
!torqueOff(node_id, counts_per_joint_revolution)) {
return false;
}
std::int8_t method = 0;
std::int32_t offset = 0;
if (!bus_runtime_->writeSdo<std::int8_t>(node_id, kHomingMethod, 0x00, 35) ||
!bus_runtime_->readSdo<std::int8_t>(node_id, kHomingMethod, 0x00, method) || method != 35 ||
!bus_runtime_->writeSdo<std::int32_t>(
node_id, msgs::CIA402_HOME_OFFSET_607C, 0x00, 0) ||
!bus_runtime_->readSdo<std::int32_t>(
node_id, msgs::CIA402_HOME_OFFSET_607C, 0x00, offset) || offset != 0) {
CMVR_LOG(ERROR) << "[TchlMotorAdapter] failed to configure current-position zero calibration, node="
<< static_cast<int>(node_id);
return false;
}
if (!writeSafeTargets_(node_id) ||
!bus_runtime_->writePdo<std::int8_t>(
node_id, msgs::CIA402_OPERATION_MODE_6060, 0x00, kHomingMode) ||
!writeControlwordAndWait_(node_id, cia402::shutdownControlword().value,
cia402::DeviceState::ReadyToSwitchOn) ||
!writeControlwordAndWait_(node_id, cia402::switchOnControlword().value,
cia402::DeviceState::SwitchedOn, kHomingMode) ||
!writeControlwordAndWait_(node_id, cia402::enableOperationControlword().value,
cia402::DeviceState::OperationEnabled, kHomingMode)) {
return false;
}
std::this_thread::sleep_for(enable_delay_);
return bus_runtime_->isHealthy() &&
bus_runtime_->writePdo<std::uint16_t>(
node_id, msgs::CIA402_CONTROL_WORD_6040, 0x00, kStartHoming) &&
waitZeroCalibration_(node_id, zeroed_position);
}();
// Also clear the homing start bit and disable after any intermediate failure.
const bool disabled = torqueOff(node_id, counts_per_joint_revolution);
if (!calibrated || !disabled ||
!bus_runtime_->readPdo<std::int32_t>(
node_id, msgs::CIA402_ACTUAL_POSITION_6064, 0x00, zeroed_position) ||
!writeSafeTargets_(node_id)) {
return false;
}
return !has_position_limits_ ||
writePositionLimits(node_id, lower_position_limit_, upper_position_limit_);
}
bool TchlMotorAdapter::waitZeroCalibration_(const std::uint8_t node_id,
std::int32_t& zeroed_position) const
{
const auto& zero_config = bus_runtime_->config().zero_calibration();
const auto timeout = std::chrono::milliseconds{
zero_config.timeout_ms() > 0 ? zero_config.timeout_ms() : 2000};
const auto poll_period = std::chrono::milliseconds{
zero_config.poll_period_ms() > 0 ? zero_config.poll_period_ms() : 10};
const std::int64_t tolerance = zero_config.position_tolerance_counts() > 0
? zero_config.position_tolerance_counts() : 100;
const auto deadline = std::chrono::steady_clock::now() + timeout;
bool start_received = false;
std::uint16_t last_statusword = 0;
std::array reads{
EthercatMotorBusRuntime::makePdoRead<std::uint16_t>(
node_id, msgs::CIA402_STATUS_WORD_6041, 0x00),
EthercatMotorBusRuntime::makePdoRead<std::int8_t>(
node_id, msgs::CIA402_MODE_DISPLAY_6061, 0x00),
EthercatMotorBusRuntime::makePdoRead<std::int32_t>(
node_id, msgs::CIA402_ACTUAL_POSITION_6064, 0x00),
EthercatMotorBusRuntime::makePdoRead<std::uint16_t>(
node_id, msgs::CIA402_ERROR_CODE_603F, 0x00),
};
do {
std::this_thread::sleep_for(poll_period);
if (!bus_runtime_->isHealthy()) {
return false;
}
if (!start_received) {
std::uint16_t controlword = 0;
if (!bus_runtime_->readSdo<std::uint16_t>(
node_id, msgs::CIA402_CONTROL_WORD_6040, 0x00, controlword)) {
return false;
}
// Method 35 can finish in one cycle; confirm receipt then take fresh feedback.
start_received = controlword == kStartHoming;
continue;
}
if (!bus_runtime_->readPdosAtomic(reads.data(), reads.size())) {
return false;
}
last_statusword = EthercatMotorBusRuntime::pdoReadValue<std::uint16_t>(reads[0]);
const auto mode = EthercatMotorBusRuntime::pdoReadValue<std::int8_t>(reads[1]);
zeroed_position = EthercatMotorBusRuntime::pdoReadValue<std::int32_t>(reads[2]);
const auto error = EthercatMotorBusRuntime::pdoReadValue<std::uint16_t>(reads[3]);
const auto status = cia402::statusword(last_statusword);
if (mode != kHomingMode || !cia402::isOperationEnabled(status) ||
status.fault || (last_statusword & kHomingError) != 0 || error != 0) {
CMVR_LOG(ERROR) << "[TchlMotorAdapter] zero calibration failed, node="
<< static_cast<int>(node_id)
<< ", statusword=0x" << std::hex << last_statusword
<< ", error=0x" << error << std::dec;
return false;
}
if ((last_statusword & kHomingAttained) != 0 && cia402::targetReached(status) &&
std::abs(static_cast<std::int64_t>(zeroed_position)) <= tolerance) {
return true;
}
} while (std::chrono::steady_clock::now() < deadline);
CMVR_LOG(ERROR) << "[TchlMotorAdapter] zero calibration timed out, node="
<< static_cast<int>(node_id) << ", start_received=" << start_received
<< ", statusword=0x" << std::hex << last_statusword << std::dec
<< ", actual_position=" << zeroed_position;
return false;
}
bool TchlMotorAdapter::brakeRelease(const std::uint8_t node_id)
{
if (!bus_runtime_) {
return false;
}
std::uint16_t statusword = 0;
if (!bus_runtime_->readSdo<std::uint16_t>(
node_id, msgs::CIA402_STATUS_WORD_6041, 0x00, statusword) ||
cia402::isOperationEnabled(cia402::statusword(statusword))) {
CMVR_LOG(ERROR) << "[TchlMotorAdapter] brake release requires a readable "
<< "statusword and a drive that is not operation enabled, node="
<< static_cast<int>(node_id);
return false;
}
std::uint16_t command_readback = 0;
const bool ok = bus_runtime_->writeSdo<std::uint16_t>(
node_id, kForceBrakeRelease, 0x00, kBrakeReleaseCommand) &&
bus_runtime_->readSdo<std::uint16_t>(
node_id, kForceBrakeRelease, 0x00, command_readback) &&
command_readback == kBrakeReleaseCommand;
if (!ok) {
CMVR_LOG(ERROR) << "[TchlMotorAdapter] failed to verify brake release command, node="
<< static_cast<int>(node_id)
<< ", command_readback=" << command_readback;
}
// Pr8.30 readback confirms the command, not physical brake feedback.
return ok;
}
} // namespace cmvr::device

View File

@ -0,0 +1,370 @@
#include <algorithm>
#include <chrono>
#include <cmath>
#include <csignal>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <thread>
#include <vector>
#include <absl/cleanup/cleanup.h>
#include <gtest/gtest.h>
#include "common/config/config_files.h"
#include "devices/motor/manager/include/motor_manager.h"
namespace cmvr::device {
namespace {
constexpr double kTargetPositionRad = 1.57; // Absolute output-axis position.
constexpr double kVelocityRadS = 0.5;
constexpr double kAccelerationRadS2 = 5.0;
constexpr double kCspExcursionRad = 1.57; // Motion range: q0 to q0 + excursion.
constexpr double kCspPeriodS = 6.0;
constexpr int kCspCycles = 2;
constexpr double kPvVelocityRadS = -0.3;
constexpr double kPvAccelerationRadS2 = 1.0;
constexpr std::chrono::seconds kPvDuration{2};
constexpr double kCsvVelocityAmplitudeRadS = 0.8;
constexpr double kCsvPeriodS = 6.0;
constexpr int kCsvCycles = 2;
constexpr double kPi = 3.14159265358979323846;
volatile std::sig_atomic_t stop_requested = 0;
void requestStop(int)
{
stop_requested = 1;
}
// Running this test enables and moves the real motor.
TEST(TchlMotorRealTest, ProfilePosition)
{
const char* config_path = std::getenv("TCHL_MOTOR_CONFIG");
config::MotorRootConfig root;
ASSERT_TRUE(ConfigHelper::loadConfigFile(
config_path ? config_path : "cmvr-es/config/devices/motor/tchl_motors.pb.txt", root));
ASSERT_EQ(root.motor().motor_groups_size(), 1);
const auto& group = root.motor().motor_groups(0);
ASSERT_EQ(group.motors().motors_size(), 1);
auto manager = std::make_shared<MotorManager>(root.motor().id(), root.motor(), group.id());
std::shared_ptr<AbstractMotor> motor;
bool enable_attempted = false;
stop_requested = 0;
const auto previous_sigint = std::signal(SIGINT, requestStop);
const auto previous_sigterm = std::signal(SIGTERM, requestStop);
// Also runs when an ASSERT returns early.
absl::Cleanup cleanup = [&] {
if (enable_attempted) {
EXPECT_TRUE(motor->quickStop());
EXPECT_TRUE(motor->torqueOff());
}
manager->stop();
std::signal(SIGINT, previous_sigint);
std::signal(SIGTERM, previous_sigterm);
};
ASSERT_TRUE(manager->init());
motor = manager->getMotor(group.motors().motors(0).joint_name());
ASSERT_NE(motor, nullptr);
ASSERT_FALSE(stop_requested);
enable_attempted = true;
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_PROFILE_POSITION));
ASSERT_TRUE(motor->torqueOn());
ASSERT_FALSE(stop_requested);
ASSERT_TRUE(motor->commandProfilePosition(
kTargetPositionRad, kVelocityRadS, kAccelerationRadS2));
const std::vector<std::shared_ptr<AbstractMotor>> motors{motor};
std::vector<double> positions, velocities, torques;
const auto end = std::chrono::steady_clock::now() + std::chrono::seconds{10};
while (!stop_requested && std::chrono::steady_clock::now() < end) {
ASSERT_TRUE(manager->readFeedbacksAtomic(motors, positions, velocities, torques));
std::cout << "target=" << kTargetPositionRad
<< ", q=" << positions[0] << " rad"
<< ", qd=" << velocities[0] << " rad/s"
<< ", torque=" << torques[0] << " per mille" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds{100});
}
}
// Running this test enables and moves the real motor.
TEST(TchlMotorRealTest, CyclicPositionSin)
{
const char* config_path = std::getenv("TCHL_MOTOR_CONFIG");
config::MotorRootConfig root;
ASSERT_TRUE(ConfigHelper::loadConfigFile(
config_path ? config_path : "cmvr-es/config/devices/motor/tchl_motors.pb.txt", root));
ASSERT_EQ(root.motor().motor_groups_size(), 1);
const auto& group = root.motor().motor_groups(0);
ASSERT_EQ(group.motors().motors_size(), 1);
ASSERT_TRUE(group.joint_limits().enable());
ASSERT_EQ(group.joint_limits().joints_size(), 1);
const auto command_period = std::chrono::microseconds{group.ethercat().cycle_us()};
ASSERT_GT(command_period.count(), 0);
auto manager = std::make_shared<MotorManager>(root.motor().id(), root.motor(), group.id());
std::shared_ptr<AbstractMotor> motor;
bool enable_attempted = false;
stop_requested = 0;
const auto previous_sigint = std::signal(SIGINT, requestStop);
const auto previous_sigterm = std::signal(SIGTERM, requestStop);
absl::Cleanup cleanup = [&] {
if (enable_attempted) {
EXPECT_TRUE(motor->quickStop());
EXPECT_TRUE(motor->torqueOff());
}
manager->stop();
std::signal(SIGINT, previous_sigint);
std::signal(SIGTERM, previous_sigterm);
};
ASSERT_TRUE(manager->init());
motor = manager->getMotor(group.motors().motors(0).joint_name());
ASSERT_NE(motor, nullptr);
ASSERT_FALSE(stop_requested);
enable_attempted = true;
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_POSITION));
ASSERT_TRUE(motor->torqueOn());
const std::vector<std::shared_ptr<AbstractMotor>> motors{motor};
std::vector<double> positions, velocities, torques;
ASSERT_TRUE(manager->readFeedbacksAtomic(motors, positions, velocities, torques));
const double start_q = positions[0];
const auto& limit = group.joint_limits().joints(0);
ASSERT_GE(std::min(start_q, start_q + kCspExcursionRad), limit.q_lb());
ASSERT_LE(std::max(start_q, start_q + kCspExcursionRad), limit.q_ub());
const double omega = 2.0 * kPi / kCspPeriodS;
const double duration_s = kCspPeriodS * kCspCycles;
const auto start_time = std::chrono::steady_clock::now();
auto next_print = start_time;
while (!stop_requested) {
const auto now = std::chrono::steady_clock::now();
const double t = std::min(duration_s,
std::chrono::duration<double>(now - start_time).count());
const bool finished = t >= duration_s;
// Same raised-cosine position and sine velocity as the Eyou CSP test.
const double target_q = finished ? start_q :
start_q + 0.5 * kCspExcursionRad * (1.0 - std::cos(omega * t));
const double target_qd = finished ? 0.0 :
0.5 * kCspExcursionRad * omega * std::sin(omega * t);
ASSERT_TRUE(motor->commandCyclicPosition(target_q, target_qd));
if (now >= next_print || finished) {
ASSERT_TRUE(manager->readFeedbacksAtomic(motors, positions, velocities, torques));
std::cout << "t=" << t << " s, target_q=" << target_q << " rad"
<< ", target_qd=" << target_qd << " rad/s"
<< ", q=" << positions[0] << " rad"
<< ", qd=" << velocities[0] << " rad/s"
<< ", torque=" << torques[0] << " per mille" << std::endl;
next_print = now + std::chrono::milliseconds{100};
}
if (finished) {
break;
}
// Skip elapsed ticks instead of sending a burst after a delayed wakeup.
const auto next_tick =
(std::chrono::steady_clock::now() - start_time) / command_period + 1;
std::this_thread::sleep_until(start_time + next_tick * command_period);
}
}
// Running this test enables and moves the real motor.
TEST(TchlMotorRealTest, ProfileVelocity)
{
const char* config_path = std::getenv("TCHL_MOTOR_CONFIG");
config::MotorRootConfig root;
ASSERT_TRUE(ConfigHelper::loadConfigFile(
config_path ? config_path : "cmvr-es/config/devices/motor/tchl_motors.pb.txt", root));
ASSERT_EQ(root.motor().motor_groups_size(), 1);
const auto& group = root.motor().motor_groups(0);
ASSERT_EQ(group.motors().motors_size(), 1);
ASSERT_TRUE(group.joint_limits().enable());
ASSERT_EQ(group.joint_limits().joints_size(), 1);
auto manager = std::make_shared<MotorManager>(root.motor().id(), root.motor(), group.id());
std::shared_ptr<AbstractMotor> motor;
bool enable_attempted = false;
stop_requested = 0;
const auto previous_sigint = std::signal(SIGINT, requestStop);
const auto previous_sigterm = std::signal(SIGTERM, requestStop);
absl::Cleanup cleanup = [&] {
if (enable_attempted) {
EXPECT_TRUE(motor->quickStop());
EXPECT_TRUE(motor->torqueOff());
}
manager->stop();
std::signal(SIGINT, previous_sigint);
std::signal(SIGTERM, previous_sigterm);
};
ASSERT_TRUE(manager->init());
motor = manager->getMotor(group.motors().motors(0).joint_name());
ASSERT_NE(motor, nullptr);
ASSERT_FALSE(stop_requested);
enable_attempted = true;
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_PROFILE_VELOCITY));
ASSERT_TRUE(motor->torqueOn());
const std::vector<std::shared_ptr<AbstractMotor>> motors{motor};
std::vector<double> positions, velocities, torques;
ASSERT_TRUE(manager->readFeedbacksAtomic(motors, positions, velocities, torques));
const auto& limit = group.joint_limits().joints(0);
ASSERT_LE(std::abs(kPvVelocityRadS), limit.qd());
// Allow travel at target speed for the whole run plus the stopping distance.
const double stop_distance = kPvVelocityRadS * kPvVelocityRadS / (2.0 * kPvAccelerationRadS2);
const double end_q = positions[0] + kPvVelocityRadS * kPvDuration.count() +
std::copysign(stop_distance, kPvVelocityRadS);
ASSERT_GE(std::min(positions[0], end_q), limit.q_lb());
ASSERT_LE(std::max(positions[0], end_q), limit.q_ub());
for (const double target_qd : {kPvVelocityRadS, 0.0}) {
if (stop_requested) {
break;
}
ASSERT_TRUE(motor->commandProfileVelocity(target_qd, kPvAccelerationRadS2));
const auto duration = target_qd == 0.0 ? std::chrono::seconds{1} : kPvDuration;
const auto end = std::chrono::steady_clock::now() + duration;
while (!stop_requested && std::chrono::steady_clock::now() < end) {
ASSERT_TRUE(manager->readFeedbacksAtomic(motors, positions, velocities, torques));
ASSERT_GE(positions[0], limit.q_lb());
ASSERT_LE(positions[0], limit.q_ub());
std::cout << "target_qd=" << target_qd << " rad/s"
<< ", q=" << positions[0] << " rad"
<< ", qd=" << velocities[0] << " rad/s"
<< ", torque=" << torques[0] << " per mille" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds{100});
}
}
}
// Running this test enables and moves the real motor.
TEST(TchlMotorRealTest, CyclicVelocitySin)
{
const char* config_path = std::getenv("TCHL_MOTOR_CONFIG");
config::MotorRootConfig root;
ASSERT_TRUE(ConfigHelper::loadConfigFile(
config_path ? config_path : "cmvr-es/config/devices/motor/tchl_motors.pb.txt", root));
ASSERT_EQ(root.motor().motor_groups_size(), 1);
const auto& group = root.motor().motor_groups(0);
ASSERT_EQ(group.motors().motors_size(), 1);
ASSERT_TRUE(group.joint_limits().enable());
ASSERT_EQ(group.joint_limits().joints_size(), 1);
const auto command_period = std::chrono::microseconds{group.ethercat().cycle_us()};
ASSERT_GT(command_period.count(), 0);
auto manager = std::make_shared<MotorManager>(root.motor().id(), root.motor(), group.id());
std::shared_ptr<AbstractMotor> motor;
bool enable_attempted = false;
stop_requested = 0;
const auto previous_sigint = std::signal(SIGINT, requestStop);
const auto previous_sigterm = std::signal(SIGTERM, requestStop);
absl::Cleanup cleanup = [&] {
if (enable_attempted) {
EXPECT_TRUE(motor->quickStop());
EXPECT_TRUE(motor->torqueOff());
}
manager->stop();
std::signal(SIGINT, previous_sigint);
std::signal(SIGTERM, previous_sigterm);
};
ASSERT_TRUE(manager->init());
motor = manager->getMotor(group.motors().motors(0).joint_name());
ASSERT_NE(motor, nullptr);
ASSERT_FALSE(stop_requested);
enable_attempted = true;
ASSERT_TRUE(motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY));
ASSERT_TRUE(motor->torqueOn());
const std::vector<std::shared_ptr<AbstractMotor>> motors{motor};
std::vector<double> positions, velocities, torques;
ASSERT_TRUE(manager->readFeedbacksAtomic(motors, positions, velocities, torques));
const auto& limit = group.joint_limits().joints(0);
ASSERT_LE(std::abs(kCsvVelocityAmplitudeRadS), limit.qd());
const double omega = 2.0 * kPi / kCsvPeriodS;
const double end_q = positions[0] + 2.0 * kCsvVelocityAmplitudeRadS / omega;
ASSERT_GE(std::min(positions[0], end_q), limit.q_lb());
ASSERT_LE(std::max(positions[0], end_q), limit.q_ub());
const double duration_s = kCsvPeriodS * kCsvCycles;
const auto start_time = std::chrono::steady_clock::now();
auto next_print = start_time;
while (!stop_requested) {
const auto now = std::chrono::steady_clock::now();
const double t = std::min(duration_s,
std::chrono::duration<double>(now - start_time).count());
const bool finished = t >= duration_s;
const double target_qd = finished ? 0.0 :
kCsvVelocityAmplitudeRadS * std::sin(omega * t);
ASSERT_TRUE(motor->commandCyclicVelocity(target_qd));
if (now >= next_print || finished) {
ASSERT_TRUE(manager->readFeedbacksAtomic(motors, positions, velocities, torques));
ASSERT_GE(positions[0], limit.q_lb());
ASSERT_LE(positions[0], limit.q_ub());
std::cout << "t=" << t << " s, target_qd=" << target_qd << " rad/s"
<< ", q=" << positions[0] << " rad"
<< ", qd=" << velocities[0] << " rad/s"
<< ", torque=" << torques[0] << " per mille" << std::endl;
next_print = now + std::chrono::milliseconds{100};
}
if (finished) {
break;
}
const auto next_tick =
(std::chrono::steady_clock::now() - start_time) / command_period + 1;
std::this_thread::sleep_until(start_time + next_tick * command_period);
}
}
// Changes the current zero point; calibration temporarily enables then disables the motor.
TEST(TchlMotorRealTest, CalibrateZeroQ)
{
const char* config_path = std::getenv("TCHL_MOTOR_CONFIG");
config::MotorRootConfig root;
ASSERT_TRUE(ConfigHelper::loadConfigFile(
config_path ? config_path : "cmvr-es/config/devices/motor/tchl_motors.pb.txt", root));
ASSERT_EQ(root.motor().motor_groups_size(), 1);
const auto& group = root.motor().motor_groups(0);
ASSERT_EQ(group.motors().motors_size(), 1);
auto manager = std::make_shared<MotorManager>(root.motor().id(), root.motor(), group.id());
std::shared_ptr<AbstractMotor> motor;
stop_requested = 0;
const auto previous_sigint = std::signal(SIGINT, requestStop);
const auto previous_sigterm = std::signal(SIGTERM, requestStop);
absl::Cleanup cleanup = [&] {
if (motor) {
EXPECT_TRUE(motor->torqueOff());
}
manager->stop();
std::signal(SIGINT, previous_sigint);
std::signal(SIGTERM, previous_sigterm);
};
ASSERT_TRUE(manager->init());
motor = manager->getMotor(group.motors().motors(0).joint_name());
ASSERT_NE(motor, nullptr);
const std::vector<std::shared_ptr<AbstractMotor>> motors{motor};
std::vector<double> positions, velocities, torques;
ASSERT_TRUE(manager->readFeedbacksAtomic(motors, positions, velocities, torques));
std::cout << "before calibration: q=" << positions[0] << " rad"
<< ", qd=" << velocities[0] << " rad/s"
<< ", torque=" << torques[0] << " per mille"
<< ", mode=" << msgs::RunMode_Name(motor->getMode()) << std::endl;
ASSERT_FALSE(stop_requested);
ASSERT_TRUE(motor->calibrateZeroQ());
ASSERT_TRUE(manager->readFeedbacksAtomic(motors, positions, velocities, torques));
std::cout << "after calibration: q=" << positions[0] << " rad"
<< ", qd=" << velocities[0] << " rad/s"
<< ", torque=" << torques[0] << " per mille"
<< ", mode=" << msgs::RunMode_Name(motor->getMode()) << std::endl;
}
} // namespace
} // namespace cmvr::device

View File

@ -28,8 +28,8 @@ public:
bool brakeRelease() override;
bool quickStop() override;
void setLimitQ(double ub, double lb) override;
void setLimitQd(double qd) override;
bool setLimitQ(double ub, double lb) override;
bool setLimitQd(double qd) override;
void setLimitQdd(double u_qdd, double l_qdd) override;
bool calibrateZeroQ() override;

View File

@ -79,17 +79,25 @@ bool MujocoMotor::quickStop()
return holdPosition_();
}
void MujocoMotor::setLimitQ(const double ub, const double lb)
bool MujocoMotor::setLimitQ(const double ub, const double lb)
{
if (!std::isfinite(ub) || !std::isfinite(lb)) {
return false;
}
std::scoped_lock lock(mtx_);
info_.limit_q_ub = ub;
info_.limit_q_lb = lb;
return true;
}
void MujocoMotor::setLimitQd(const double qd)
bool MujocoMotor::setLimitQd(const double qd)
{
if (!std::isfinite(qd)) {
return false;
}
std::scoped_lock lock(mtx_);
info_.limit_qd = std::abs(qd);
return true;
}
void MujocoMotor::setLimitQdd(const double u_qdd, const double l_qdd)

View File

@ -67,8 +67,12 @@ namespace cmvr {
}
// canopen_protocol->seedSdoRequest(node_id_, msgs::CS_WRITE_TWO_BYTES, msgs::CIA402_CONTROL_WORD_6040, msgs::SUB_INDEX_0, 0x06,15);
// canopen_protocol->seedSdoRequest(node_id_, msgs::CS_WRITE_TWO_BYTES, msgs::CIA402_CONTROL_WORD_6040, msgs::SUB_INDEX_0, 0x0F,15);
canopen_protocol->setLimitQ(node_id_, info_.limit_q_ub, info_.limit_q_lb);
canopen_protocol->setLimitQd(node_id_, info_.limit_qd);
if (!canopen_protocol->setLimitQ(node_id_, info_.limit_q_ub, info_.limit_q_lb) ||
!canopen_protocol->setLimitQd(node_id_, info_.limit_qd)) {
CMVR_LOG(ERROR) << "[Ti5Motor] failed to submit motor limits: "
<< info_.joint_name;
return false;
}
canopen_protocol->setLimitQdd(node_id_, info_.limit_qdd, -info_.limit_qdd);
// canopen_protocol->torqueOff(node_id_);
@ -76,6 +80,54 @@ namespace cmvr {
return true;
}
bool setLimitQ(double ub, double lb) override {
std::scoped_lock lock(mtx_);
const auto canopen_protocol =
std::dynamic_pointer_cast<Ti5MotorCanopenProtocol>(protocol_);
if (!canopen_protocol) {
CMVR_LOG(ERROR) << "[Ti5Motor] invalid CANopen protocol for motor: "
<< info_.joint_name;
return false;
}
return canopen_protocol->setLimitQ(node_id_, ub, lb);
}
bool setLimitQd(double qd) override {
std::scoped_lock lock(mtx_);
const auto canopen_protocol =
std::dynamic_pointer_cast<Ti5MotorCanopenProtocol>(protocol_);
if (!canopen_protocol) {
CMVR_LOG(ERROR) << "[Ti5Motor] invalid CANopen protocol for motor: "
<< info_.joint_name;
return false;
}
return canopen_protocol->setLimitQd(node_id_, qd);
}
bool calibrateZeroQ() override {
std::scoped_lock lock(mtx_);
const auto canopen_protocol =
std::dynamic_pointer_cast<Ti5MotorCanopenProtocol>(protocol_);
if (!canopen_protocol) {
CMVR_LOG(ERROR) << "[Ti5Motor] invalid CANopen protocol for motor: "
<< info_.joint_name;
return false;
}
return canopen_protocol->calibrateZeroQ(node_id_);
}
bool brakeRelease() override {
std::scoped_lock lock(mtx_);
const auto canopen_protocol =
std::dynamic_pointer_cast<Ti5MotorCanopenProtocol>(protocol_);
if (!canopen_protocol) {
CMVR_LOG(ERROR) << "[Ti5Motor] invalid CANopen protocol for motor: "
<< info_.joint_name;
return false;
}
return canopen_protocol->brakeRelease(node_id_);
}
private:
double encoder_counts_per_rev_{0.0};
double gear_ratio_{0.0};

View File

@ -31,13 +31,14 @@ namespace cmvr {
bool initNode(uint8_t node_id) override;
bool setMode(uint8_t node_id, msgs::RunMode mode) override;
void setLimitQ(uint8_t node_id, double ub, double lb) override;
void setLimitQd(uint8_t node_id, double qd) override;
// true 表示限位请求已提交到 CAN 发送缓存,不代表驱动器已确认。
bool setLimitQ(uint8_t node_id, double ub, double lb);
bool setLimitQd(uint8_t node_id, double qd);
void setLimitQdd(uint8_t node_id, double u_qdd,double l_qdd) override;
bool calibrateZeroQ(uint8_t node_id) override;
bool calibrateZeroQ(uint8_t node_id);
bool torqueOn(uint8_t node_id) override;
bool torqueOff(uint8_t node_id) override;
bool brakeRelease(uint8_t node_id) override;
bool brakeRelease(uint8_t node_id);
bool quickStop(uint8_t node_id) override;
bool reachedTargetQ(uint8_t node_id) override;

View File

@ -10,6 +10,7 @@
#include "motor/drivers/ti5_canopen/include/protocol/ti5_motor_tpdo2.h"
#include "motor/drivers/ti5_canopen/include/protocol/ti5_motor_sdo_response.h"
#include "canbus/canopen/nmt_response_protocol.h"
#include <limits>
using namespace cmvr::device;
using namespace cmvr::msgs;
@ -552,25 +553,51 @@ void Ti5MotorCanopenProtocol::setLimitQdd(uint8_t node_id, double u_qdd, double
seedSdoRequest(node_id, CS_WRITE_FOUR_BYTES, CIA402_PROFILE_DECELERATION_6084, SUB_INDEX_0, std::abs(decel));
}
void Ti5MotorCanopenProtocol::setLimitQd(uint8_t node_id, double qd) {
bool Ti5MotorCanopenProtocol::setLimitQd(uint8_t node_id, double qd) {
const auto command = sdo_commands_.find(node_id);
if (!can_sender_ || command == sdo_commands_.end() || !command->second ||
!std::isfinite(qd)) {
return false;
}
const auto* conversion = conversionForNode(node_id);
if (!conversion) {
return;
return false;
}
auto speed = radPerSecToVelocityRaw(qd, *conversion);
seedSdoRequest(node_id, CS_WRITE_FOUR_BYTES, CIA402_MAX_PROFILE_VELOCITY_607F, SUB_INDEX_0, speed);
const auto speed = radPerSecToVelocityRaw(qd, *conversion);
if (!std::isfinite(speed) || speed < 0.0 ||
speed > std::numeric_limits<uint32_t>::max()) {
return false;
}
seedSdoRequest(node_id, CS_WRITE_FOUR_BYTES, CIA402_MAX_PROFILE_VELOCITY_607F,
SUB_INDEX_0, static_cast<uint32_t>(speed));
return true;
}
void Ti5MotorCanopenProtocol::setLimitQ(uint8_t node_id, double ub, double lb) {
bool Ti5MotorCanopenProtocol::setLimitQ(uint8_t node_id, double ub, double lb) {
const auto command = sdo_commands_.find(node_id);
if (!can_sender_ || command == sdo_commands_.end() || !command->second ||
!std::isfinite(ub) || !std::isfinite(lb)) {
return false;
}
const auto* conversion = conversionForNode(node_id);
if (!conversion) {
return;
return false;
}
ub = radToCounts(ub, *conversion);
lb = radToCounts(lb, *conversion);
if (!std::isfinite(ub) || !std::isfinite(lb) ||
ub < std::numeric_limits<int32_t>::min() ||
ub > std::numeric_limits<int32_t>::max() ||
lb < std::numeric_limits<int32_t>::min() ||
lb > std::numeric_limits<int32_t>::max()) {
return false;
}
seedSdoRequest(node_id, CS_WRITE_FOUR_BYTES, CIA402_SOFTWARE_POSITION_LIMIT_607D, SUB_INDEX_1, lb);
seedSdoRequest(node_id, CS_WRITE_FOUR_BYTES, CIA402_SOFTWARE_POSITION_LIMIT_607D, SUB_INDEX_2, ub);
seedSdoRequest(node_id, CS_WRITE_FOUR_BYTES, CIA402_SOFTWARE_POSITION_LIMIT_607D,
SUB_INDEX_1, static_cast<uint32_t>(static_cast<int32_t>(lb)));
seedSdoRequest(node_id, CS_WRITE_FOUR_BYTES, CIA402_SOFTWARE_POSITION_LIMIT_607D,
SUB_INDEX_2, static_cast<uint32_t>(static_cast<int32_t>(ub)));
return true;
}

View File

@ -53,10 +53,20 @@ public:
bool commandCyclicVelocitiesAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
const std::vector<double>& velocities) const;
// Torques are per mille of rated torque: 1000 equals rated torque.
bool commandCyclicTorquesAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
const std::vector<double>& torques) const;
bool readFeedbacksAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
std::vector<double>& positions,
std::vector<double>& velocities) const;
// Reads all three quantities from one EtherCAT snapshot; torques are per mille.
bool readFeedbacksAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
std::vector<double>& positions,
std::vector<double>& velocities,
std::vector<double>& torques) const;
static std::shared_ptr<MotorManager> managerFor(const std::string& id);
static std::shared_ptr<simulate::MujocoWorld> mujocoWorldFor(const std::string& id);

View File

@ -15,9 +15,13 @@
#include "devices/motor/bus_runtime/ethercat/include/ethercat_motor_bus_runtime.h"
#include "devices/motor/bus_runtime/mujoco/include/mujoco_motor_bus_runtime.h"
#include "devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h"
#include "devices/motor/drivers/ethercat_motor/include/ethercat_motor.h"
#include "devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_cia402_pdo_mapping.h"
#include "devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h"
#include "devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor_adapter.h"
#include "devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_cia402_pdo_mapping.h"
#include "devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_motor.h"
#include "devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_motor_adapter.h"
#include "devices/motor/drivers/mujoco/include/mujoco_motor.h"
#include "devices/motor/drivers/ti5_canopen/include/ti5_motor.h"
#include "devices/motor/drivers/ti5_canopen/include/ti5_motor_canopen_protocol.h"
@ -279,8 +283,8 @@ bool MotorManager::commandCyclicPositionsAtomic(
return false;
}
if (std::dynamic_pointer_cast<EyouMotor>(motors.front())) {
return EyouMotor::commandCyclicPositionsAtomic(motors, positions, velocities);
if (std::dynamic_pointer_cast<EthercatMotor>(motors.front())) {
return EthercatMotor::commandCyclicPositionsAtomic(motors, positions, velocities);
}
if (std::dynamic_pointer_cast<MujocoMotor>(motors.front())) {
return MujocoMotor::commandCyclicPositionsAtomic(motors, positions, velocities);
@ -328,8 +332,8 @@ bool MotorManager::commandCyclicVelocitiesAtomic(
}
}
}
if (std::dynamic_pointer_cast<EyouMotor>(motors.front())) {
return EyouMotor::commandCyclicVelocitiesAtomic(motors, velocities);
if (std::dynamic_pointer_cast<EthercatMotor>(motors.front())) {
return EthercatMotor::commandCyclicVelocitiesAtomic(motors, velocities);
}
if (std::dynamic_pointer_cast<MujocoMotor>(motors.front())) {
return MujocoMotor::commandCyclicVelocitiesAtomic(motors, velocities);
@ -364,6 +368,21 @@ bool MotorManager::commandCyclicVelocitiesAtomic(
return false;
}
bool MotorManager::commandCyclicTorquesAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
const std::vector<double>& torques) const
{
if (motors.empty() || !motors.front()) {
return false;
}
if (std::dynamic_pointer_cast<EthercatMotor>(motors.front())) {
return EthercatMotor::commandCyclicTorquesAtomic(motors, torques);
}
CMVR_LOG(ERROR) << "[MotorManager] atomic cyclic torque is unsupported for motor type: "
<< motors.front()->typeName();
return false;
}
bool MotorManager::readFeedbacksAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
std::vector<double>& positions,
@ -383,8 +402,8 @@ bool MotorManager::readFeedbacksAtomic(
}
}
if (std::dynamic_pointer_cast<EyouMotor>(motors.front())) {
return EyouMotor::readFeedbacksAtomic(motors, positions, velocities);
if (std::dynamic_pointer_cast<EthercatMotor>(motors.front())) {
return EthercatMotor::readFeedbacksAtomic(motors, positions, velocities);
}
if (std::dynamic_pointer_cast<MujocoMotor>(motors.front())) {
return MujocoMotor::readFeedbacksAtomic(motors, positions, velocities);
@ -418,6 +437,24 @@ bool MotorManager::readFeedbacksAtomic(
return false;
}
bool MotorManager::readFeedbacksAtomic(
const std::vector<std::shared_ptr<AbstractMotor>>& motors,
std::vector<double>& positions,
std::vector<double>& velocities,
std::vector<double>& torques) const
{
if (motors.empty() || !motors.front() || &positions == &velocities ||
&positions == &torques || &velocities == &torques) {
return false;
}
if (std::dynamic_pointer_cast<EthercatMotor>(motors.front())) {
return EthercatMotor::readFeedbacksAtomic(motors, positions, velocities, torques);
}
CMVR_LOG(ERROR) << "[MotorManager] atomic torque feedback is unsupported for motor type: "
<< motors.front()->typeName();
return false;
}
std::shared_ptr<MotorManager> MotorManager::managerFor(const std::string& id)
{
std::lock_guard<std::mutex> lock(registry_mutex_);
@ -530,10 +567,15 @@ std::shared_ptr<AbstractMotorBusRuntime> MotorManager::createBusRuntime_(
return std::make_shared<MujocoMotorBusRuntime>();
case config::MOTOR_BUS_ETHERCAT: {
auto runtime = std::make_shared<EthercatMotorBusRuntime>();
if (group_cfg.vendor() == config::MOTOR_VENDOR_EYOU &&
group_cfg.protocol() == config::MOTOR_PROTOCOL_ETHERCAT_CIA402) {
runtime->setPdoMapping(createEyouCia402PdoMapping());
return runtime;
if (group_cfg.protocol() == config::MOTOR_PROTOCOL_ETHERCAT_CIA402) {
if (group_cfg.vendor() == config::MOTOR_VENDOR_EYOU) {
runtime->setPdoMapping(createEyouCia402PdoMapping());
return runtime;
}
if (group_cfg.vendor() == config::MOTOR_VENDOR_TCHL) {
runtime->setPdoMapping(createTchlCia402PdoMapping());
return runtime;
}
}
CMVR_LOG(ERROR) << "[MotorManager] unsupported EtherCAT motor: vendor="
<< config::MotorVendor_Name(group_cfg.vendor())
@ -645,8 +687,12 @@ std::vector<std::shared_ptr<AbstractMotor>> MotorManager::createMujocoMotors_(
cfg.joint_name(),
mujoco_bus_runtime->mujocoWorld(),
static_cast<std::uint8_t>(cfg.id()));
motor->setLimitQ(cfg.limit_q_ub(), cfg.limit_q_lb());
motor->setLimitQd(cfg.limit_qd());
if (!motor->setLimitQ(cfg.limit_q_ub(), cfg.limit_q_lb()) ||
!motor->setLimitQd(cfg.limit_qd())) {
CMVR_LOG(ERROR) << "[MotorManager] failed to set MuJoCo motor limits: "
<< cfg.joint_name();
return {};
}
if (cfg.limit_qdd() > 0.0) {
motor->setLimitQdd(cfg.limit_qdd(), -cfg.limit_qdd());
}
@ -674,7 +720,8 @@ std::vector<std::shared_ptr<AbstractMotor>> MotorManager::createEthercatMotors_(
CMVR_LOG(ERROR) << "[MotorManager] missing EtherCAT config: " << group_cfg.id();
return {};
}
if (group_cfg.vendor() != config::MOTOR_VENDOR_EYOU ||
if ((group_cfg.vendor() != config::MOTOR_VENDOR_EYOU &&
group_cfg.vendor() != config::MOTOR_VENDOR_TCHL) ||
group_cfg.protocol() != config::MOTOR_PROTOCOL_ETHERCAT_CIA402) {
CMVR_LOG(ERROR) << "[MotorManager] unsupported EtherCAT motor: vendor="
<< config::MotorVendor_Name(group_cfg.vendor())
@ -696,11 +743,18 @@ std::vector<std::shared_ptr<AbstractMotor>> MotorManager::createEthercatMotors_(
std::vector<std::shared_ptr<AbstractMotor>> motors;
motors.reserve(motor_cfgs.size());
for (const auto& cfg : motor_cfgs) {
auto motor = std::make_shared<EyouMotor>(
cfg, protocol, std::make_unique<EyouMotorAdapter>(ethercat_bus_runtime));
std::shared_ptr<AbstractMotor> motor;
if (group_cfg.vendor() == config::MOTOR_VENDOR_EYOU) {
motor = std::make_shared<EyouMotor>(
cfg, protocol, std::make_unique<EyouMotorAdapter>(ethercat_bus_runtime));
} else {
motor = std::make_shared<TchlMotor>(
cfg, protocol, std::make_unique<TchlMotorAdapter>(ethercat_bus_runtime));
}
if (!motor->init()) {
CMVR_LOG(ERROR) << "[MotorManager] failed to init EYOU EtherCAT motor: "
<< cfg.joint_name();
CMVR_LOG(ERROR) << "[MotorManager] failed to init EtherCAT motor: "
<< cfg.joint_name() << ", vendor="
<< config::MotorVendor_Name(group_cfg.vendor());
return {};
}
motors.push_back(std::move(motor));

View File

@ -6,6 +6,7 @@
#pragma once
#include <cstdint>
#include <limits>
#include "cmvr/msgs/canopen.pb.h"
#include "cmvr/msgs/motor.pb.h"
@ -30,9 +31,6 @@ namespace cmvr {
virtual bool setMode(uint8_t node_id,msgs::RunMode mode ) = 0;
virtual msgs::RunMode getMode(uint8_t node_id) = 0;
virtual void setLimitQdd(uint8_t node_id, double u_qdd,double l_qdd) = 0;
virtual void setLimitQd(uint8_t node_id,double qd) = 0;
virtual void setLimitQ(uint8_t node_id, double ub, double lb) = 0;
virtual bool calibrateZeroQ(uint8_t node_id) = 0;
virtual bool reachedTargetQ(uint8_t node_id) = 0;
// target_q: rad, max_qd: rad/s, max_qdd: rad/s^2.
// Profile Position 写入目标位置和轮廓速度/加速度,并触发一次新目标。
@ -45,6 +43,16 @@ namespace cmvr {
virtual bool commandProfileVelocity(uint8_t node_id,
double target_qd,
double max_qdd) = 0;
// target_tau: per mille of rated torque; torque_slope: per mille/s, > 0.
// Unsupported protocols return false.
virtual bool commandProfileTorque(uint8_t node_id,
double target_tau,
std::uint32_t torque_slope) {
(void)node_id;
(void)target_tau;
(void)torque_slope;
return false;
}
// target_q: rad, target_qd: rad/s.
// Cyclic Position 周期写入目标位置和目标速度。
virtual bool commandCyclicPosition(uint8_t node_id,
@ -54,18 +62,22 @@ namespace cmvr {
// Cyclic Velocity 周期写入目标速度。
virtual bool commandCyclicVelocity(uint8_t node_id,
double target_qd) = 0;
// target_tau: N*m.
// target_tau: per mille of rated torque (1000 = rated torque).
virtual bool commandCyclicTorque(uint8_t node_id, double target_tau) = 0;
virtual void setMotorConversion(uint8_t node_id,
double encoder_counts_per_rev,
double gear_ratio) = 0;
virtual bool torqueOn(uint8_t node_id) = 0;
virtual bool torqueOff(uint8_t node_id) = 0;
virtual bool brakeRelease(uint8_t node_id) = 0;
virtual bool quickStop(uint8_t node_id) = 0;
virtual double getQ(uint8_t node_id) = 0;
virtual double getQd(uint8_t node_id) = 0;
// Per mille of rated torque; NaN when unavailable.
virtual double getTau(uint8_t node_id) {
(void)node_id;
return std::numeric_limits<double>::quiet_NaN();
}
CommProto comm_proto{CommProto::CANOPEN};
protected:
};

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@ -1,11 +1,17 @@
# EtherCAT 电机接入教程
当前已接入意优 `EYOU_ServoModule_ECAT_V145`,协议为 EtherCAT CoE + CiA402,PDO 使用 `docs/EYOU_ServoModule_ECAT_V145_no_slot.xml` 中的 `0x1600/0x1A00` 映射。
当前 EtherCAT CoE + CiA402 驱动包含意优和同川两种厂商适配:
| 厂商 | 配置枚举 | ESI 资料 | RxPDO / TxPDO |
| --- | --- | --- | --- |
| 意优 | `MOTOR_VENDOR_EYOU` | `docs/EYOU_ServoModule_ECAT_V145_no_slot.xml` | `0x1600 / 0x1A00` |
| 同川 TCHL | `MOTOR_VENDOR_TCHL` | `docs/TC-TECH_TC600E_TR_1.5.xml` | `0x1601 / 0x1A01` |
ESI XML 作为厂商通信说明和对照资料保存,运行时不直接解析 XML。实际 PDO 映射写在:
```text
cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_cia402_pdo_mapping.h
cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_cia402_pdo_mapping.h
```
## 1. 系统依赖
@ -29,7 +35,7 @@ script/ethercat/status_ethercat.sh
dependency/x86/third_party/ethercat/v1.7.0/etc/ethercat.conf
```
并通过 bundled IgH 的 `ethercatctl -c` 启动 master。能看到 EYOU slave 后再启动程序。
并通过 bundled IgH 的 `ethercatctl -c` 启动 master。确认目标从站的身份和位置后再启动程序。
停止 EtherCAT:
@ -66,9 +72,10 @@ motor {
ethercat {
master_index: 0
cycle_us: 1000
slave_op_timeout_ms: 12000
slave_state_poll_period_ms: 10
cia402 {
profile_position_trigger_delay_ms: 2
state_transition_timeout_ms: 1200
velocity_stop_timeout_ms: 2000
status_poll_period_ms: 10
@ -83,6 +90,8 @@ motor {
stable_delta_counts: 1000
}
dc { enable: false }
slaves { motor_id: 1 alias: 0 position: 0 }
slaves { motor_id: 2 alias: 0 position: 1 }
slaves { motor_id: 3 alias: 0 position: 2 }
@ -120,11 +129,12 @@ motor {
字段说明:
- `master_index`:IgH master 编号,第一张 EtherCAT master 是 `0`。
- `slave_op_timeout_ms`、`slave_state_poll_period_ms`:进入 OP 的等待超时和状态查询周期,均需显式配置正值。
- `dc`:必须显式配置是否启用;启用时还需提供参考从站、Sync0 周期和偏移、同步周期及 `assign_activate` 等字段。
- `alias`:EtherCAT alias,一般为 `0`。
- `position`:slave 在 EtherCAT 链路上的顺序,从 `0` 开始。
- `motor_id`:系统内电机 id,必须和 `motors.motors.id` 对应。
- `encoder_counts_per_rev`:电机编码器每转 count 数,用于 `rad <-> count` 换算。
- `gear_ratio`:电机轴到关节输出轴的减速比,用于接口层 `rad/rad/s` 和驱动器 raw count/counts/s 换算。
- `encoder_counts_per_rev`、`gear_ratio`:两者乘积表示关节输出轴每转对应的驱动器位置单位数。驱动器使用电机端原始计数时,分别填写电机编码器每转计数和机械减速比;其他单位设置见下方同川说明。
## 3. 注册设备
@ -176,41 +186,166 @@ cmvr-es/devices/motor/bus_runtime/ethercat/src/ethercat_motor_bus_runtime.cpp
- 打开 IgH master
- 创建 domain
- 使用 `vendor + protocol` 选择 PDO mapping
- 按 mapping 配置 `0x1600/0x1A00` PDO
- 使用 `MotorManager` 按 `vendor + protocol` 选定的 PDO mapping 配置从站
- 按 mapping 配置对应的 RxPDO / TxPDO
- 注册每个非 padding PDO entry 的 offset
- 启动 cyclic loop
- 按 `motor_id + index + subindex` 提供通用 PDO 读写接口
CiA402 EtherCAT 电机驱动:
公共电机层和 CiA402 协议层:
```text
cmvr-es/devices/motor/drivers/ethercat_motor/include/ethercat_motor.h
cmvr-es/devices/motor/drivers/ethercat_motor/src/ethercat_motor.cpp
cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h
cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_objects.h
cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/motor_vendor_adapter.h
cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_protocol.cpp
```
EYOU 私有适配:
继承与调用关系:
```text
cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h
cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor_adapter.h
cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_cia402_pdo_mapping.h
cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_objects.h
cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor.cpp
cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor_adapter.cpp
AbstractMotor
└── EthercatMotor:公共配置、单位换算、多轴批量命令和反馈
├── EyouMotor:组合 EyouMotorAdapter
└── TchlMotor:组合 TchlMotorAdapter
厂家 Motor → 共享 Cia402Protocol → EthercatMotorBusRuntime
厂家 Motor → 厂家 Adapter → EthercatMotorBusRuntime
```
它负责:
`Cia402Protocol` 负责:
- CiA402 `6040/6041` 状态机
- 设置 `6060` 运行模式
- 写 `607A/60FF/6071`
- PP、PV、PT、CSP、CSV、CST 的目标值和模式切换
- 根据映射选择 CSP 速度前馈对象;PP/PV 轮廓参数通过 SDO 下发
- 读 `6064/606C/6077/603F`
- `rad` 和 encoder count 的换算
## 6. 编译验证
各厂家文件分别位于 `include/vendor/eyou`、`src/vendor/eyou` 和 `include/vendor/tchl`、`src/vendor/tchl`。按完整操作划分职责:通用控制由 Protocol 完成;厂家限位、抱闸、校准及同川使能/失能由 Adapter 完成。Adapter 内部可以访问标准对象,以保留厂家要求的步骤和顺序;Protocol 与 Adapter 都只依赖 Runtime,互不持有或调用。
Motor 负责加锁、参数换算和分发,同一个功能只调用其中一层。例如位置限位直接委托 Adapter,避免 Motor 先通过 Protocol 写一遍 `607D`。校准后的目标同步、软限位恢复和失败处理也由 Adapter 完成。Protocol 在后续标准控制入口根据实际模式和状态校验指令;周期控制只读取 PDO,不增加周期 SDO 访问。
`setLimitQ`、`setLimitQd`、`calibrateZeroQ` 和 `brakeRelease` 保留为 Motor 层业务接口,不再属于 `MotorProtocolInterface` 或 `Cia402Protocol`。意优和同川通过各自 Adapter 实现;TI5 保留具体驱动的转发实现。
`torqueOn()` 按驱动当前已配置的模式使能,不再强制切换到 PP,也不写 `6060`。驱动已有有效模式时,可先 `torqueOn()` 再 `setMode(...)`;模式尚未配置时,需要先 `setMode(...)` 再使能。单轴测试显式采用后一种顺序,确保初始模式明确。使能前准备安全目标,随后按 `0006→0007→000F` 等待 `OperationEnabled`;模式确认由 `setMode()` 完成,PP 的新目标及应答握手由 `commandProfilePosition()` 完成。同川额外完成厂家要求的等待。机械臂初始化时,仅为未配置模式的 EtherCAT 轴选择初始 CSP,已有模式保留。
## 6. 同川 TCHL 配置与联调
使用单轴模板 `cmvr-es/config/devices/motor/tchl_motors.pb.txt`。模板尚未注册为活动设备;按当前实机 `PrD.00=0`、电子齿轮 `1:1`,依据手册印刷第 2 页参数表及第 20 页换算,`encoder_counts_per_rev` 配置为 `131072`,当前 `gear_ratio` 配置为 `101`。接入其他模块时应读取 `PrD.06 / 3D06:00 UINT16` 确认减速比,并核对机械轴实际位置、速度和加速度限位,再按第 3、4 节关联设备与使用方;设备 id、组 id 和关节名需使用模板中的对应值。
映射按提供的 TC600E TR ESI 编写,Vendor ID 为 `0x00075500`,Product Code 为 `0x00000002`;实机身份仍需核对。默认 PDO 如下,所有子索引均为 `0`:
| 方向 | PDO / SM | 条目顺序(位宽) |
| --- | --- | --- |
| 主站发送 | `0x1601 / SM2`,17 字节 | `6040(16), 607A(32), 60FF(32), 6071(16), 60B1(32), 6060(8)` |
| 主站接收 | `0x1A01 / SM3`,19 字节 | `6041(16), 6064(32), 606C(32), 6077(16), 60F4(32), 603F(16), 6061(8)` |
CSP 写目标位置 `607A` 和速度前馈 `60B1`;CSV 的目标速度写 `60FF`。`6081/6083/6084` 不放入此默认 PDO,PP/PV 参数使用 SDO。模板当前关闭 DC,通信周期为 1 ms;保留的 DC 配置为 Sync0 周期 1 ms、`assign_activate: 768`(`0x0300`)、偏移 0,开启前需核对实际同步要求。手册列出的 Sync0 周期为 1、2、3 ms。
目标力矩和反馈力矩均以额定力矩的千分比(‰)表示:`1000` 为额定力矩,`100` 为额定力矩的 10%。PT 的 `torque_slope` 按已确认的 **`0.1%/s`(‰/s)** 直接写入 `6087`;例如 `1000` 表示每秒变化一个额定力矩,不做额外的 1000 倍换算。
单位配置必须与驱动器当前设置一致,程序不自动修改全闭环、电子齿轮或绝对位置参数:
- `PrD.00=0` 且电子齿轮为 1:1 时,使用电机端每转计数和机械减速比。
- 手册第 2 页列出的 TCHL_11/14/17/20/25/32 电机端均为 17 bit,即每转 `131072`,输出端为 19 bit,即每转 `524288`。第 65 页说明 `PrD.04` 是输出端一圈计数除以 4,因此 `3D04=131072` 对应输出端 `524288`,不能将该寄存器当作电机端分辨率来源。
- `PrD.00=1` 时位置采用输出端编码器尺度,应填写输出端每转的驱动器位置单位数,并将换算用 `gear_ratio` 设为 `1`,避免重复乘机械减速比。
- 若设置了电子齿轮,应使用换算后的用户单位数;还需核对 `PrD.07` 对 `606C` 速度反馈来源的选择。当前协议按同一尺度处理位置和每秒速度,联调时通过小幅运动核对位置增量与速度反馈。
同川厂家操作的具体行为:
- 位置限位完整流程在 Adapter 中:写入 `607D:01/:02`,再设置 `3809:00 UINT16=1` 开启软限位,并读回验证。速度限位也由 Adapter 写入、读回 `607F` 和 `6081`;意优另外处理厂家限速对象 `2024`。
- 初始化读取 `3136:00`(Pr1.54)和 `3137:00`(Pr1.55),均为 UINT16 毫秒值,范围 0–500。同川 Adapter 完整执行使能/失能:使能后等待固定 PrF.44 的 200 ms 加 Pr1.54;失能后等待 Pr1.55,再允许后续使能。
- 强制释放抱闸先确认 `6041` 不是 Operation Enabled,再写 `381E:00 UINT16=128` 并读回。该读回只确认命令值,不能作为物理抱闸状态反馈。
- 零位校准沿用 `motor->calibrateZeroQ()`,具体流程在 `TchlMotorAdapter::calibrateZero()` 中实现:停止并失能后,将 `6098:00 INT8` 设为 35、`607C:00 INT32` 设为 0,切换 `6060=6`,按 `0006→0007→000F→001F` 将当前位置定义为零。Adapter 内部处理使能/失能延迟、完成检查、最终失能、目标 PDO 同步和软限位恢复;`TchlMotor` 只调用 Adapter。意优仍由自己的 Adapter 实现完整校准,`Cia402Protocol` 不提供厂家校准流程。
- 同川手册还给出了写 `3801:00 UINT16=5` 后断电重启的置零方式;上述接口使用方法 35,其掉电保持尚未实机验证。
### 单轴 PP 实机测试
测试入口为 `tchl_motor_real_test` 的 `TchlMotorRealTest.ProfilePosition`。默认读取同川单轴模板,可用环境变量 `TCHL_MOTOR_CONFIG` 指定配置文件。
测试使用 `MotorManager` 完成总线、电机及限位初始化,随后设置 PP 模式、使能、下发一次目标、打印反馈。目标是绝对输出轴位置 `1.57 rad`,速度 `0.5 rad/s`,加减速度 `5.0 rad/s²`;修改测试文件顶部三个常量即可。每 100 ms 打印目标、实际位置、速度和额定力矩千分比,共打印 10 秒,不自动返回起点,也不进行到位或轮廓参数读回校验。
正常结束、接口失败或收到 Ctrl+C 后,依次尝试 `quickStop`、`torqueOff`,最后停止总线。Ctrl+C 在当前阻塞接口返回后处理。
构建和列举用例:
```bash
cmake --build cmake-build-debug --target tchl_motor_real_test --parallel 4
LD_LIBRARY_PATH="$PWD/dependency/x86/third_party/grpc/v1.76.0/lib" \
cmake-build-debug/cmvr-es/devices/motor/drivers/ethercat_motor/tchl_motor_real_test --gtest_list_tests
```
以下命令会使能并移动电机,需使用实际换算参数和机械限位:
```bash
LD_LIBRARY_PATH="$PWD/dependency/x86/third_party/grpc/v1.76.0/lib" \
cmake-build-debug/cmvr-es/devices/motor/drivers/ethercat_motor/tchl_motor_real_test \
--gtest_filter=TchlMotorRealTest.ProfilePosition
```
### 单轴 CSP 正弦往返测试
入口为同一测试程序的 `TchlMotorRealTest.CyclicPositionSin`,使用同一份同川配置。参考意优 CSP 用例,采用升余弦位置和正弦速度前馈:
```text
q_target = q0 + Δq / 2 × (1 − cos(ωt))
qd_target = Δq / 2 × ω × sin(ωt)
ω = 2π / T
```
`q0` 取设置 CSP 并使能后的实际位置。当前 `Δq = 1.57 rad`、`T = 6 s`、运行两周期(12 秒),范围为 `q0` 到 `q0 + 1.57 rad`;可修改测试顶部的 `kCspExcursionRad`、`kCspPeriodS`、`kCspCycles`。开始下发前检查整个轨迹在配置的位置限位内。
下发间隔使用 `ethercat.cycle_us`(当前为 1 ms),位置经 PDO 写入 `607A`,速度前馈写入同川的 `60B1`。轨迹按实际经过时间计算,延迟后跳过错过的时刻;每 100 ms 打印目标位置、目标速度及实际位置、速度、力矩。正常结束下发起点位置和零前馈,再停止、失能;中途 Ctrl+C 直接停止、失能。
以下命令会使能并移动电机:
```bash
LD_LIBRARY_PATH="$PWD/dependency/x86/third_party/grpc/v1.76.0/lib" \
cmake-build-debug/cmvr-es/devices/motor/drivers/ethercat_motor/tchl_motor_real_test \
--gtest_filter=TchlMotorRealTest.CyclicPositionSin
```
### 单轴 PV / CSV 速度测试
同一测试文件增加两个速度用例,继续使用 `TCHL_MOTOR_CONFIG` 指定配置:
| 用例 | 目标及持续时间 | 下发方式 |
| --- | --- | --- |
| `TchlMotorRealTest.ProfileVelocity` | `0.3 rad/s`,加减速度 `1 rad/s²`,运行 2 秒;随后下发零速度并打印 1 秒 | 每个阶段调用一次 `commandProfileVelocity`;`6083/6084` 通过 SDO 配置,`60FF` 通过 PDO 下发 |
| `TchlMotorRealTest.CyclicVelocitySin` | `qd = 0.2 × sin(2πt/6) rad/s`,运行两周期(12 秒),最后下发零速度 | 按 `ethercat.cycle_us`(当前 1 ms)调用 `commandCyclicVelocity`,写入 PDO `60FF` |
可修改测试顶部的 `kPvVelocityRadS`、`kPvAccelerationRadS2`、`kPvDuration` 和 `kCsvVelocityAmplitudeRadS`、`kCsvPeriodS`、`kCsvCycles`。两个用例每 100 ms 打印目标速度、实际位置、实际速度和力矩;开始前检查预计行程及速度限位,打印反馈时检查实际位置是否越界。正常结束、接口失败或 Ctrl+C 都会执行停止和失能。
默认 PV 预计前进约 `0.6 rad`,开始前按 `0.645 rad` 预留运行及减速空间;CSV 的理想最大位移约为 `0.382 rad`,整周期积分回到起点,实际位置以反馈为准。
分别运行以下用例会使能并移动电机:
```bash
LD_LIBRARY_PATH="$PWD/dependency/x86/third_party/grpc/v1.76.0/lib" \
cmake-build-debug/cmvr-es/devices/motor/drivers/ethercat_motor/tchl_motor_real_test \
--gtest_filter=TchlMotorRealTest.ProfileVelocity
LD_LIBRARY_PATH="$PWD/dependency/x86/third_party/grpc/v1.76.0/lib" \
cmake-build-debug/cmvr-es/devices/motor/drivers/ethercat_motor/tchl_motor_real_test \
--gtest_filter=TchlMotorRealTest.CyclicVelocitySin
```
### 单轴当前位置置零测试
入口为 `TchlMotorRealTest.CalibrateZeroQ`。将机械轴放在希望定义为零点的位置后单独运行。测试调用一次 `motor->calibrateZeroQ()`,打印校准前后的实际位置、速度、力矩和模式。方法 35 内部会暂时使能,成功后保持失能、模式为 Homing;后续运动需先设置所需模式,再重新使能。
Adapter 检查启动命令已经到达驱动、状态字 bit12/bit10 已置位、bit13 无错误且实际位置接近 0。等待默认超时 2000 ms、轮询 10 ms、位置容差 100 个计数,可通过已有 `ethercat.zero_calibration` 配置覆盖。配置中的软限位会按新零点重新应用。
```bash
LD_LIBRARY_PATH="$PWD/output/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" \
./cmake-build-debug/cmvr-es/devices/motor/drivers/ethercat_motor/tchl_motor_real_test \
--gtest_filter=TchlMotorRealTest.CalibrateZeroQ
```
## 7. 编译验证
```bash
cmake -S . -B cmake-build-debug

View File

@ -81,6 +81,7 @@ enum MotorVendor {
MOTOR_VENDOR_TI5 = 1;
MOTOR_VENDOR_MUJOCO = 2;
MOTOR_VENDOR_EYOU = 3;
MOTOR_VENDOR_TCHL = 4;
}
enum MotorProtocol {