diff --git a/cmvr-es/config/devices/arm/tchl_arm.pb.txt b/cmvr-es/config/devices/arm/tchl_arm.pb.txt new file mode 100644 index 00000000..76126848 --- /dev/null +++ b/cmvr-es/config/devices/arm/tchl_arm.pb.txt @@ -0,0 +1,35 @@ +# 六轴纯关节运动配置;MoveJ 目标向量按 joint_names 的顺序填写。 +arm { + robot_arms { + id: "tchl_arm" + + motor { + motor_system_id: "tchl_joint_motors" + motor_group_ids: "tchl_joint_motors" + dof: 6 + joint_names: "TCHL_AXIS_1" + joint_names: "TCHL_AXIS_2" + joint_names: "TCHL_AXIS_3" + joint_names: "TCHL_AXIS_4" + joint_names: "TCHL_AXIS_5" + joint_names: "TCHL_AXIS_6" + upd_freq: 1000 + } + + motion { + # 保持 linbo_dev 的 TOPPRA 规划器,不引入另一分支的规划接口。 + move_j { + settle_timeout_s: 2.0 + settle_position_tolerance_rad: 0.002 + settle_velocity_tolerance_rad_s: 0.02 + settle_stable_sample_count: 3 + toppra_joint_motion_planner { + path_type: TOPPRA_PATH_TYPE_QUINTIC + sample_period_s: 0.001 + grid_size: 150 + high_grid_size: 300 + } + } + } + } +} diff --git a/cmvr-es/config/devices/motor/lingkong_motors.pb.txt b/cmvr-es/config/devices/motor/lingkong_motors.pb.txt new file mode 100644 index 00000000..f9c401c2 --- /dev/null +++ b/cmvr-es/config/devices/motor/lingkong_motors.pb.txt @@ -0,0 +1,34 @@ +# One MG6010E-i6 V3, selected by device_manager as lingkong_can_motors. +# CAN ID 1 is provisional: confirm the physical ID before hardware operation. +# Bring up can0 at the drive's configured bitrate (manual default 1 Mbps). +# All public q/qd values refer to OUTPUT shaft radians/radians per second. +motor { + id: "lingkong_motors" + motor_groups { + id: "lingkong_can_motors" + bus_type: MOTOR_BUS_CAN + vendor: MOTOR_VENDOR_LINGKONG + protocol: MOTOR_PROTOCOL_LINGKONG_CAN + can { channel_id: 0 } + motors { + motors { + id: 1 + joint_name: "MG6010E_AXIS_1" + gear_ratio: 6 + # Example SOFTWARE position/speed limits; confirm for the installation. + limit_q_lb: -3.14 + limit_q_ub: 3.14 + limit_qd: 0.5 + lingkong { + current_amp_per_lsb: 0.01611328125 # MG: 66/4096 A/LSB + response_timeout_ms: 100 + reached_position_tolerance_rad: 0.001 + # rated_torque_current_a: confirm before enabling per-mille torque APIs. + # B1 limit units are not specified by the supplied manual. Leave unset: + # acceleration_deg_s2_per_lsb / speed_limit_deg_s_per_lsb. + # Pass qdd=0 to keep existing DRIVE acceleration in motion commands. + } + } + } + } +} diff --git a/cmvr-es/config/devices/motor/tchl_motors.pb.txt b/cmvr-es/config/devices/motor/tchl_motors.pb.txt new file mode 100644 index 00000000..56672f9d --- /dev/null +++ b/cmvr-es/config/devices/motor/tchl_motors.pb.txt @@ -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 + } + } + } +} diff --git a/cmvr-es/config/devices/motor/tchl_multi_motors.pb.txt b/cmvr-es/config/devices/motor/tchl_multi_motors.pb.txt new file mode 100644 index 00000000..bc85319e --- /dev/null +++ b/cmvr-es/config/devices/motor/tchl_multi_motors.pb.txt @@ -0,0 +1,61 @@ +# 同川 TC600E TR 七轴模板;设备管理器默认不启用。 +# 各轴按实机确认 PrD.00、电子齿轮、编码器分辨率和减速比。 +# 以下 131072 / 101 仅为 PrD.00=0、电子齿轮 1:1 的配置示例。 +motor { + id: "tchl_motors" + + motor_groups { + id: "tchl_joint_motors" + 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 } + + slaves { motor_id: 1 alias: 0 position: 0 } + slaves { motor_id: 2 alias: 0 position: 1 } + slaves { motor_id: 3 alias: 0 position: 2 } + slaves { motor_id: 4 alias: 0 position: 3 } + slaves { motor_id: 5 alias: 0 position: 4 } + slaves { motor_id: 6 alias: 0 position: 5 } + + } + + # 示例限位;启用设备前按各轴实际行程和允许速度、加速度填写。 + # q: rad,qd: rad/s,qdd: rad/s^2。 + joint_limits { + enable: true + source: JOINT_LIMIT_SOURCE_CUSTOM + joints { joint_name: "TCHL_AXIS_1" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 } + joints { joint_name: "TCHL_AXIS_2" q_lb: -1.96 q_ub: 2.02 qd: 5.0 qdd: 10.0 } + joints { joint_name: "TCHL_AXIS_3" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 } + joints { joint_name: "TCHL_AXIS_4" q_lb: -2.04 q_ub: 1.10 qd: 5.0 qdd: 10.0 } + joints { joint_name: "TCHL_AXIS_5" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 } + joints { joint_name: "TCHL_AXIS_6" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 } + + } + + motors { + motors { id: 1 joint_name: "TCHL_AXIS_1" encoder_counts_per_rev: 131072 gear_ratio: 101 } + motors { id: 2 joint_name: "TCHL_AXIS_2" encoder_counts_per_rev: 131072 gear_ratio: 101 } + motors { id: 3 joint_name: "TCHL_AXIS_3" encoder_counts_per_rev: 131072 gear_ratio: 101 } + motors { id: 4 joint_name: "TCHL_AXIS_4" encoder_counts_per_rev: 131072 gear_ratio: 101 } + motors { id: 5 joint_name: "TCHL_AXIS_5" encoder_counts_per_rev: 131072 gear_ratio: 101 } + motors { id: 6 joint_name: "TCHL_AXIS_6" encoder_counts_per_rev: 131072 gear_ratio: 101 } + + } + } +} diff --git a/cmvr-es/config/manager/device_manager.pb.txt b/cmvr-es/config/manager/device_manager.pb.txt index 3f23a797..8eaa95b4 100644 --- a/cmvr-es/config/manager/device_manager.pb.txt +++ b/cmvr-es/config/manager/device_manager.pb.txt @@ -119,7 +119,7 @@ device_manager { id: "right_arm_ethercat_motors" type: DEVICE_TYPE_MOTOR_SYSTEM config_file: "devices/motor/ethercat_single_arm_motors.pb.txt" - enable: true + enable: false } devices { @@ -217,7 +217,7 @@ device_manager { id: "right_ethercat_arm" type: DEVICE_TYPE_ROBOT_ARM config_file: "devices/arm/ethercat_single_arm.pb.txt" - enable: true + enable: false } devices { @@ -227,4 +227,29 @@ device_manager { enable: false } + devices { + id: "tchl_single_axis" + type: DEVICE_TYPE_MOTOR_SYSTEM + config_file: "devices/motor/tchl_motors.pb.txt" + enable: false + } + devices { + id: "lingkong_can_motors" + type: DEVICE_TYPE_MOTOR_SYSTEM + config_file: "devices/motor/lingkong_motors.pb.txt" + enable: false + } + devices { + id: "tchl_joint_motors" + type: DEVICE_TYPE_MOTOR_SYSTEM + config_file: "devices/motor/tchl_multi_motors.pb.txt" + enable: true + } + devices { + id: "tchl_arm" + type: DEVICE_TYPE_ROBOT_ARM + config_file: "devices/arm/tchl_arm.pb.txt" + enable: true + } + } diff --git a/cmvr-es/devices/motor/CMakeLists.txt b/cmvr-es/devices/motor/CMakeLists.txt index c3081330..b7d7c87f 100644 --- a/cmvr-es/devices/motor/CMakeLists.txt +++ b/cmvr-es/devices/motor/CMakeLists.txt @@ -14,6 +14,7 @@ target_link_libraries(motor_core add_library(cmvr_es::device::motor_core ALIAS motor_core) add_subdirectory(drivers/ti5_canopen) +add_subdirectory(drivers/lingkong_can) add_subdirectory(drivers/mujoco) add_subdirectory(bus_runtime) add_subdirectory(drivers/ethercat_motor) diff --git a/cmvr-es/devices/motor/abstract_motor.h b/cmvr-es/devices/motor/abstract_motor.h index ed737f2e..a0124f78 100644 --- a/cmvr-es/devices/motor/abstract_motor.h +++ b/cmvr-es/devices/motor/abstract_motor.h @@ -6,13 +6,12 @@ #define CMVR_ES_ABSTRACT_MOTOR_H #pragma once - #include -#include #include "devices/abstract_device.h" #include "common/base/logging/logger.h" #include "motor/motor_protocol_interface.h" +#include namespace cmvr::device{ @@ -23,6 +22,7 @@ namespace cmvr::device{ } MotorProfile; + public: struct MotorInfo { int id; std::string joint_name; @@ -32,6 +32,7 @@ namespace cmvr::device{ double limit_qdd; }; + private: typedef struct { double position; double velocity; @@ -86,22 +87,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_) { @@ -112,22 +99,16 @@ 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() { + // deceleration: positive output-axis rad/s^2. + virtual bool quickStop(double deceleration = 5.0) { std::scoped_lock lock(mtx_); if (!protocol_) { CMVR_LOG(ERROR) << "Protocol not set for motor"; return false; } - return protocol_->quickStop(node_id_); + return protocol_->quickStop(node_id_, deceleration); } virtual bool commandProfilePosition(double target_q, double max_qd = 0.0, @@ -149,6 +130,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_); @@ -168,6 +159,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_) { @@ -177,14 +169,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_) { @@ -214,9 +199,17 @@ namespace cmvr::device{ return protocol_->getQd(node_id_); } - // Returns the actual motor current in mA when supported by the driver. - virtual std::int16_t getCurrent() { - return 0; + // Keep the existing arm-current telemetry contract alongside torque. + virtual std::int16_t getCurrent() { return 0; } + + // 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::quiet_NaN(); + } + return protocol_->getTau(node_id_); } @@ -237,6 +230,22 @@ namespace cmvr::device{ std::string jointName() const { return info_.joint_name; } + // Cached metadata and configured limits; does not read the drive. + MotorInfo motorInfo() const { + std::scoped_lock lock(mtx_); + return info_; + } + // Optional diagnostic status; unsupported drivers must not report a fake zero. + virtual bool readDriveStatus(std::uint16_t&, std::uint16_t&) { return false; } + // Default CiA402 interpretation; non-CiA402 drivers override using their + // real native status, rather than fabricating a CiA402 status word. + virtual bool readDiagnosticState(std::uint16_t& status, std::uint16_t& error, + bool& enabled, bool& fault) { + if (!readDriveStatus(status, error)) return false; + enabled = (status & 0x006f) == 0x0027; + fault = (status & 0x0008) != 0; + return true; + } protected: mutable std::mutex mtx_; MotorInfo info_{}; diff --git a/cmvr-es/devices/motor/bus_runtime/can/include/can_motor_bus_runtime.h b/cmvr-es/devices/motor/bus_runtime/can/include/can_motor_bus_runtime.h index 9158a018..477b92b5 100644 --- a/cmvr-es/devices/motor/bus_runtime/can/include/can_motor_bus_runtime.h +++ b/cmvr-es/devices/motor/bus_runtime/can/include/can_motor_bus_runtime.h @@ -29,6 +29,7 @@ public: const std::string& id() const { return id_; } std::shared_ptr> sender() const { return sender_; } + std::shared_ptr client() const { return client_; } std::shared_ptr> messageManager() const { return message_manager_; } private: diff --git a/cmvr-es/devices/motor/bus_runtime/ethercat/include/ethercat_motor_bus_runtime.h b/cmvr-es/devices/motor/bus_runtime/ethercat/include/ethercat_motor_bus_runtime.h index 21727952..7effd655 100644 --- a/cmvr-es/devices/motor/bus_runtime/ethercat/include/ethercat_motor_bus_runtime.h +++ b/cmvr-es/devices/motor/bus_runtime/ethercat/include/ethercat_motor_bus_runtime.h @@ -24,6 +24,7 @@ namespace cmvr::device { class EthercatMotorBusRuntime final : public AbstractMotorBusRuntime { public: + ~EthercatMotorBusRuntime() override; struct PdoWrite { int motor_id{0}; std::uint16_t index{0}; diff --git a/cmvr-es/devices/motor/bus_runtime/ethercat/include/ethercat_pdo_mapping.h b/cmvr-es/devices/motor/bus_runtime/ethercat/include/ethercat_pdo_mapping.h index 30db0781..850bed8b 100644 --- a/cmvr-es/devices/motor/bus_runtime/ethercat/include/ethercat_pdo_mapping.h +++ b/cmvr-es/devices/motor/bus_runtime/ethercat/include/ethercat_pdo_mapping.h @@ -28,6 +28,10 @@ struct EthercatPdoMapping { std::string name; std::vector rx_pdos; std::vector 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 diff --git a/cmvr-es/devices/motor/bus_runtime/ethercat/src/ethercat_motor_bus_runtime.cpp b/cmvr-es/devices/motor/bus_runtime/ethercat/src/ethercat_motor_bus_runtime.cpp index be1ad688..59ce4cf0 100644 --- a/cmvr-es/devices/motor/bus_runtime/ethercat/src/ethercat_motor_bus_runtime.cpp +++ b/cmvr-es/devices/motor/bus_runtime/ethercat/src/ethercat_motor_bus_runtime.cpp @@ -15,6 +15,11 @@ namespace cmvr::device { +EthercatMotorBusRuntime::~EthercatMotorBusRuntime() +{ + stop(); +} + bool EthercatMotorBusRuntime::init(const config::MotorGroupConfig& group_cfg) { id_ = group_cfg.id(); diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/CMakeLists.txt b/cmvr-es/devices/motor/drivers/ethercat_motor/CMakeLists.txt index 36685aeb..824da8b9 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/CMakeLists.txt +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/CMakeLists.txt @@ -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,16 @@ 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 + gtest + gtest_main + pthread + glog +) diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h b/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h index f0903a91..6affcac1 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h @@ -28,21 +28,32 @@ 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 { + std::uint8_t node_id{0}; + 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 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; + // Uses abs(max_qd) in rad/s; zero or non-finite speeds send no command. bool commandProfilePosition(std::uint8_t node_id, double target_q, double max_qd, @@ -50,12 +61,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 readFeedbacksAtomic(MotorFeedback* feedbacks, std::size_t count) const; + bool commandCyclicPositionsAtomic(const std::vector& commands); + bool commandCyclicVelocitiesAtomic(const std::vector& commands); + bool commandCyclicTorquesAtomic(const std::vector& commands); + // Caller supplies node_id in each element; all feedback uses one PDO snapshot. + bool readFeedbacksAtomic(std::vector& feedbacks) const; bool commandCyclicVelocity(std::uint8_t node_id, double target_qd) override; bool commandCyclicTorque(std::uint8_t node_id, double target_tau) override; @@ -64,12 +80,13 @@ 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; + // Position/velocity modes use 6085, then disable the drive (605A = 2). + bool quickStop(std::uint8_t node_id, double deceleration = 5.0) 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; + bool readDriveStatus(std::uint8_t node_id,std::uint16_t& status,std::uint16_t& error) const; private: struct NodeState { @@ -81,9 +98,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}; @@ -91,9 +105,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; @@ -103,11 +116,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, @@ -119,8 +133,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, @@ -134,14 +146,14 @@ 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 bus_runtime_; std::unique_ptr status_monitor_; config::Cia402ProtocolConfig config_; + const std::uint16_t velocity_feedforward_; std::unordered_map nodes_; - std::mutex cyclic_position_mutex_; - std::vector cyclic_position_writes_; + std::mutex cyclic_command_mutex_; + std::vector cyclic_command_writes_; }; } // namespace cmvr::device diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_status_monitor.h b/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_status_monitor.h index 3a92a7df..2d23cf83 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_status_monitor.h +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_status_monitor.h @@ -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, diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/include/ethercat_motor.h b/cmvr-es/devices/motor/drivers/ethercat_motor/include/ethercat_motor.h new file mode 100644 index 00000000..8117797c --- /dev/null +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/include/ethercat_motor.h @@ -0,0 +1,58 @@ +#ifndef CMVR_ES_ETHERCAT_MOTOR_H +#define CMVR_ES_ETHERCAT_MOTOR_H + +#include +#include +#include + +#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 cia402_protocol); + bool readDriveStatus(std::uint16_t& status,std::uint16_t& error) override { + std::scoped_lock lock(mtx_); + return cia402_protocol_ && cia402_protocol_->readDriveStatus(node_id_,status,error); + } + + static bool commandCyclicPositionsAtomic( + const std::vector>& motors, + const std::vector& positions, + const std::vector& velocities); + static bool readFeedbacksAtomic( + const std::vector>& motors, + std::vector& positions, + std::vector& velocities); + // Torques are per mille of rated torque: 1000 equals rated torque. + static bool readFeedbacksAtomic( + const std::vector>& motors, + std::vector& positions, + std::vector& velocities, + std::vector& torques); + static bool commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities); + // Torques are per mille of rated torque: 1000 equals rated torque. + static bool commandCyclicTorquesAtomic( + const std::vector>& motors, + const std::vector& 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 cia402_protocol_; + double encoder_counts_per_rev_{0.0}; + double gear_ratio_{0.0}; +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_ETHERCAT_MOTOR_H diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_cia402_pdo_mapping.h b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_cia402_pdo_mapping.h index 69d30288..638e9f37 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_cia402_pdo_mapping.h +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_cia402_pdo_mapping.h @@ -72,6 +72,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; diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h index d4247105..df10b8e8 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h @@ -3,16 +3,13 @@ #include #include -#include -#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 cia402_protocol, @@ -20,35 +17,20 @@ 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; std::int16_t getCurrent() override; - static bool commandCyclicPositionsAtomic( - const std::vector>& motors, - const std::vector& positions, - const std::vector& velocities); - static bool readFeedbacksAtomic( - const std::vector>& motors, - std::vector& positions, - std::vector& velocities); - private: - bool hasDependencies_() const; - bool hasValidConversion_() const; + bool hasDependencies_() const override; + void configureCurrentConversion_(); + double current_scale_ma_per_count_{1.0}; bool writeVendorPositionLimits_() const; bool writeVendorVelocityLimit_() const; - void configureCurrentConversion_(); - std::int32_t radToCounts_(double angle_rad) const; - std::uint32_t radPerSecToCounts_(double velocity_rad_s) const; - std::shared_ptr cia402_protocol_; std::unique_ptr vendor_adapter_; - double encoder_counts_per_rev_{0.0}; - double gear_ratio_{0.0}; - double current_scale_ma_per_count_{1.0}; }; } // namespace cmvr::device diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor_adapter.h b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor_adapter.h index cf85e802..5893446f 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor_adapter.h +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor_adapter.h @@ -4,6 +4,8 @@ #include #include #include +#include +#include #include "devices/motor/bus_runtime/ethercat/include/ethercat_motor_bus_runtime.h" #include "devices/motor/drivers/ethercat_motor/include/vendor/motor_vendor_adapter.h" @@ -25,14 +27,15 @@ public: std::int64_t counts_per_joint_revolution, std::int32_t& zeroed_position) override; bool brakeRelease(std::uint8_t node_id) override; - bool readActualCurrent(std::uint8_t node_id, - std::int16_t& current_value) const; - bool readMotorIdentity(std::uint8_t node_id, - std::string& motor_model, - std::string& motor_version) const; + bool readActualCurrent(std::uint8_t node_id, std::int16_t& current_value) const; + bool readMotorIdentity(std::uint8_t node_id, std::string& model, std::string& version) const; private: + bool syncTargetToActualPosition_(std::uint8_t node_id, + std::int32_t& actual_position) const; + std::shared_ptr bus_runtime_; + std::optional> position_limits_; }; } // namespace cmvr::device diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/motor_vendor_adapter.h b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/motor_vendor_adapter.h index 7eb65f95..beccf377 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/motor_vendor_adapter.h +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/motor_vendor_adapter.h @@ -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; diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_cia402_pdo_mapping.h b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_cia402_pdo_mapping.h new file mode 100644 index 00000000..77007715 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_cia402_pdo_mapping.h @@ -0,0 +1,79 @@ +#ifndef CMVR_ES_TCHL_CIA402_PDO_MAPPING_H +#define CMVR_ES_TCHL_CIA402_PDO_MAPPING_H + +#include +#include +#include + +#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 diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_motor.h b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_motor.h new file mode 100644 index 00000000..72625384 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_motor.h @@ -0,0 +1,36 @@ +#ifndef CMVR_ES_TCHL_MOTOR_H +#define CMVR_ES_TCHL_MOTOR_H + +#include + +#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 cia402_protocol, + std::unique_ptr 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 vendor_adapter_; +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_TCHL_MOTOR_H diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_motor_adapter.h b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_motor_adapter.h new file mode 100644 index 00000000..1cc362a6 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_motor_adapter.h @@ -0,0 +1,51 @@ +#ifndef CMVR_ES_TCHL_MOTOR_ADAPTER_H +#define CMVR_ES_TCHL_MOTOR_ADAPTER_H + +#include +#include +#include + +#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 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 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 diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_protocol.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_protocol.cpp index a621ddda..7f29df6c 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_protocol.cpp +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_protocol.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -17,10 +18,11 @@ namespace cmvr::device { Cia402Protocol::Cia402Protocol(std::shared_ptr 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_position_writes_.reserve(512); + cyclic_command_writes_.reserve(512); status_monitor_ = std::make_unique( bus_runtime_, std::chrono::milliseconds(config_.status_poll_period_ms())); } @@ -35,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(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; } @@ -55,17 +54,25 @@ bool Cia402Protocol::commandProfilePosition(const std::uint8_t node_id, const double max_qd, const double max_qdd) { - auto& state = nodeState_(node_id); - if (!hasValidConversion_(node_id, state) || - !status_monitor_->isNodeOperational(node_id)) { + if (!std::isfinite(max_qd) || max_qd == 0.0) { + CMVR_LOG(ERROR) << "[Cia402Protocol] profile velocity must be finite and nonzero, node=" + << static_cast(node_id) << ", max_qd=" << max_qd; return false; } + auto& state = nodeState_(node_id); + if (!hasValidConversion_(node_id, state) || + !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)); + state.profile_velocity = radPerSecToCounts_(std::abs(max_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 writeProfilePositionTarget_(node_id, state); } @@ -76,44 +83,78 @@ 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( + node_id, msgs::CIA402_PROFILE_ACCELERATION_6083, 0x00, + static_cast(state.profile_acceleration)) || + !bus_runtime_->writeSdo( + node_id, msgs::CIA402_PROFILE_DECELERATION_6084, 0x00, + static_cast(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( + node_id, msgs::CIA402_TORQUE_SLOPE_6087, 0x00, torque_slope) || + !bus_runtime_->writePdo( + 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 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& 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 lock(cyclic_position_mutex_); - cyclic_position_writes_.clear(); - cyclic_position_writes_.reserve(count * 2); + std::lock_guard lock(cyclic_command_mutex_); + cyclic_command_writes_.clear(); + cyclic_command_writes_.reserve(count * 2); for (std::size_t i = 0; i < count; ++i) { 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) { @@ -122,41 +163,42 @@ bool Cia402Protocol::commandCyclicPositionsAtomic( } } - cyclic_position_writes_.push_back( + cyclic_command_writes_.push_back( EthercatMotorBusRuntime::makePdoWrite( command.node_id, msgs::CIA402_TARGET_POSITION_607A, 0x00, radToCounts_(command.target_q, *state))); - cyclic_position_writes_.push_back( + cyclic_command_writes_.push_back( EthercatMotorBusRuntime::makePdoWrite( command.node_id, - msgs::CIA402_TARGET_VELOCITY_60FF, + velocity_feedforward_, 0x00, radPerSecToCounts_(command.target_qd, *state))); } - if (!bus_runtime_->writePdosAtomic(cyclic_position_writes_.data(), - cyclic_position_writes_.size())) { + if (!bus_runtime_->writePdosAtomic(cyclic_command_writes_.data(), + cyclic_command_writes_.size())) { return false; } 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& 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 reads{}; + std::array 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)) { @@ -167,13 +209,15 @@ bool Cia402Protocol::readFeedbacksAtomic(MotorFeedback* feedbacks, return false; } } - reads[2 * i] = EthercatMotorBusRuntime::makePdoRead( + reads[3 * i] = EthercatMotorBusRuntime::makePdoRead( feedbacks[i].node_id, msgs::CIA402_ACTUAL_POSITION_6064, 0x00); - reads[2 * i + 1] = EthercatMotorBusRuntime::makePdoRead( + reads[3 * i + 1] = EthercatMotorBusRuntime::makePdoRead( feedbacks[i].node_id, msgs::CIA402_ACTUAL_VELOCITY_606C, 0x00); + reads[3 * i + 2] = EthercatMotorBusRuntime::makePdoRead( + 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; } @@ -182,11 +226,60 @@ bool Cia402Protocol::readFeedbacksAtomic(MotorFeedback* feedbacks, if (!state) { return false; } - const auto position = EthercatMotorBusRuntime::pdoReadValue(reads[2 * i]); + const auto position = EthercatMotorBusRuntime::pdoReadValue(reads[3 * i]); const auto velocity = - EthercatMotorBusRuntime::pdoReadValue(reads[2 * i + 1]); + EthercatMotorBusRuntime::pdoReadValue(reads[3 * i + 1]); feedbacks[i].q = countsToRad_(position, *state); feedbacks[i].qd = countsToRadPerSec_(velocity, *state); + feedbacks[i].tau = + EthercatMotorBusRuntime::pdoReadValue(reads[3 * i + 2]); + } + return true; +} + +bool Cia402Protocol::commandCyclicVelocitiesAtomic( + const std::vector& commands) +{ + const auto count = commands.size(); + if (!bus_runtime_ || commands.empty() || count > 256) { + return false; + } + std::lock_guard lock(cyclic_command_mutex_); + cyclic_command_writes_.clear(); + cyclic_command_writes_.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + const auto& command = commands[i]; + const auto* state = findNodeState_(command.node_id); + if (!std::isfinite(command.target_qd) || !state || + !hasValidConversion_(command.node_id, *state) || + !status_monitor_->isNodeOperational(command.node_id, 9)) { + return false; + } + for (std::size_t previous = 0; previous < i; ++previous) { + if (commands[previous].node_id == command.node_id) { + return false; + } + } + const double counts = command.target_qd / (2.0 * M_PI) * + state->gear_ratio * state->encoder_counts_per_rev; + if (!std::isfinite(counts) || + counts < std::numeric_limits::min() || + counts > std::numeric_limits::max()) { + return false; + } + cyclic_command_writes_.push_back( + EthercatMotorBusRuntime::makePdoWrite( + command.node_id, msgs::CIA402_TARGET_VELOCITY_60FF, 0x00, + radPerSecToCounts_(command.target_qd, *state))); + } + // The bus validates every PDO before changing the shared output frame. + if (!bus_runtime_->writePdosAtomic(cyclic_command_writes_.data(), count)) { + return false; + } + 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; } @@ -194,33 +287,84 @@ bool Cia402Protocol::readFeedbacksAtomic(MotorFeedback* feedbacks, bool Cia402Protocol::commandCyclicVelocity(const std::uint8_t node_id, const double target_qd) { - auto& state = nodeState_(node_id); - if (!hasValidConversion_(node_id, state) || - !status_monitor_->isNodeOperational(node_id)) { - return false; - } - state.target_velocity = radPerSecToCounts_(target_qd, state); - return writeTargetsForMode_(node_id, state.mode, state); + thread_local std::vector commands(1); + commands.front() = {node_id, target_qd}; + return commandCyclicVelocitiesAtomic(commands); +} + +bool Cia402Protocol::readDriveStatus(std::uint8_t id,std::uint16_t& status,std::uint16_t& error) const +{ + if (!bus_runtime_) return false; + using Bus=EthercatMotorBusRuntime; + std::array reads{{Bus::makePdoRead(id,0x6041,0),Bus::makePdoRead(id,0x603f,0)}}; + if (!bus_runtime_->readPdosAtomic(reads.data(),reads.size())) return false; + status=Bus::pdoReadValue(reads[0]);error=Bus::pdoReadValue(reads[1]); + return true; } 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(node_id); - return false; + thread_local std::vector commands(1); + commands.front() = {node_id, target_tau}; + return commandCyclicTorquesAtomic(commands); +} + +bool Cia402Protocol::commandCyclicTorquesAtomic( + const std::vector& commands) +{ + if (!bus_runtime_ || commands.empty() || commands.size() > 256) { + return false; + } + std::lock_guard 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( + 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::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 writes{}; + std::size_t count = 0; + writes[count++] = EthercatMotorBusRuntime::makePdoWrite( + 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(node_id) << ", mode=" << static_cast(mode); return false; @@ -232,7 +376,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; } @@ -251,35 +397,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(node_id); - return false; -} - bool Cia402Protocol::reachedTargetQ(const std::uint8_t node_id) { std::uint16_t statusword = 0; @@ -305,7 +422,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) { @@ -316,17 +432,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(node_id); return false; } - if (!bus_runtime_->writePdo(node_id, msgs::CIA402_OPERATION_MODE_6060, 0x00, - toCia402Mode_(state.mode))) { + if (!prepareSafeTargetsForMode_(node_id, state.mode, state) || + !bus_runtime_->writePdo(node_id, velocity_feedforward_, 0x00, 0) || + !writeTargetsForMode_(node_id, state.mode, state)) { return false; } @@ -340,27 +456,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) @@ -369,8 +467,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; @@ -414,32 +514,41 @@ 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(node_id); - return false; -} - -bool Cia402Protocol::quickStop(const std::uint8_t node_id) +bool Cia402Protocol::quickStop(const std::uint8_t node_id, const double deceleration) { if (!bus_runtime_) { return false; } - status_monitor_->setExpectedOperationEnabled(node_id, false); auto& state = nodeState_(node_id); - state.target_velocity = 0; - state.target_torque = 0; - if (!writeTargetsForMode_(node_id, state.mode, state)) { + if (!std::isfinite(deceleration) || deceleration <= 0.0 || + !hasValidConversion_(node_id, state)) { return false; } - + const double deceleration_counts = std::round( + deceleration / (2.0 * M_PI) * state.gear_ratio * state.encoder_counts_per_rev); + if (!std::isfinite(deceleration_counts) || deceleration_counts < 1.0 || + deceleration_counts > std::numeric_limits::max()) { + return false; + } + const bool parameters_written = + bus_runtime_->writeSdo( + node_id, msgs::CIA402_QUICK_STOP_DECELERATION_6085, 0x00, + static_cast(deceleration_counts)) && + bus_runtime_->writeSdo( + node_id, msgs::CIA402_QUICK_STOP_OPTION_605A, 0x00, 2); + if (!parameters_written) { + CMVR_LOG(ERROR) << "[Cia402Protocol] failed to configure quick stop, node=" + << static_cast(node_id); + } + // Let the drive apply its configured stop ramp; do not step cyclic targets to zero. + // Still request a stop if SDO configuration failed, and report the failure. state.controlword = cia402::quickStopControlword(); if (!writeControlword_(node_id, state.controlword)) { return false; } - return waitVelocityNearZero_(node_id, "quickStop"); + const bool stopped = waitVelocityNearZero_(node_id, "quickStop"); + return parameters_written && stopped; } double Cia402Protocol::getQ(const std::uint8_t node_id) @@ -468,20 +577,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(node_id); - return false; + std::int16_t actual_torque = 0; + if (!bus_runtime_ || !bus_runtime_->readPdo( + node_id, msgs::CIA402_ACTUAL_TORQUE_6077, 0x00, actual_torque)) { + return std::numeric_limits::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) @@ -491,6 +594,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: @@ -511,6 +616,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: @@ -524,36 +631,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::min() || + target_tau > std::numeric_limits::max()) { + return false; + } + raw = static_cast(std::llround(target_tau)); + return true; +} + std::int32_t Cia402Protocol::radToCounts_(const double angle_rad, const NodeState& state) const { @@ -623,46 +716,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(node_id) - << ": " << entry.name - << " 0x" << std::hex << entry.index - << ":" << static_cast(entry.subindex) << std::dec; - return false; - } - } - return true; -} - bool Cia402Protocol::readStatusword_(const std::uint8_t node_id, std::uint16_t& statusword) const { @@ -695,6 +748,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( + node_id, msgs::CIA402_PROFILE_ACCELERATION_6083, 0x00, acceleration) || + !bus_runtime_->readSdo( + node_id, msgs::CIA402_PROFILE_DECELERATION_6084, 0x00, deceleration) || + acceleration > static_cast(std::numeric_limits::max()) || + deceleration > static_cast(std::numeric_limits::max())) { + return false; + } + state.profile_acceleration = static_cast(acceleration); + state.profile_deceleration = static_cast(deceleration); + return true; +} + bool Cia402Protocol::writeControlword_(const std::uint8_t node_id, const cia402::Controlword controlword) { @@ -815,59 +898,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(node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, - 0x01, lower_limit) && - bus_runtime_->writeSdo(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(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::abs(radPerSecToCounts_(state.limit_qd, state))); - const bool ok = - bus_runtime_->writeSdo(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(node_id) - << ", velocity_limit=" << velocity_limit; - } - return ok; -} - bool Cia402Protocol::writeAccelerationLimitsToDictionary_( const std::uint8_t node_id, const NodeState& state) const @@ -901,13 +931,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( + node_id, msgs::CIA402_PROFILE_VELOCITY_6081, 0x00, + static_cast(state.profile_velocity)) || + !bus_runtime_->writeSdo( + node_id, msgs::CIA402_PROFILE_ACCELERATION_6083, 0x00, + static_cast(state.profile_acceleration)) || + !bus_runtime_->writeSdo( + node_id, msgs::CIA402_PROFILE_DECELERATION_6084, 0x00, + static_cast(state.profile_deceleration))) { + return false; } if (!writeTargetsForMode_(node_id, state.mode, state)) { @@ -957,6 +990,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: @@ -964,6 +998,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( + node_id, velocity_feedforward_, 0x00, 0))) { + CMVR_LOG(ERROR) << "[Cia402Protocol] failed to clear velocity feedforward" + << " before switching mode, node=" << static_cast(node_id); + return false; + } + return true; } @@ -1011,27 +1054,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( - 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( - 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( - node_id, msgs::CIA402_PROFILE_DECELERATION_6084, - 0x00, state.profile_deceleration))) { - return false; - } - } break; case msgs::RUN_MODE_PROFILE_VELOCITY: @@ -1040,20 +1062,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( - 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( - node_id, msgs::CIA402_PROFILE_DECELERATION_6084, - 0x00, state.profile_deceleration))) { - return false; - } - } break; case msgs::RUN_MODE_CYCLIC_SYNC_POSITION: @@ -1061,7 +1069,7 @@ bool Cia402Protocol::appendTargetWritesForMode_( node_id, msgs::CIA402_TARGET_POSITION_607A, 0x00, state.target_position)) || !append(EthercatMotorBusRuntime::makePdoWrite( - node_id, msgs::CIA402_TARGET_VELOCITY_60FF, + node_id, velocity_feedforward_, 0x00, state.target_velocity))) { return false; } @@ -1075,6 +1083,7 @@ bool Cia402Protocol::appendTargetWritesForMode_( } break; + case msgs::RUN_MODE_TORQUE: case msgs::RUN_MODE_CYCLIC_SYNC_CURRENT: if (!append(EthercatMotorBusRuntime::makePdoWrite( node_id, msgs::CIA402_TARGET_TORQUE_6071, @@ -1086,38 +1095,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 writes{}; - std::size_t count = 0; - writes[count++] = EthercatMotorBusRuntime::makePdoWrite( - node_id, msgs::CIA402_CONTROL_WORD_6040, 0x00, state.controlword.value); - writes[count++] = EthercatMotorBusRuntime::makePdoWrite( - 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 diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_status_monitor.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_status_monitor.cpp index 1e0eeb5f..3f3bd7e5 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_status_monitor.cpp +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_status_monitor.cpp @@ -34,38 +34,22 @@ void Cia402StatusMonitor::addNode(const std::uint8_t node_id) std::lock_guard 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 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 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, 256> nodes{}; + std::array nodes{}; std::size_t node_count = 0; { std::lock_guard 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 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; } diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/ethercat_motor.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/ethercat_motor.cpp new file mode 100644 index 00000000..47282bd3 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/ethercat_motor.cpp @@ -0,0 +1,260 @@ +#include "devices/motor/drivers/ethercat_motor/include/ethercat_motor.h" + +#include +#include +#include +#include +#include +#include + +#include "common/base/logging/logger.h" + +namespace cmvr::device { + +EthercatMotor::EthercatMotor(const config::MotorConfigItem& config, + std::shared_ptr 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(info_.id); + id_ = info_.joint_name; + protocol_ = cia402_protocol_; +} + +bool EthercatMotor::commandCyclicPositionsAtomic( + const std::vector>& motors, + const std::vector& positions, + const std::vector& velocities) +{ + if (motors.empty() || motors.size() != positions.size() || + motors.size() != velocities.size() || motors.size() > 256) { + return false; + } + + std::array lock_order{}; + thread_local std::vector commands; + commands.reserve(256); + commands.resize(motors.size()); + std::shared_ptr protocol; + for (std::size_t i = 0; i < motors.size(); ++i) { + const auto motor = std::dynamic_pointer_cast(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{}); + std::array, 256> locks{}; + for (std::size_t i = 0; i < motors.size(); ++i) { + locks[i] = std::unique_lock(lock_order[i]->mtx_); + } + return protocol && protocol->commandCyclicPositionsAtomic(commands); +} + +bool EthercatMotor::commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities) +{ + if (motors.empty() || motors.size() != velocities.size() || motors.size() > 256) { + return false; + } + std::array lock_order{}; + thread_local std::vector commands; + commands.reserve(256); + commands.resize(motors.size()); + std::shared_ptr protocol; + for (std::size_t i = 0; i < motors.size(); ++i) { + const auto motor = std::dynamic_pointer_cast(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{}); + std::array, 256> locks{}; + for (std::size_t i = 0; i < motors.size(); ++i) { + locks[i] = std::unique_lock(lock_order[i]->mtx_); + } + return protocol->commandCyclicVelocitiesAtomic(commands); +} + +bool EthercatMotor::commandCyclicTorquesAtomic( + const std::vector>& motors, + const std::vector& torques) +{ + if (motors.empty() || motors.size() != torques.size() || motors.size() > 256) { + return false; + } + std::array lock_order{}; + thread_local std::vector commands; + commands.reserve(256); + commands.resize(motors.size()); + std::shared_ptr protocol; + for (std::size_t i = 0; i < motors.size(); ++i) { + const auto motor = std::dynamic_pointer_cast(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{}); + std::array, 256> locks{}; + for (std::size_t i = 0; i < motors.size(); ++i) { + locks[i] = std::unique_lock(lock_order[i]->mtx_); + } + return protocol->commandCyclicTorquesAtomic(commands); +} + +bool EthercatMotor::readFeedbacksAtomic( + const std::vector>& motors, + std::vector& positions, + std::vector& velocities) +{ + thread_local std::vector torques; + torques.reserve(256); + return readFeedbacksAtomic(motors, positions, velocities, torques); +} + +bool EthercatMotor::readFeedbacksAtomic( + const std::vector>& motors, + std::vector& positions, + std::vector& velocities, + std::vector& torques) +{ + if (motors.empty() || motors.size() > 256 || &positions == &velocities || + &positions == &torques || &velocities == &torques) { + return false; + } + + std::array lock_order{}; + thread_local std::vector feedbacks; + feedbacks.reserve(256); + feedbacks.resize(motors.size()); + std::shared_ptr protocol; + for (std::size_t i = 0; i < motors.size(); ++i) { + const auto motor = std::dynamic_pointer_cast(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{}); + std::array, 256> locks{}; + for (std::size_t i = 0; i < motors.size(); ++i) { + locks[i] = std::unique_lock(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::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::llround(rev_per_sec * gear_ratio_ * encoder_counts_per_rev_)); +} + +} // namespace cmvr::device diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor.cpp index b153112a..04958a55 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor.cpp +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor.cpp @@ -1,53 +1,24 @@ #include "devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h" -#include -#include #include -#include -#include +#include #include #include -#include #include +#include +#include #include #include "common/base/logging/logger.h" namespace cmvr::device { -namespace { - -struct MotorCurrentInfo { - double adc_amperes_per_count; - double rated_current_amperes; -}; - -const std::map kMotorCurrentMap = { - {"EuPH11", {0.005371094, 3.8}}, - {"EuPH14", {0.007672991, 3.9}}, - {"EuPH17", {0.007672991, 3.9}}, - {"EuPH20", {0.013427734, 6.9}}, -}; - -} // namespace - EyouMotor::EyouMotor(const config::MotorConfigItem& config, std::shared_ptr cia402_protocol, std::unique_ptr 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(info_.id); - id_ = info_.joint_name; - protocol_ = cia402_protocol_; } bool EyouMotor::init() @@ -57,6 +28,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; @@ -66,9 +38,6 @@ bool EyouMotor::init() return false; } configureCurrentConversion_(); - cia402_protocol_->setMotorConversion(node_id_, encoder_counts_per_rev_, gear_ratio_); - - cia402_protocol_->setLimitQd(node_id_, info_.limit_qd); if (!writeVendorVelocityLimit_()) { return false; } @@ -81,26 +50,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() @@ -113,114 +81,8 @@ bool EyouMotor::calibrateZeroQ() const auto counts_per_joint_revolution = static_cast( 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>& motors, - const std::vector& positions, - const std::vector& velocities) -{ - if (motors.empty() || motors.size() != positions.size() || - motors.size() != velocities.size() || motors.size() > 256) { - return false; - } - - std::array lock_order{}; - std::array commands{}; - std::shared_ptr protocol; - for (std::size_t i = 0; i < motors.size(); ++i) { - const auto motor = std::dynamic_pointer_cast(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{}); - std::array, 256> locks{}; - for (std::size_t i = 0; i < motors.size(); ++i) { - locks[i] = std::unique_lock(lock_order[i]->mtx_); - } - return protocol && protocol->commandCyclicPositionsAtomic(commands.data(), motors.size()); -} - -bool EyouMotor::readFeedbacksAtomic( - const std::vector>& motors, - std::vector& positions, - std::vector& velocities) -{ - if (motors.empty() || motors.size() > 256) { - return false; - } - - std::array lock_order{}; - std::array feedbacks{}; - std::shared_ptr protocol; - for (std::size_t i = 0; i < motors.size(); ++i) { - const auto motor = std::dynamic_pointer_cast(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{}); - std::array, 256> locks{}; - for (std::size_t i = 0; i < motors.size(); ++i) { - locks[i] = std::unique_lock(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() @@ -235,50 +97,42 @@ bool EyouMotor::brakeRelease() std::int16_t EyouMotor::getCurrent() { std::scoped_lock lock(mtx_); - if (!hasDependencies_()) { - return 0; - } - - std::int16_t raw_current = 0; - if (!vendor_adapter_->readActualCurrent(node_id_, raw_current)) { - CMVR_LOG(ERROR) << "[EyouMotor] failed to read actual current: " - << info_.joint_name; - return 0; - } - - const double current_ma = static_cast(raw_current) * - current_scale_ma_per_count_; - const double clamped_current_ma = std::clamp( - current_ma, + std::int16_t raw = 0; + if (!hasDependencies_() || !vendor_adapter_->readActualCurrent(node_id_, raw)) return 0; + return static_cast(std::clamp(raw * current_scale_ma_per_count_, static_cast(std::numeric_limits::min()), - static_cast(std::numeric_limits::max())); - return static_cast(clamped_current_ma); + static_cast(std::numeric_limits::max()))); +} + +void EyouMotor::configureCurrentConversion_() +{ + std::string model, version; + if (!vendor_adapter_->readMotorIdentity(node_id_, model, version)) { + CMVR_LOG(WARNING) << "[EyouMotor] failed to read motor identity; current uses raw PDO: " << info_.joint_name; + return; + } + const auto dash = model.find('-'); + const std::string prefix = dash != std::string::npos ? model.substr(0, dash) + : model.rfind("EuPH", 0) == 0 && model.size() >= 6 ? model.substr(0, 6) : model; + const std::map> scales{ + {"EuPH11", {0.005371094, 3.8}}, {"EuPH14", {0.007672991, 3.9}}, + {"EuPH17", {0.007672991, 3.9}}, {"EuPH20", {0.013427734, 6.9}}}; + const auto it = scales.find(prefix); + if (it == scales.end()) { + CMVR_LOG(WARNING) << "[EyouMotor] unsupported motor current conversion: " << model; + return; + } + current_scale_ma_per_count_ = version.find("V145") != std::string::npos + ? it->second.second : it->second.first * 1000.0; } 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 @@ -288,7 +142,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)); @@ -303,49 +156,4 @@ bool EyouMotor::writeVendorVelocityLimit_() const return vendor_adapter_->writeVelocityLimit(node_id_, radPerSecToCounts_(info_.limit_qd)); } -void EyouMotor::configureCurrentConversion_() -{ - std::string motor_model; - std::string motor_version; - if (!vendor_adapter_->readMotorIdentity(node_id_, motor_model, motor_version)) { - CMVR_LOG(WARNING) << "[EyouMotor] failed to read motor identity; actual current " - << "will use the raw PDO value: " << info_.joint_name; - return; - } - - std::string model_prefix = motor_model; - const auto dash_pos = motor_model.find('-'); - if (dash_pos != std::string::npos) { - model_prefix = motor_model.substr(0, dash_pos); - } else if (motor_model.rfind("EuPH", 0) == 0 && motor_model.size() >= 6) { - model_prefix = motor_model.substr(0, 6); - } - - const auto current_info = kMotorCurrentMap.find(model_prefix); - if (current_info == kMotorCurrentMap.end()) { - CMVR_LOG(WARNING) << "[EyouMotor] unsupported motor model for current conversion: " - << motor_model << ", actual current will use the raw PDO value"; - return; - } - - const bool is_v145 = motor_version.find("V145") != std::string::npos; - current_scale_ma_per_count_ = is_v145 - ? current_info->second.rated_current_amperes - : current_info->second.adc_amperes_per_count * 1000.0; -} - -std::int32_t EyouMotor::radToCounts_(const double angle_rad) const -{ - const double rev = angle_rad / (2.0 * M_PI); - return static_cast( - 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::llround(rev_per_sec * gear_ratio_ * encoder_counts_per_rev_)); -} - } // namespace cmvr::device diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor_adapter.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor_adapter.cpp index 99848f49..fdd72934 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor_adapter.cpp +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor_adapter.cpp @@ -1,5 +1,6 @@ #include "devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor_adapter.h" +#include #include #include #include @@ -33,20 +34,22 @@ bool EyouMotorAdapter::writePositionLimits(const std::uint8_t node_id, return false; } - const auto write_limits = [&]() { - return bus_runtime_->writeSdo(node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003, - 0x00, 0) && - bus_runtime_->writeSdo( - node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, - 0x02, upper_limit) && - bus_runtime_->writeSdo( - node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, - 0x01, lower_limit) && - bus_runtime_->writeSdo( - 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( + node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003, 0x00, original_state) || + !bus_runtime_->readSdo( + node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, 0x01, original_lower) || + !bus_runtime_->readSdo( + node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, 0x02, original_upper)) { + CMVR_LOG(ERROR) << "[EyouMotorAdapter] failed to snapshot software position limits, node=" + << static_cast(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( @@ -55,17 +58,47 @@ bool EyouMotorAdapter::writePositionLimits(const std::uint8_t node_id, bus_runtime_->readSdo( 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( + node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003, 0x00, 0) && + bus_runtime_->writeSdo( + node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, 0x02, upper_limit) && + bus_runtime_->writeSdo( + node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, 0x01, lower_limit) && + readback_matches(lower_limit, upper_limit) && + bus_runtime_->writeSdo( + node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003, 0x00, 0x4C494D54) && + bus_runtime_->readSdo( + node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003, 0x00, actual_state) && + actual_state == 0x4C494D54; if (!ok) { + const bool disabled = bus_runtime_->writeSdo( + node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003, 0x00, 0); + const bool upper_restored = disabled && bus_runtime_->writeSdo( + node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, 0x02, original_upper); + const bool lower_restored = disabled && bus_runtime_->writeSdo( + 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( + node_id, eyou::EYOU_SOFT_LIMIT_STATE_2003, 0x00, original_state) && + bus_runtime_->readSdo( + 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(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(node_id, eyou::EYOU_OVER_SPEED_THRESHOLD_2024, - 0x00, velocity_limit) && - bus_runtime_->readSdo(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(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(node_id, index, 0x00, velocity_limit) || + !bus_runtime_->readSdo(node_id, index, 0x00, actual_velocity_limit) || + actual_velocity_limit != velocity_limit) { + CMVR_LOG(ERROR) << "[EyouMotorAdapter] failed to write velocity limit, node=" + << static_cast(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(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(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( + node_id, msgs::CIA402_ACTUAL_POSITION_6064, 0x00, actual_position)) { + CMVR_LOG(ERROR) << "[EyouMotorAdapter] failed to read position for target synchronization, node=" + << static_cast(node_id); + return false; + } + + std::array writes{ + EthercatMotorBusRuntime::makePdoWrite( + node_id, msgs::CIA402_TARGET_POSITION_607A, 0x00, actual_position), + EthercatMotorBusRuntime::makePdoWrite( + node_id, msgs::CIA402_TARGET_VELOCITY_60FF, 0x00, 0), + EthercatMotorBusRuntime::makePdoWrite( + 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( + 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(node_id); + return false; + } + return true; +} + bool EyouMotorAdapter::brakeRelease(const std::uint8_t node_id) { if (!bus_runtime_) { @@ -373,25 +453,18 @@ bool EyouMotorAdapter::brakeRelease(const std::uint8_t node_id) return false; } -bool EyouMotorAdapter::readActualCurrent(const std::uint8_t node_id, - std::int16_t& current_value) const +bool EyouMotorAdapter::readActualCurrent(std::uint8_t node_id, std::int16_t& value) const { - return bus_runtime_ && - bus_runtime_->readPdo( - node_id, msgs::CIA402_ACTUAL_CURRENT_6078, 0x00, current_value); + return bus_runtime_ && bus_runtime_->readPdo( + node_id, msgs::CIA402_ACTUAL_CURRENT_6078, 0x00, value); } -bool EyouMotorAdapter::readMotorIdentity(const std::uint8_t node_id, - std::string& motor_model, - std::string& motor_version) const +bool EyouMotorAdapter::readMotorIdentity(std::uint8_t node_id, std::string& model, + std::string& version) const { - if (!bus_runtime_) { - return false; - } - return bus_runtime_->readSdoString( - node_id, eyou::EYOU_DEVICE_NAME_1008, 0x00, motor_model) && - bus_runtime_->readSdoString( - node_id, eyou::EYOU_SOFTWARE_VERSION_100A, 0x00, motor_version); + return bus_runtime_ && + bus_runtime_->readSdoString(node_id, eyou::EYOU_DEVICE_NAME_1008, 0x00, model) && + bus_runtime_->readSdoString(node_id, eyou::EYOU_SOFTWARE_VERSION_100A, 0x00, version); } } // namespace cmvr::device diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor_device_manager_real_test.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor_device_manager_real_test.cpp index 140f7c15..c6b31762 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor_device_manager_real_test.cpp +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor_device_manager_real_test.cpp @@ -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 center_q; diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor_real_test.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor_real_test.cpp index 6afcf47f..151ac5ef 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor_real_test.cpp +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor_real_test.cpp @@ -145,7 +145,6 @@ void printMotorState(const char* label, AbstractMotor& motor) std::cout << label << ": motor_q=" << motor.getQ() << " rad" << ", motor_qd=" << motor.getQd() << " rad/s" - << ", motor_current=" << motor.getCurrent() << " mA" << std::endl; } @@ -165,7 +164,6 @@ void printRawEthercatFeedback(const char* label, std::int32_t actual_position = 0; std::int32_t actual_velocity = 0; std::int16_t actual_torque = 0; - std::int16_t actual_current = 0; std::uint16_t error_code = 0; runtime->readPdo(kMotorId, msgs::CIA402_STATUS_WORD_6041, 0x00, statusword); @@ -176,8 +174,6 @@ void printRawEthercatFeedback(const char* label, actual_velocity); runtime->readPdo(kMotorId, msgs::CIA402_ACTUAL_TORQUE_6077, 0x00, actual_torque); - runtime->readPdo(kMotorId, msgs::CIA402_ACTUAL_CURRENT_6078, 0x00, - actual_current); runtime->readPdo(kMotorId, msgs::CIA402_ERROR_CODE_603F, 0x00, error_code); std::cout << label @@ -186,7 +182,6 @@ void printRawEthercatFeedback(const char* label, << ", actual_position=" << actual_position << ", actual_velocity=" << actual_velocity << ", actual_torque=" << actual_torque - << ", actual_current=" << actual_current << ", error_code=" << hex16(error_code) << std::endl; } @@ -219,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); @@ -242,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); } @@ -257,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); @@ -275,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)); @@ -298,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; @@ -347,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; @@ -400,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; @@ -455,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(); @@ -494,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; @@ -530,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(); diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor.cpp new file mode 100644 index 00000000..8aba5ec3 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor.cpp @@ -0,0 +1,126 @@ +#include "devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_motor.h" + +#include +#include +#include + +#include "common/base/logging/logger.h" + +namespace cmvr::device { + +TchlMotor::TchlMotor(const config::MotorConfigItem& config, + std::shared_ptr cia402_protocol, + std::unique_ptr 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::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::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::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 diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor_adapter.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor_adapter.cpp new file mode 100644 index 00000000..36ff9ab7 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor_adapter.cpp @@ -0,0 +1,516 @@ +#include "devices/motor/drivers/ethercat_motor/include/vendor/tchl/tchl_motor_adapter.h" + +#include +#include +#include +#include +#include + +#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 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(node_id); + return false; + } + + std::uint16_t enable_command_delay_ms = 0; + std::uint16_t disable_delay_ms = 0; + if (!bus_runtime_->readSdo( + node_id, kEnableCommandDelay, 0x00, enable_command_delay_ms) || + !bus_runtime_->readSdo( + 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(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( + node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, + 0x01, lower_limit) && + bus_runtime_->writeSdo( + node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, + 0x02, upper_limit) && + bus_runtime_->writeSdo( + node_id, kSoftLimitEnable, 0x00, 1) && + bus_runtime_->readSdo( + node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, + 0x01, actual_lower) && + bus_runtime_->readSdo( + node_id, msgs::CIA402_SOFTWARE_POSITION_LIMIT_607D, + 0x02, actual_upper) && + bus_runtime_->readSdo( + 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(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( + node_id, msgs::CIA402_MAX_PROFILE_VELOCITY_607F, + 0x00, velocity_limit) && + bus_runtime_->writeSdo( + node_id, msgs::CIA402_PROFILE_VELOCITY_6081, + 0x00, velocity_limit) && + bus_runtime_->readSdo( + node_id, msgs::CIA402_MAX_PROFILE_VELOCITY_607F, + 0x00, actual_velocity_limit) && + bus_runtime_->readSdo( + 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(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( + node_id, msgs::CIA402_ACTUAL_POSITION_6064, 0x00, actual_position)) { + return false; + } + const std::array writes{ + EthercatMotorBusRuntime::makePdoWrite( + node_id, msgs::CIA402_TARGET_POSITION_607A, 0x00, actual_position), + EthercatMotorBusRuntime::makePdoWrite( + node_id, msgs::CIA402_TARGET_VELOCITY_60FF, 0x00, 0), + EthercatMotorBusRuntime::makePdoWrite( + node_id, msgs::CIA402_TARGET_TORQUE_6071, 0x00, 0), + EthercatMotorBusRuntime::makePdoWrite( + 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( + 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(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( + 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( + 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(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(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( + node_id, msgs::CIA402_ACTUAL_VELOCITY_606C, 0x00, velocity)) { + return false; + } + if (std::abs(static_cast(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(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( + 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(node_id) + << ", mode=" << static_cast(mode); + return false; + } + std::uint16_t statusword = 0; + if (!bus_runtime_->readPdo( + node_id, msgs::CIA402_STATUS_WORD_6041, 0x00, statusword)) { + return false; + } + if (cia402::statusword(statusword).fault) { + if (!bus_runtime_->writePdo( + node_id, msgs::CIA402_CONTROL_WORD_6040, 0x00, + cia402::faultResetControlword().value)) { + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds{ + std::max(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( + 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( + 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( + node_id, msgs::CIA402_CONTROL_WORD_6040, 0x00, 0); + } + } + std::this_thread::sleep_for(disable_delay_); + // A forced release without an intervening enable remains latched after disabling. + std::uint16_t brake_command = 0; + const bool brake_reset = disabled && + bus_runtime_->readSdo( + node_id, kForceBrakeRelease, 0x00, brake_command) && + (brake_command == 0 || + (bus_runtime_->writeSdo( + node_id, kForceBrakeRelease, 0x00, 0) && + bus_runtime_->readSdo( + node_id, kForceBrakeRelease, 0x00, brake_command) && + brake_command == 0)); + if (disabled && !brake_reset) { + CMVR_LOG(ERROR) << "[TchlMotorAdapter] failed to clear forced brake release, node=" + << static_cast(node_id) + << ", command_readback=" << brake_command; + } + return targets_written && stopped && disabled && brake_reset; +} + +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(node_id, kHomingMethod, 0x00, 35) || + !bus_runtime_->readSdo(node_id, kHomingMethod, 0x00, method) || method != 35 || + !bus_runtime_->writeSdo( + node_id, msgs::CIA402_HOME_OFFSET_607C, 0x00, 0) || + !bus_runtime_->readSdo( + 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(node_id); + return false; + } + if (!writeSafeTargets_(node_id) || + !bus_runtime_->writePdo( + 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( + 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( + 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( + node_id, msgs::CIA402_STATUS_WORD_6041, 0x00), + EthercatMotorBusRuntime::makePdoRead( + node_id, msgs::CIA402_MODE_DISPLAY_6061, 0x00), + EthercatMotorBusRuntime::makePdoRead( + node_id, msgs::CIA402_ACTUAL_POSITION_6064, 0x00), + EthercatMotorBusRuntime::makePdoRead( + 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( + 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(reads[0]); + const auto mode = EthercatMotorBusRuntime::pdoReadValue(reads[1]); + zeroed_position = EthercatMotorBusRuntime::pdoReadValue(reads[2]); + const auto error = EthercatMotorBusRuntime::pdoReadValue(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(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(zeroed_position)) <= tolerance) { + return true; + } + } while (std::chrono::steady_clock::now() < deadline); + CMVR_LOG(ERROR) << "[TchlMotorAdapter] zero calibration timed out, node=" + << static_cast(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( + node_id, msgs::CIA402_STATUS_WORD_6041, 0x00, statusword) || + cia402::statusword(statusword).operation_enabled != 0) { + CMVR_LOG(ERROR) << "[TchlMotorAdapter] brake release requires a readable " + << "statusword with operation-enabled bit cleared, node=" + << static_cast(node_id); + return false; + } + + std::uint16_t command_readback = 0; + const bool ok = bus_runtime_->writeSdo( + node_id, kForceBrakeRelease, 0x00, kBrakeReleaseCommand) && + bus_runtime_->readSdo( + node_id, kForceBrakeRelease, 0x00, command_readback) && + command_readback == kBrakeReleaseCommand; + if (!ok) { + CMVR_LOG(ERROR) << "[TchlMotorAdapter] failed to verify brake release command, node=" + << static_cast(node_id) + << ", command_readback=" << command_readback; + } + // Pr8.30 readback confirms the command, not physical brake feedback. + return ok; +} + +} // namespace cmvr::device diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor_real_test.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor_real_test.cpp new file mode 100644 index 00000000..726a841f --- /dev/null +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor_real_test.cpp @@ -0,0 +1,217 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "common/config/config_files.h" +#include "devices/motor/manager/include/motor_manager.h" + +namespace cmvr::device { +namespace { + +constexpr double kTargetPositionRad = 1.57; +constexpr double kVelocityRadS = 0.5; +constexpr double kAccelerationRadS2 = 5.0; +constexpr double kCspExcursionRad = 3.0; +constexpr double kCspPeriodS = 6.0; +constexpr int kCspCycles = 2; +constexpr double kPvVelocityRadS = -0.3; +constexpr double kPvAccelerationRadS2 = 1.0; +constexpr double kCsvVelocityAmplitudeRadS = 1.3; +constexpr double kCsvPeriodS = 12.0; +constexpr int kCsvCycles = 2; +constexpr double kQuickStopVelocityRadS = 0.3; +constexpr double kQuickStopAccelerationRadS2 = 1.0; +constexpr double kPi = 3.14159265358979323846; +constexpr std::chrono::milliseconds kCommandPeriod{1}; +constexpr std::chrono::milliseconds kPrintPeriod{100}; + +std::shared_ptr initMotor(std::shared_ptr& manager) +{ + const char* config_path = std::getenv("TCHL_MOTOR_CONFIG"); + config::MotorRootConfig root; + if (!ConfigHelper::loadConfigFile( + config_path ? config_path : "cmvr-es/config/devices/motor/tchl_motors.pb.txt", root) || + root.motor().motor_groups_size() != 1 || + root.motor().motor_groups(0).motors().motors_size() != 1) { + throw std::runtime_error("Cannot load the single-axis motor configuration"); + } + const auto& group = root.motor().motor_groups(0); + manager = std::make_shared(root.motor().id(), root.motor(), group.id()); + if (!manager->init()) { + throw std::runtime_error("Motor initialization failed"); + } + auto motor = manager->getMotor(group.motors().motors(0).joint_name()); + if (!motor) { + throw std::runtime_error("Configured motor was not found"); + } + return motor; +} + +void printFeedback(const std::shared_ptr& motor) +{ + std::cout << "q=" << motor->getQ() << " rad" + << ", qd=" << motor->getQd() << " rad/s" + << ", torque=" << motor->getTau() << " per mille" << std::endl; +} + +void printFeedbackFor(const std::shared_ptr& motor, + std::chrono::seconds duration) +{ + const auto end = std::chrono::steady_clock::now() + duration; + while (std::chrono::steady_clock::now() < end) { + printFeedback(motor); + std::this_thread::sleep_for(kPrintPeriod); + } +} + +TEST(TchlMotorRealTest, ProfilePosition) +{ + std::shared_ptr manager; + auto motor = initMotor(manager); + motor->calibrateZeroQ(); + if (!motor->setMode(msgs::RUN_MODE_PROFILE_POSITION) || !motor->torqueOn() || + !motor->commandProfilePosition(-6, -1, kAccelerationRadS2)) { + throw std::runtime_error("Profile position command failed"); + } + std::cout << "target=" << kTargetPositionRad << " rad" << std::endl; + printFeedbackFor(motor, std::chrono::seconds{4}); + // motor->quickStop(); + printFeedbackFor(motor, std::chrono::seconds{1000}); +} + +TEST(TchlMotorRealTest, CyclicPositionSin) +{ + std::shared_ptr manager; + auto motor = initMotor(manager); + motor->calibrateZeroQ(); + if (!motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_POSITION) || !motor->torqueOn()) { + throw std::runtime_error("CSP enable failed"); + } + const double start_q = motor->getQ(); + const double omega = 2.0 * kPi / kCspPeriodS; + const double duration_s = kCspPeriodS * kCspCycles; + const auto start = std::chrono::steady_clock::now(); + auto next_print = start; + while (true) { + const auto now = std::chrono::steady_clock::now(); + const double t = std::min(duration_s, std::chrono::duration(now - start).count()); + const bool finished = t >= duration_s; + 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); + if (!motor->commandCyclicPosition(target_q, target_qd)) { + throw std::runtime_error("Cyclic position command failed"); + } + if (now >= next_print || finished) { + std::cout << "t=" << t << " s, target_q=" << target_q + << " rad, target_qd=" << target_qd << " rad/s, "; + printFeedback(motor); + next_print = now + kPrintPeriod; + } + if (finished) { + break; + } + const auto next_tick = (std::chrono::steady_clock::now() - start) / kCommandPeriod + 1; + std::this_thread::sleep_until(start + next_tick * kCommandPeriod); + } +} + +TEST(TchlMotorRealTest, ProfileVelocity) +{ + std::shared_ptr manager; + auto motor = initMotor(manager); + motor->calibrateZeroQ(); + if (!motor->setMode(msgs::RUN_MODE_PROFILE_VELOCITY) || !motor->torqueOn()) { + throw std::runtime_error("PV enable failed"); + } + if (!motor->commandProfileVelocity(-1.0, kPvAccelerationRadS2)) { + throw std::runtime_error("Profile velocity command failed"); + } + std::cout << "target_qd=" << kPvVelocityRadS << " rad/s" << std::endl; + while (true) { + printFeedback(motor); + std::this_thread::sleep_for(kPrintPeriod); + } +} + +TEST(TchlMotorRealTest, CyclicVelocitySin) +{ + std::shared_ptr manager; + auto motor = initMotor(manager); + if (!motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY) || !motor->torqueOn()) { + throw std::runtime_error("CSV enable failed"); + } + const double omega = 2.0 * kPi / kCsvPeriodS; + const double duration_s = kCsvPeriodS * kCsvCycles; + const auto start = std::chrono::steady_clock::now(); + auto next_print = start; + while (true) { + const auto now = std::chrono::steady_clock::now(); + const double t = std::min(duration_s, std::chrono::duration(now - start).count()); + const bool finished = t >= duration_s; + const double target_qd = finished ? 0.0 : kCsvVelocityAmplitudeRadS * std::sin(omega * t); + if (!motor->commandCyclicVelocity(target_qd)) { + throw std::runtime_error("Cyclic velocity command failed"); + } + if (now >= next_print || finished) { + std::cout << "t=" << t << " s, target_qd=" << target_qd << " rad/s, "; + printFeedback(motor); + next_print = now + kPrintPeriod; + } + if (finished) { + break; + } + const auto next_tick = (std::chrono::steady_clock::now() - start) / kCommandPeriod + 1; + std::this_thread::sleep_until(start + next_tick * kCommandPeriod); + } +} + +TEST(TchlMotorRealTest, QuickStopInProfileVelocity) +{ + std::shared_ptr manager; + auto motor = initMotor(manager); + const double target_qd = motor->getQ() > 0.0 ? -kQuickStopVelocityRadS : kQuickStopVelocityRadS; + if (!motor->setMode(msgs::RUN_MODE_PROFILE_VELOCITY) || !motor->torqueOn() || + !motor->commandProfileVelocity(target_qd, kQuickStopAccelerationRadS2)) { + throw std::runtime_error("Profile velocity command failed"); + } + printFeedbackFor(motor, std::chrono::seconds{2}); + if (!motor->quickStop()) { // Default deceleration: 5.0 rad/s^2. + throw std::runtime_error("Quick stop failed"); + } + printFeedbackFor(motor, std::chrono::seconds{1}); +} + +TEST(TchlMotorRealTest, BrakeRelease) +{ + std::shared_ptr manager; + auto motor = initMotor(manager); + if (!motor->torqueOff() || !motor->brakeRelease()) { + throw std::runtime_error("Brake release failed"); + } + printFeedbackFor(motor, std::chrono::seconds{10}); +} + +TEST(TchlMotorRealTest, CalibrateZeroQ) +{ + std::shared_ptr manager; + auto motor = initMotor(manager); + std::cout << "before calibration: "; + printFeedback(motor); + if (!motor->calibrateZeroQ()) { + throw std::runtime_error("Zero calibration failed"); + } + std::cout << "after calibration: "; + printFeedback(motor); +} + +} // namespace +} // namespace cmvr::device diff --git a/cmvr-es/devices/motor/drivers/lingkong_can/CMakeLists.txt b/cmvr-es/devices/motor/drivers/lingkong_can/CMakeLists.txt new file mode 100644 index 00000000..dabb38e3 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/lingkong_can/CMakeLists.txt @@ -0,0 +1,19 @@ +add_library(lingkong_can_motor_driver SHARED + src/protocol/lingkong_motor_request.cpp + src/protocol/lingkong_motor_response.cpp + src/lingkong_can_protocol.cpp + src/lingkong_motor.cpp +) +target_include_directories(lingkong_can_motor_driver PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) +target_link_libraries(lingkong_can_motor_driver + PUBLIC cmvr_es::device::motor_core + PRIVATE cmvr_es::device::canbus cmvr_es::proto glog pthread +) +add_library(cmvr_es::device::lingkong_can_motor_driver ALIAS lingkong_can_motor_driver) +install(TARGETS lingkong_can_motor_driver LIBRARY DESTINATION lib) + +# Fake transport only: these tests never open CAN or send commands to hardware. +add_executable(lingkong_motor_protocol_test tests/lingkong_motor_protocol_test.cpp) +target_link_libraries(lingkong_motor_protocol_test PRIVATE + cmvr_es::device::lingkong_can_motor_driver + cmvr_es::device::canbus gtest gtest_main pthread glog) diff --git a/cmvr-es/devices/motor/drivers/lingkong_can/include/lingkong_can_protocol.h b/cmvr-es/devices/motor/drivers/lingkong_can/include/lingkong_can_protocol.h new file mode 100644 index 00000000..a058eba0 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/lingkong_can/include/lingkong_can_protocol.h @@ -0,0 +1,87 @@ +#pragma once + +#include +#include +#include +#include + +#include "canbus/abstract_canbus.h" +#include "canbus/can_comm/message_manager.h" +#include "cmvr/config/motor_config/motor_config.pb.h" +#include "cmvr/msgs/robot_detail.pb.h" +#include "motor/motor_protocol_interface.h" +#include "motor/drivers/lingkong_can/include/protocol/lingkong_motor_response.h" + +namespace cmvr::device { + +class LingkongCanProtocol final : public MotorProtocolInterface { +public: + using Payload = motor::LingkongMotorRequest::Payload; + using Send = std::function; + struct Status { + double temperature{0}, voltage{0}, bus_current{0}; + uint8_t motor_state{0}, error{0}; + }; + LingkongCanProtocol(Send send, std::shared_ptr> manager); + bool initNode(uint8_t node_id) override; + bool configureNode(uint8_t node_id, const config::MotorConfigItem& config); + bool probe(uint8_t node_id); + // No standalone set-mode/read-mode command exists in this manual. A* commands + // select the native loop themselves; do not claim a drive mode readback. + bool setMode(uint8_t, msgs::RunMode) override { return false; } + msgs::RunMode getMode(uint8_t) override { return msgs::RUN_MODE_UNSPECIFIED; } + void setMotorConversion(uint8_t node_id, double counts, double gear_ratio) override; + bool setLimitQ(uint8_t node_id, double upper, double lower); + bool setLimitQd(uint8_t node_id, double value); + void setLimitQdd(uint8_t node_id, double upper, double lower) override; + bool torqueOn(uint8_t node_id) override; + bool torqueOff(uint8_t node_id) override; + // Native stop command has no configurable deceleration argument. + bool quickStop(uint8_t node_id, double deceleration = 5.0) override; + bool brakeRelease(uint8_t node_id); + // 0x95 RAM zero only; never write ROM (0x19/0x91) during initialization. + bool calibrateZeroQ(uint8_t node_id); + bool reachedTargetQ(uint8_t node_id) override; + double getQ(uint8_t node_id) override; + double getQd(uint8_t node_id) override; + double getTau(uint8_t node_id) override; + bool readFeedback(uint8_t node_id, double& q, double& qd); + bool readStatus(uint8_t node_id, Status& status); + bool readCurrent(uint8_t node_id, double& amps); + bool commandProfilePosition(uint8_t node_id, double q, double qd, double qdd) override; + bool commandProfileVelocity(uint8_t node_id, double qd, double qdd) override; + // Vendor setpoints, NOT synchronized CiA402 PDOs; no host trajectory planner. + bool commandCyclicPosition(uint8_t node_id, double q, double qd) override; + bool commandCyclicVelocity(uint8_t node_id, double qd) override; + bool commandCyclicTorque(uint8_t node_id, double tau) override; + // B0/B1 raw values, kept explicit because parameter units are firmware-specific. + bool readControlParameter(uint8_t node_id, uint8_t index, int32_t& value); + bool writeControlParameter(uint8_t node_id, uint8_t index, int32_t value); + bool clearError(uint8_t node_id); +private: + struct Node { + motor::LingkongMotorResponse* response{nullptr}; + config::MotorConfigItem config; + double target_q{0}; + bool target_valid{false}; + }; + bool exchange(uint8_t node_id, const Payload& request, Payload& response); + bool simple(uint8_t node_id, uint8_t command); + bool position(uint8_t node_id, double q, double qd); + bool velocity(uint8_t node_id, double qd); + bool acceleration(uint8_t node_id, double qdd); + bool parameter(uint8_t node_id, uint8_t command, uint8_t index, int32_t& value); + double scale(uint8_t node_id) const; + static int64_t signedLe(const uint8_t* data, unsigned bytes); + static void putLe(Payload& data, unsigned offset, uint32_t value, unsigned bytes); + static bool toInt32(double value, int32_t& raw); + Node* node(uint8_t node_id); + Send send_; + std::shared_ptr> manager_; + std::map nodes_; + // Serializes complete transactions, including multi-frame parameter+command + // operations. No retries: the wire protocol has no transaction sequence ID. + mutable std::recursive_mutex mutex_; +}; + +} // namespace cmvr::device diff --git a/cmvr-es/devices/motor/drivers/lingkong_can/include/lingkong_motor.h b/cmvr-es/devices/motor/drivers/lingkong_can/include/lingkong_motor.h new file mode 100644 index 00000000..aa4a1608 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/lingkong_can/include/lingkong_motor.h @@ -0,0 +1,27 @@ +#pragma once + +#include "motor/abstract_motor.h" +#include "lingkong_can_protocol.h" + +namespace cmvr::device { + +class LingkongMotor final : public AbstractMotor { +public: + explicit LingkongMotor(const config::MotorConfigItem& config); + std::string typeName() const override { return "LingkongMotor"; } + bool init() override; + bool setLimitQ(double upper, double lower) override; + bool setLimitQd(double value) override; + void setLimitQdd(double upper, double lower) override; + bool brakeRelease() override; + bool calibrateZeroQ() override; + bool readDiagnosticState(std::uint16_t& status, std::uint16_t& error, + bool& enabled, bool& fault) override; + bool readFeedback(double& q, double& qd); + bool readCurrent(double& amps); +private: + std::shared_ptr nativeProtocol() const; + config::MotorConfigItem config_; +}; + +} // namespace cmvr::device diff --git a/cmvr-es/devices/motor/drivers/lingkong_can/include/protocol/lingkong_motor_request.h b/cmvr-es/devices/motor/drivers/lingkong_can/include/protocol/lingkong_motor_request.h new file mode 100644 index 00000000..6ce54688 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/lingkong_can/include/protocol/lingkong_motor_request.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include "canbus/abstract_canbus.h" +#include "canbus/can_comm/protocol_data.h" +#include "cmvr/msgs/robot_detail.pb.h" + +namespace cmvr::device::motor { + +class LingkongMotorRequest final : public ProtocolData { +public: + using Payload = std::array; + static constexpr uint32_t BASE_ID = 0x140U; + static uint32_t ID(uint8_t node_id) { return BASE_ID + node_id; } + uint32_t ID() const { return ID(node_id_); } + explicit LingkongMotorRequest(uint8_t node_id) : node_id_(node_id) {} + void SetFrameData(const Payload& payload); + void UpdateData(uint8_t* data) override; + void Reset() override; + CanFrame frame(); +private: + uint8_t node_id_{0}; + Payload payload_{}; +}; + +} // namespace cmvr::device::motor diff --git a/cmvr-es/devices/motor/drivers/lingkong_can/include/protocol/lingkong_motor_response.h b/cmvr-es/devices/motor/drivers/lingkong_can/include/protocol/lingkong_motor_response.h new file mode 100644 index 00000000..d38b9238 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/lingkong_can/include/protocol/lingkong_motor_response.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include +#include +#include +#include "motor/drivers/lingkong_can/include/protocol/lingkong_motor_request.h" + +namespace cmvr::device::motor { + +// Request and response share one CAN ID. Register only the response parser in +// MessageManager; a second registration would overwrite its ID mapping. +class LingkongMotorResponse final : public ProtocolData { +public: + using Payload = LingkongMotorRequest::Payload; + static constexpr uint32_t BASE_ID = LingkongMotorRequest::BASE_ID; + static uint32_t ID(uint8_t node_id) { return BASE_ID + node_id; } + uint32_t ID() const { return ID(node_id_); } + explicit LingkongMotorResponse(uint8_t node_id) : node_id_(node_id) {} + void Parse(const uint8_t* bytes, int32_t length, msgs::RobotDetail*) const override; + bool exchange(const Payload& request, Payload& response, + std::chrono::milliseconds timeout, const std::function& send); +private: + uint8_t node_id_{0}; + mutable std::mutex mutex_; + mutable std::condition_variable changed_; + mutable bool waiting_{false}, received_{false}; + mutable Payload request_{}, response_{}; +}; + +} // namespace cmvr::device::motor diff --git a/cmvr-es/devices/motor/drivers/lingkong_can/src/lingkong_can_protocol.cpp b/cmvr-es/devices/motor/drivers/lingkong_can/src/lingkong_can_protocol.cpp new file mode 100644 index 00000000..7d3950d5 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/lingkong_can/src/lingkong_can_protocol.cpp @@ -0,0 +1,390 @@ +#include "lingkong_can_protocol.h" + +#include +#include +#include +#include +#include + +namespace cmvr::device { +namespace { +constexpr double kRadToDeg = 180.0 / 3.14159265358979323846; +constexpr double kUnavailable = std::numeric_limits::quiet_NaN(); +bool parameterIndex(uint8_t index) { return index == 10 || index == 12 || index == 14; } +} + +LingkongCanProtocol::LingkongCanProtocol( + Send send, std::shared_ptr> manager) + : send_(std::move(send)), manager_(std::move(manager)) +{ + comm_proto = CommProto::CUSTOM; +} + +bool LingkongCanProtocol::initNode(uint8_t id) +{ + std::lock_guard lock(mutex_); + if (!send_ || !manager_ || id < 1 || id > 32 || nodes_.count(id) || + manager_->GetMutableProtocolDataById(motor::LingkongMotorResponse::ID(id))) return false; + // Registration happens before CanMotorBusRuntime::start(), like TI5. + manager_->AddRecvProtocolData(id); + auto* response = dynamic_cast( + manager_->GetMutableProtocolDataById(motor::LingkongMotorResponse::ID(id))); + if (!response) return false; + nodes_[id].response = response; + return true; +} + +LingkongCanProtocol::Node* LingkongCanProtocol::node(uint8_t id) +{ + auto it = nodes_.find(id); + return it == nodes_.end() ? nullptr : &it->second; +} + +bool LingkongCanProtocol::configureNode(uint8_t id, const config::MotorConfigItem& cfg) +{ + std::lock_guard lock(mutex_); + auto* n = node(id); + const auto& c = cfg.lingkong(); + if (!n || cfg.id() != id || !std::isfinite(cfg.gear_ratio()) || cfg.gear_ratio() <= 0 || + !std::isfinite(cfg.limit_q_lb()) || !std::isfinite(cfg.limit_q_ub()) || + cfg.limit_q_lb() >= cfg.limit_q_ub()) return false; + for (double value : {cfg.limit_qd(), cfg.limit_qdd(), c.current_amp_per_lsb(), + c.rated_torque_current_a(), c.acceleration_deg_s2_per_lsb(), + c.speed_limit_deg_s_per_lsb(), c.reached_position_tolerance_rad()}) { + if (!std::isfinite(value) || value < 0) return false; + } + n->config = cfg; + return true; +} + +double LingkongCanProtocol::scale(uint8_t id) const +{ + const auto it = nodes_.find(id); + return it == nodes_.end() ? kUnavailable : kRadToDeg * it->second.config.gear_ratio(); +} + +int64_t LingkongCanProtocol::signedLe(const uint8_t* data, unsigned bytes) +{ + uint64_t value = 0; + for (unsigned i = 0; i < bytes; ++i) value |= uint64_t(data[i]) << (8U * i); + // 0x92 uses SEVEN payload bytes: sign extend bit 55, not bit 63. + if (data[bytes - 1] & 0x80) return -1 - static_cast((uint64_t(1) << (bytes * 8)) - 1 - value); + return static_cast(value); +} + +void LingkongCanProtocol::putLe(Payload& data, unsigned offset, uint32_t value, unsigned bytes) +{ + for (unsigned i = 0; i < bytes; ++i) data[offset + i] = (value >> (i * 8)) & 0xff; +} + +bool LingkongCanProtocol::toInt32(double value, int32_t& raw) +{ + if (!std::isfinite(value)) return false; + const double rounded = std::round(value); + if (rounded < std::numeric_limits::min() || + rounded > std::numeric_limits::max()) return false; + raw = static_cast(rounded); + return true; +} + +bool LingkongCanProtocol::exchange(uint8_t id, const Payload& request, Payload& response) +{ + auto* n = node(id); + if (!n || !n->response || !(n->config.gear_ratio() > 0)) return false; + motor::LingkongMotorRequest command(id); + command.SetFrameData(request); + const CanFrame frame = command.frame(); + const auto timeout = n->config.lingkong().response_timeout_ms(); + const bool ok = n->response->exchange(request, response, + std::chrono::milliseconds(timeout ? timeout : 100), [&] { return send_(frame); }); + if (!ok) CMVR_LOG(ERROR) << "[LingkongCanProtocol] send/reply failed: node=" << int(id) + << ", command=" << int(request[0]); + return ok; +} + +bool LingkongCanProtocol::simple(uint8_t id, uint8_t command) +{ + Payload request{}, response{}; + request[0] = command; + return exchange(id, request, response); +} + +bool LingkongCanProtocol::probe(uint8_t id) +{ + std::lock_guard lock(mutex_); + Status status; + double q, qd; + // Read-only initialization: no NMT, PDO setup, enabling or ROM writes. + return readStatus(id, status) && readFeedback(id, q, qd); +} + +void LingkongCanProtocol::setMotorConversion(uint8_t id, double, double gear) +{ + std::lock_guard lock(mutex_); + if (auto* n = node(id); n && std::isfinite(gear) && gear > 0) n->config.set_gear_ratio(gear); +} + +bool LingkongCanProtocol::setLimitQ(uint8_t id, double upper, double lower) +{ + std::lock_guard lock(mutex_); + auto* n = node(id); + if (!n || !std::isfinite(upper) || !std::isfinite(lower) || upper <= lower) return false; + // No angle-limit write command is specified: these are software limits only. + n->config.set_limit_q_ub(upper); + n->config.set_limit_q_lb(lower); + return true; +} + +bool LingkongCanProtocol::parameter(uint8_t id, uint8_t command, uint8_t index, int32_t& value) +{ + if (!parameterIndex(index) || (index == 10 && command == 0xB1 && + (value < -32768 || value > 32767))) return false; + Payload request{}, response{}; + request[0] = command; + request[1] = index; + // Manual p13: parameter bytes 1/2 are NULL; value starts at DATA[4]. + if (command == 0xB1) putLe(request, 4, static_cast(value), index == 10 ? 2 : 4); + if (!exchange(id, request, response)) return false; + value = static_cast(signedLe(response.data() + 4, index == 10 ? 2 : 4)); + return true; +} + +bool LingkongCanProtocol::readControlParameter(uint8_t id, uint8_t index, int32_t& value) +{ + std::lock_guard lock(mutex_); + return parameter(id, 0xB0, index, value); +} + +bool LingkongCanProtocol::writeControlParameter(uint8_t id, uint8_t index, int32_t value) +{ + std::lock_guard lock(mutex_); + return parameter(id, 0xB1, index, value); +} + +bool LingkongCanProtocol::setLimitQd(uint8_t id, double value) +{ + std::lock_guard lock(mutex_); + auto* n = node(id); + int32_t raw; + if (!n || !std::isfinite(value) || value <= 0 || + n->config.lingkong().speed_limit_deg_s_per_lsb() <= 0 || + !toInt32(value * scale(id) / n->config.lingkong().speed_limit_deg_s_per_lsb(), raw) || + raw <= 0 || !writeControlParameter(id, 14, raw)) return false; + n->config.set_limit_qd(value); + return true; +} + +bool LingkongCanProtocol::acceleration(uint8_t id, double value) +{ + auto* n = node(id); + if (!n || !std::isfinite(value) || value < 0) return false; + if (value == 0) return true; // Explicitly keep the drive's existing acceleration. + int32_t raw; + if (n->config.lingkong().acceleration_deg_s2_per_lsb() <= 0 || + !toInt32(value * scale(id) / n->config.lingkong().acceleration_deg_s2_per_lsb(), raw) || + raw <= 0) { + CMVR_LOG(ERROR) << "[LingkongCanProtocol] acceleration parameter units are not configured"; + return false; + } + return writeControlParameter(id, 12, raw); +} + +void LingkongCanProtocol::setLimitQdd(uint8_t id, double upper, double lower) +{ + std::lock_guard lock(mutex_); + if (!std::isfinite(upper) || !std::isfinite(lower) || upper <= 0 || lower >= 0 || + std::abs(upper + lower) > 1e-9 || !acceleration(id, upper)) { + // B1 has one symmetric limit; do not silently drop asymmetric input. + throw std::runtime_error("Lingkong acceleration limit failed: verify symmetric input, firmware units and CAN reply"); + } + node(id)->config.set_limit_qdd(upper); +} + +bool LingkongCanProtocol::torqueOn(uint8_t id) +{ + std::lock_guard lock(mutex_); + return simple(id, 0x88); +} +bool LingkongCanProtocol::torqueOff(uint8_t id) +{ + std::lock_guard lock(mutex_); + if (auto* n = node(id)) n->target_valid = false; // 0x80 clears multi-turn count. + return simple(id, 0x80); +} +bool LingkongCanProtocol::quickStop(uint8_t id, double /*deceleration*/) +{ + std::lock_guard lock(mutex_); + if (auto* n = node(id)) n->target_valid = false; + return simple(id, 0x81); +} +bool LingkongCanProtocol::brakeRelease(uint8_t id) +{ + std::lock_guard lock(mutex_); + Payload request{}, response{}; + request[0] = 0x8C; + request[1] = 1; + return exchange(id, request, response); +} +bool LingkongCanProtocol::calibrateZeroQ(uint8_t id) +{ + std::lock_guard lock(mutex_); + if (auto* n = node(id)) n->target_valid = false; + return simple(id, 0x95); +} +bool LingkongCanProtocol::clearError(uint8_t id) +{ + std::lock_guard lock(mutex_); + Payload request{}, response{}; + request[0] = 0x9B; + return exchange(id, request, response) && response[7] == 0; +} + +double LingkongCanProtocol::getQ(uint8_t id) +{ + std::lock_guard lock(mutex_); + Payload request{}, response{}; + request[0] = 0x92; + return exchange(id, request, response) ? signedLe(response.data() + 1, 7) / (100.0 * scale(id)) : kUnavailable; +} +double LingkongCanProtocol::getQd(uint8_t id) +{ + std::lock_guard lock(mutex_); + Payload request{}, response{}; + request[0] = 0x9C; + return exchange(id, request, response) ? signedLe(response.data() + 4, 2) / scale(id) : kUnavailable; +} +bool LingkongCanProtocol::readFeedback(uint8_t id, double& q, double& qd) +{ + std::lock_guard lock(mutex_); + // Separate replies, not a simultaneous/atomic hardware sample. + const double position = getQ(id), velocity = getQd(id); + if (!std::isfinite(position) || !std::isfinite(velocity)) return false; + q = position; + qd = velocity; + return true; +} +bool LingkongCanProtocol::readStatus(uint8_t id, Status& status) +{ + std::lock_guard lock(mutex_); + Payload request{}, response{}; + request[0] = 0x9A; + if (!exchange(id, request, response) || (response[6] != 0 && response[6] != 0x10)) return false; + status.temperature = signedLe(response.data() + 1, 1); + status.voltage = signedLe(response.data() + 2, 2) * 0.01; + status.bus_current = signedLe(response.data() + 4, 2) * 0.01; + status.motor_state = response[6]; + status.error = response[7]; + return true; +} +bool LingkongCanProtocol::readCurrent(uint8_t id, double& amps) +{ + std::lock_guard lock(mutex_); + auto* n = node(id); + if (!n || n->config.lingkong().current_amp_per_lsb() <= 0) return false; + Payload request{}, response{}; + request[0] = 0x9C; + if (!exchange(id, request, response)) return false; + amps = signedLe(response.data() + 2, 2) * n->config.lingkong().current_amp_per_lsb(); + return true; +} +double LingkongCanProtocol::getTau(uint8_t id) +{ + std::lock_guard lock(mutex_); + auto* n = node(id); + double current; + if (!n || n->config.lingkong().rated_torque_current_a() <= 0 || !readCurrent(id, current)) return kUnavailable; + return current * 1000.0 / n->config.lingkong().rated_torque_current_a(); +} + +bool LingkongCanProtocol::position(uint8_t id, double q, double qd) +{ + auto* n = node(id); + int32_t angle; + if (!n || !std::isfinite(qd) || qd < 0 || + q < n->config.limit_q_lb() || q > n->config.limit_q_ub() || + !toInt32(q * scale(id) * 100.0, angle)) return false; + if (n->config.limit_qd() > 0 && (qd == 0 || qd > n->config.limit_qd())) qd = n->config.limit_qd(); + Payload request{}, response{}; + request[0] = qd > 0 ? 0xA4 : 0xA3; + if (qd > 0) { + // Never round a speed ceiling UP (or send zero and rely on firmware). + const double speed = std::floor(qd * scale(id)); + if (speed < 1 || speed > 65535) return false; + putLe(request, 2, static_cast(speed), 2); + } + putLe(request, 4, static_cast(angle), 4); + n->target_valid = false; + if (!exchange(id, request, response)) return false; + n->target_q = q; + n->target_valid = true; + return true; +} +bool LingkongCanProtocol::velocity(uint8_t id, double qd) +{ + auto* n = node(id); + int32_t raw; + if (!n || !std::isfinite(qd) || + (n->config.limit_qd() > 0 && std::abs(qd) > n->config.limit_qd()) || + !toInt32(qd * scale(id) * 100.0, raw)) return false; + Payload request{}, response{}; + request[0] = 0xA2; + putLe(request, 4, static_cast(raw), 4); + n->target_valid = false; + return exchange(id, request, response); +} +bool LingkongCanProtocol::commandProfilePosition(uint8_t id, double q, double qd, double qdd) +{ + std::lock_guard lock(mutex_); + // Validate the target BEFORE changing a hardware parameter. + auto* n = node(id); + int32_t raw; + if (!n || !std::isfinite(qd) || qd < 0 || !toInt32(q * scale(id) * 100, raw) || + q < n->config.limit_q_lb() || q > n->config.limit_q_ub()) return false; + return acceleration(id, qdd) && position(id, q, qd); +} +bool LingkongCanProtocol::commandProfileVelocity(uint8_t id, double qd, double qdd) +{ + std::lock_guard lock(mutex_); + auto* n = node(id); + int32_t raw; + if (!n || !toInt32(qd * scale(id) * 100, raw) || + (n->config.limit_qd() > 0 && std::abs(qd) > n->config.limit_qd())) return false; + return acceleration(id, qdd) && velocity(id, qd); +} +bool LingkongCanProtocol::commandCyclicPosition(uint8_t id, double q, double qd) +{ + std::lock_guard lock(mutex_); + // Native A4 accepts a speed CEILING, not signed velocity feed-forward. + return position(id, q, std::abs(qd)); +} +bool LingkongCanProtocol::commandCyclicVelocity(uint8_t id, double qd) +{ + std::lock_guard lock(mutex_); + return velocity(id, qd); +} +bool LingkongCanProtocol::commandCyclicTorque(uint8_t id, double tau) +{ + std::lock_guard lock(mutex_); + auto* n = node(id); + if (!n || n->config.lingkong().rated_torque_current_a() <= 0 || + n->config.lingkong().current_amp_per_lsb() <= 0) return false; + int32_t raw; + if (!toInt32(tau * n->config.lingkong().rated_torque_current_a() / + (1000.0 * n->config.lingkong().current_amp_per_lsb()), raw) || + raw < -2048 || raw > 2048) return false; + Payload request{}, response{}; + request[0] = 0xA1; + putLe(request, 4, static_cast(raw), 2); + n->target_valid = false; + return exchange(id, request, response); +} +bool LingkongCanProtocol::reachedTargetQ(uint8_t id) +{ + std::lock_guard lock(mutex_); + auto* n = node(id); + if (!n || !n->target_valid || n->config.lingkong().reached_position_tolerance_rad() <= 0) return false; + const double q = getQ(id); + return std::isfinite(q) && std::abs(q - n->target_q) <= n->config.lingkong().reached_position_tolerance_rad(); +} + +} // namespace cmvr::device diff --git a/cmvr-es/devices/motor/drivers/lingkong_can/src/lingkong_motor.cpp b/cmvr-es/devices/motor/drivers/lingkong_can/src/lingkong_motor.cpp new file mode 100644 index 00000000..de4ed8af --- /dev/null +++ b/cmvr-es/devices/motor/drivers/lingkong_can/src/lingkong_motor.cpp @@ -0,0 +1,96 @@ +#include "lingkong_motor.h" +#include + +namespace cmvr::device { + +LingkongMotor::LingkongMotor(const config::MotorConfigItem& config) : config_(config) +{ + node_id_ = static_cast(config.id()); + info_ = {config.id(), config.joint_name(), config.limit_q_lb(), config.limit_q_ub(), + config.limit_qd(), config.limit_qdd()}; +} + +std::shared_ptr LingkongMotor::nativeProtocol() const +{ + return std::dynamic_pointer_cast(protocol_); +} + +bool LingkongMotor::init() +{ + std::scoped_lock lock(mtx_); + auto p = nativeProtocol(); + return p && !info_.joint_name.empty() && config_.id() >= 1 && config_.id() <= 32 && + p->configureNode(node_id_, config_) && p->probe(node_id_); +} + +bool LingkongMotor::setLimitQ(double upper, double lower) +{ + std::scoped_lock lock(mtx_); + auto p = nativeProtocol(); + if (!p || !p->setLimitQ(node_id_, upper, lower)) return false; + info_.limit_q_ub = upper; + info_.limit_q_lb = lower; + return true; +} + +bool LingkongMotor::setLimitQd(double value) +{ + std::scoped_lock lock(mtx_); + auto p = nativeProtocol(); + if (!p || !p->setLimitQd(node_id_, value)) return false; + info_.limit_qd = value; + return true; +} + +void LingkongMotor::setLimitQdd(double upper, double lower) +{ + std::scoped_lock lock(mtx_); + auto p = nativeProtocol(); + if (!p) throw std::runtime_error("Lingkong protocol is not configured"); + p->setLimitQdd(node_id_, upper, lower); + info_.limit_qdd = upper; +} + +bool LingkongMotor::brakeRelease() +{ + std::scoped_lock lock(mtx_); + auto p = nativeProtocol(); + return p && p->brakeRelease(node_id_); +} + +bool LingkongMotor::calibrateZeroQ() +{ + std::scoped_lock lock(mtx_); + auto p = nativeProtocol(); + return p && p->calibrateZeroQ(node_id_); +} + +bool LingkongMotor::readDiagnosticState(std::uint16_t& status, std::uint16_t& error, + bool& enabled, bool& fault) +{ + std::scoped_lock lock(mtx_); + auto p = nativeProtocol(); + LingkongCanProtocol::Status native; + if (!p || !p->readStatus(node_id_, native)) return false; + status = native.motor_state; // Native 0x00/0x10, NOT a synthesized 0x6041. + error = native.error; + enabled = native.motor_state == 0; + fault = native.error != 0; + return true; +} + +bool LingkongMotor::readFeedback(double& q, double& qd) +{ + std::scoped_lock lock(mtx_); + auto p = nativeProtocol(); + return p && p->readFeedback(node_id_, q, qd); +} + +bool LingkongMotor::readCurrent(double& amps) +{ + std::scoped_lock lock(mtx_); + auto p = nativeProtocol(); + return p && p->readCurrent(node_id_, amps); +} + +} // namespace cmvr::device diff --git a/cmvr-es/devices/motor/drivers/lingkong_can/src/protocol/lingkong_motor_request.cpp b/cmvr-es/devices/motor/drivers/lingkong_can/src/protocol/lingkong_motor_request.cpp new file mode 100644 index 00000000..48d5ca7a --- /dev/null +++ b/cmvr-es/devices/motor/drivers/lingkong_can/src/protocol/lingkong_motor_request.cpp @@ -0,0 +1,31 @@ +#include "motor/drivers/lingkong_can/include/protocol/lingkong_motor_request.h" + +#include + +namespace cmvr::device::motor { + +void LingkongMotorRequest::SetFrameData(const Payload& payload) +{ + payload_ = payload; +} + +void LingkongMotorRequest::UpdateData(uint8_t* data) +{ + if (data) std::copy(payload_.begin(), payload_.end(), data); +} + +void LingkongMotorRequest::Reset() +{ + payload_.fill(0); +} + +CanFrame LingkongMotorRequest::frame() +{ + CanFrame result; + result.id = ID(); + result.len = GetLength(); + UpdateData(result.data); + return result; +} + +} // namespace cmvr::device::motor diff --git a/cmvr-es/devices/motor/drivers/lingkong_can/src/protocol/lingkong_motor_response.cpp b/cmvr-es/devices/motor/drivers/lingkong_can/src/protocol/lingkong_motor_response.cpp new file mode 100644 index 00000000..35541494 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/lingkong_can/src/protocol/lingkong_motor_response.cpp @@ -0,0 +1,46 @@ +#include "motor/drivers/lingkong_can/include/protocol/lingkong_motor_response.h" + +#include + +namespace cmvr::device::motor { + +void LingkongMotorResponse::Parse(const uint8_t* bytes, int32_t length, msgs::RobotDetail*) const +{ + if (!bytes || length != 8) return; + std::lock_guard lock(mutex_); + if (!waiting_ || bytes[0] != request_[0]) return; + if ((bytes[0] == 0xB0 || bytes[0] == 0xB1) && bytes[1] != request_[1]) return; + if ((bytes[0] == 0x80 || bytes[0] == 0x81 || bytes[0] == 0x88 || + bytes[0] == 0x95 || bytes[0] == 0xB1) && + !std::equal(bytes, bytes + 8, request_.begin())) return; + if (bytes[0] == 0x8C && request_[1] != 0x10 && bytes[1] != request_[1]) return; + std::copy(bytes, bytes + 8, response_.begin()); + received_ = true; + waiting_ = false; + changed_.notify_one(); +} + +bool LingkongMotorResponse::exchange(const Payload& request, Payload& response, + std::chrono::milliseconds timeout, + const std::function& send) +{ + { + std::lock_guard lock(mutex_); + request_ = request; + received_ = false; + waiting_ = true; + } + // Never hold the receive lock across send: fake transports can reply inline. + if (!send()) { + std::lock_guard lock(mutex_); + waiting_ = false; + return false; + } + std::unique_lock lock(mutex_); + const bool ok = changed_.wait_for(lock, timeout, [&] { return received_; }); + waiting_ = false; + if (ok) response = response_; + return ok; +} + +} // namespace cmvr::device::motor diff --git a/cmvr-es/devices/motor/drivers/lingkong_can/tests/lingkong_motor_protocol_test.cpp b/cmvr-es/devices/motor/drivers/lingkong_can/tests/lingkong_motor_protocol_test.cpp new file mode 100644 index 00000000..cd7527e6 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/lingkong_can/tests/lingkong_motor_protocol_test.cpp @@ -0,0 +1,251 @@ +#include "lingkong_motor.h" + +#include +#include +#include +#include +#include + +using namespace cmvr; +using namespace cmvr::device; +namespace { +constexpr double kPi = 3.14159265358979323846; +using Payload = LingkongCanProtocol::Payload; +void put(Payload& p, unsigned offset, int64_t value, unsigned length) +{ + const auto bits = static_cast(value); + for (unsigned i = 0; i < length; ++i) p[offset + i] = (bits >> (8 * i)) & 0xff; +} + +class LingkongTest : public testing::Test { +protected: + std::shared_ptr> manager = + std::make_shared>(); + std::shared_ptr protocol; + std::vector sent; + bool respond = true, transport_ok = true; + int32_t velocity = -60, current = -409; + int64_t angle = -36000; + uint8_t state = 0x10, error = 0; + std::function mutate; + config::MotorConfigItem config; + + void SetUp() override { + config.set_id(1); + config.set_joint_name("MG6010E_AXIS_1"); + config.set_gear_ratio(6); + config.set_limit_q_lb(-4); + config.set_limit_q_ub(4); + config.set_limit_qd(1); + config.mutable_lingkong()->set_current_amp_per_lsb(66.0 / 4096.0); + config.mutable_lingkong()->set_response_timeout_ms(2); + config.mutable_lingkong()->set_reached_position_tolerance_rad(0.001); + protocol = std::make_shared([this](const CanFrame& frame) { + sent.push_back(frame); + if (!transport_ok) return false; + if (!respond) return true; + Payload reply{}; + std::copy(frame.data, frame.data + 8, reply.begin()); + if (reply[0] == 0x92) put(reply, 1, angle, 7); + if (reply[0] == 0x9C || (reply[0] >= 0xA1 && reply[0] <= 0xA8)) { + reply[1] = uint8_t(-12); + put(reply, 2, current, 2); + put(reply, 4, velocity, 2); + put(reply, 6, 12345, 2); + } + if (reply[0] == 0x9A || reply[0] == 0x9B) { + reply[1] = uint8_t(-12); + put(reply, 2, 4800, 2); + put(reply, 4, -125, 2); + reply[6] = state; + reply[7] = error; + } + if (reply[0] == 0xB0) put(reply, 4, reply[1] == 10 ? -123 : 123456, reply[1] == 10 ? 2 : 4); + if (mutate) mutate(reply); + manager->Parse(frame.id, reply.data(), reply.size()); + return true; + }, manager); + ASSERT_TRUE(protocol->initNode(1)); + ASSERT_TRUE(protocol->configureNode(1, config)); + } +}; + +TEST_F(LingkongTest, StandardCanIdAndReadOnlyInit) { + LingkongMotor motor(config); + // Use a fresh protocol to exercise the full setProtocol/init lifecycle. + auto other_manager = std::make_shared>(); + auto p = std::make_shared([&](const CanFrame& f) { + sent.push_back(f); + Payload r{}; r[0] = f.data[0]; + if (r[0] == 0x9A) r[6] = 0x10; + other_manager->Parse(f.id, r.data(), r.size()); + return true; + }, other_manager); + ASSERT_TRUE(motor.setProtocol(p)); + ASSERT_TRUE(motor.init()); + ASSERT_EQ(sent.size(), 3); + EXPECT_EQ(sent[0].data[0], 0x9A); + EXPECT_EQ(sent[1].data[0], 0x92); + EXPECT_EQ(sent[2].data[0], 0x9C); + for (const auto& f : sent) { EXPECT_EQ(f.id, 0x141); EXPECT_EQ(f.len, 8); } +} + +TEST_F(LingkongTest, RequestProtocolCopiesAndResetsAllEightBytes) { + motor::LingkongMotorRequest request(32); + Payload data{0xA4, 0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc}; + request.SetFrameData(data); + auto frame = request.frame(); + EXPECT_EQ(request.ID(), 0x160); + EXPECT_EQ(frame.id, 0x160); + EXPECT_EQ(frame.len, 8); + for (unsigned i = 0; i < data.size(); ++i) EXPECT_EQ(frame.data[i], data[i]); + request.Reset(); + frame = request.frame(); + for (auto byte : frame.data) EXPECT_EQ(byte, 0); +} + +TEST_F(LingkongTest, SignedMultiTurnAndVelocityUseGearRatio) { + EXPECT_NEAR(protocol->getQ(1), -kPi / 3, 1e-12); + EXPECT_NEAR(protocol->getQd(1), -kPi / 18, 1e-12); + angle = -(int64_t(1) << 40); // Seven-byte sign extension, not int32 truncation. + EXPECT_NEAR(protocol->getQ(1), angle * kPi / (18000.0 * 6), 1e-6); + angle = (int64_t(1) << 45); + EXPECT_NEAR(protocol->getQ(1), angle * kPi / (18000.0 * 6), 1e-4); +} + +TEST_F(LingkongTest, StatusAndCurrentAreNativeValues) { + LingkongCanProtocol::Status s; + ASSERT_TRUE(protocol->readStatus(1, s)); + EXPECT_EQ(s.motor_state, 0x10); + EXPECT_EQ(s.temperature, -12); + EXPECT_DOUBLE_EQ(s.voltage, 48); + EXPECT_DOUBLE_EQ(s.bus_current, -1.25); + double amps; + ASSERT_TRUE(protocol->readCurrent(1, amps)); + EXPECT_DOUBLE_EQ(amps, -409 * 66.0 / 4096); + EXPECT_TRUE(std::isnan(protocol->getTau(1))); // No fake rated torque/current. +} + +TEST_F(LingkongTest, NativeStatusIsNotDecodedAsCia402) { + LingkongMotor motor(config); + // A second node uses the same bus and its own response parser. + auto second = config; second.set_id(2); + LingkongMotor other(second); + ASSERT_TRUE(other.setProtocol(protocol)); + ASSERT_TRUE(other.init()); + uint16_t sw, ec; bool enabled, fault; + ASSERT_TRUE(other.readDiagnosticState(sw, ec, enabled, fault)); + EXPECT_EQ(sw, 0x10); EXPECT_FALSE(enabled); EXPECT_FALSE(fault); + state = 0; error = 8; + ASSERT_TRUE(other.readDiagnosticState(sw, ec, enabled, fault)); + EXPECT_TRUE(enabled); EXPECT_TRUE(fault); EXPECT_EQ(ec, 8); +} + +TEST_F(LingkongTest, PositionAndNegativeSpeedPackets) { + ASSERT_TRUE(protocol->commandProfilePosition(1, -kPi / 6, 0.5, 0)); + auto p = sent.back(); + EXPECT_EQ(p.data[0], 0xA4); + EXPECT_EQ(p.data[2], 171); // floor(0.5 * 180/pi * 6) dps. + EXPECT_EQ(p.data[3], 0); + Payload expected{}; put(expected, 4, -18000, 4); + for (int i = 4; i < 8; ++i) EXPECT_EQ(p.data[i], expected[i]); + ASSERT_TRUE(protocol->commandCyclicVelocity(1, -kPi / 36)); + expected = {}; put(expected, 4, -3000, 4); + EXPECT_EQ(sent.back().data[0], 0xA2); + for (int i = 4; i < 8; ++i) EXPECT_EQ(sent.back().data[i], expected[i]); +} + +TEST_F(LingkongTest, OperationsSendOnlyTheirOwnCommand) { + ASSERT_TRUE(protocol->torqueOn(1)); EXPECT_EQ(sent.back().data[0], 0x88); + ASSERT_TRUE(protocol->torqueOff(1)); EXPECT_EQ(sent.back().data[0], 0x80); + ASSERT_TRUE(protocol->quickStop(1)); EXPECT_EQ(sent.back().data[0], 0x81); + ASSERT_TRUE(protocol->brakeRelease(1)); EXPECT_EQ(sent.back().data[0], 0x8C); EXPECT_EQ(sent.back().data[1], 1); + ASSERT_TRUE(protocol->calibrateZeroQ(1)); EXPECT_EQ(sent.back().data[0], 0x95); + ASSERT_TRUE(protocol->clearError(1)); EXPECT_EQ(sent.back().data[0], 0x9B); + EXPECT_EQ(sent.size(), 6); + EXPECT_FALSE(protocol->setMode(1, msgs::RUN_MODE_CYCLIC_SYNC_POSITION)); + EXPECT_EQ(protocol->getMode(1), msgs::RUN_MODE_UNSPECIFIED); + EXPECT_EQ(sent.size(), 6); +} + +TEST_F(LingkongTest, ParameterOffsetsAndUnknownUnits) { + EXPECT_FALSE(protocol->setLimitQd(1, 0.5)); + EXPECT_THROW(protocol->setLimitQdd(1, 1, -1), std::runtime_error); + EXPECT_FALSE(protocol->commandProfilePosition(1, 0.5, 0.5, 1)); + EXPECT_TRUE(sent.empty()); + int32_t value; + ASSERT_TRUE(protocol->readControlParameter(1, 10, value)); EXPECT_EQ(value, -123); + ASSERT_TRUE(protocol->readControlParameter(1, 12, value)); EXPECT_EQ(value, 123456); + ASSERT_TRUE(protocol->writeControlParameter(1, 14, 123456)); + EXPECT_EQ(sent.back().data[2], 0); EXPECT_EQ(sent.back().data[3], 0); + EXPECT_EQ(sent.back().data[4], 0x40); EXPECT_EQ(sent.back().data[5], 0xe2); + EXPECT_EQ(sent.back().data[6], 1); EXPECT_EQ(sent.back().data[7], 0); +} + +TEST_F(LingkongTest, ExplicitParameterUnitsAndTorqueCalibration) { + config.mutable_lingkong()->set_acceleration_deg_s2_per_lsb(1); + config.mutable_lingkong()->set_speed_limit_deg_s_per_lsb(0.01); + config.mutable_lingkong()->set_rated_torque_current_a(5); + ASSERT_TRUE(protocol->configureNode(1, config)); + ASSERT_TRUE(protocol->commandProfileVelocity(1, 0.25, 1)); + ASSERT_EQ(sent.size(), 2); EXPECT_EQ(sent[0].data[0], 0xB1); EXPECT_EQ(sent[0].data[1], 12); + EXPECT_EQ(sent[1].data[0], 0xA2); + ASSERT_TRUE(protocol->commandCyclicTorque(1, -1000)); + Payload expected{}; put(expected, 4, -310, 2); + EXPECT_EQ(sent.back().data[0], 0xA1); + EXPECT_EQ(sent.back().data[4], expected[4]); EXPECT_EQ(sent.back().data[5], expected[5]); + EXPECT_DOUBLE_EQ(protocol->getTau(1), (-409 * 66.0 / 4096) * 1000 / 5); + EXPECT_FALSE(protocol->commandCyclicTorque(1, 100000)); +} + +TEST_F(LingkongTest, MissingRepliesNeverReuseOldData) { + EXPECT_TRUE(std::isfinite(protocol->getQ(1))); + respond = false; + EXPECT_TRUE(std::isnan(protocol->getQ(1))); + EXPECT_FALSE(protocol->torqueOn(1)); + double q = 42, qd = 43; + EXPECT_FALSE(protocol->readFeedback(1, q, qd)); + EXPECT_EQ(q, 42); EXPECT_EQ(qd, 43); + transport_ok = false; + EXPECT_FALSE(protocol->quickStop(1)); +} + +TEST_F(LingkongTest, WrongCommandAndParameterRepliesAreRejected) { + mutate = [](Payload& p) { p[0] = 0x9C; }; + EXPECT_TRUE(std::isnan(protocol->getQ(1))); + mutate = [](Payload& p) { p[1] = 10; }; + int32_t value = 0; + EXPECT_FALSE(protocol->readControlParameter(1, 12, value)); + mutate = [](Payload& p) { p[4] ^= 1; }; + EXPECT_FALSE(protocol->writeControlParameter(1, 12, 123)); +} + +TEST_F(LingkongTest, InvalidNodeConfigAndTargetsDoNotSend) { + EXPECT_FALSE(protocol->initNode(0)); EXPECT_FALSE(protocol->initNode(33)); + EXPECT_FALSE(protocol->initNode(1)); EXPECT_TRUE(protocol->initNode(32)); + EXPECT_FALSE(protocol->commandProfilePosition(1, 100, 0.5, 0)); + EXPECT_FALSE(protocol->commandProfileVelocity(1, 2, 0)); + EXPECT_FALSE(protocol->commandCyclicPosition(1, std::numeric_limits::quiet_NaN(), 0)); + EXPECT_FALSE(protocol->commandCyclicVelocity(1, std::numeric_limits::infinity())); + EXPECT_FALSE(protocol->commandCyclicTorque(1, 0)); // Missing rated current. + EXPECT_TRUE(sent.empty()); + auto bad = config; bad.set_gear_ratio(0); + EXPECT_FALSE(protocol->configureNode(1, bad)); +} + +TEST_F(LingkongTest, ReachedTargetUsesRealMultiTurnPosition) { + EXPECT_FALSE(protocol->reachedTargetQ(1)); + ASSERT_TRUE(protocol->commandCyclicPosition(1, -kPi / 3, 0.5)); + EXPECT_TRUE(protocol->reachedTargetQ(1)); + angle = 0; EXPECT_FALSE(protocol->reachedTargetQ(1)); + ASSERT_TRUE(protocol->quickStop(1)); EXPECT_FALSE(protocol->reachedTargetQ(1)); +} + +TEST_F(LingkongTest, ShortAndUnsolicitedPacketsAreIgnored) { + auto* parser = manager->GetMutableProtocolDataById(0x141); + Payload old{}; old[0] = 0x92; + parser->Parse(old.data(), 8, nullptr); + mutate = [&](Payload& p) { parser->Parse(p.data(), 7, nullptr); p[0] = 0; }; + EXPECT_TRUE(std::isnan(protocol->getQ(1))); +} +} // namespace diff --git a/cmvr-es/devices/motor/drivers/mujoco/include/mujoco_motor.h b/cmvr-es/devices/motor/drivers/mujoco/include/mujoco_motor.h index 57c97387..3a200da6 100644 --- a/cmvr-es/devices/motor/drivers/mujoco/include/mujoco_motor.h +++ b/cmvr-es/devices/motor/drivers/mujoco/include/mujoco_motor.h @@ -26,10 +26,11 @@ public: bool torqueOn() override; bool torqueOff() override; bool brakeRelease() override; - bool quickStop() override; + // Holds the current position; this backend does not simulate a deceleration ramp. + bool quickStop(double deceleration = 5.0) 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; @@ -49,6 +50,13 @@ public: const std::vector>& motors, const std::vector& positions, const std::vector& velocities); + static bool commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities); + static bool readFeedbacksAtomic( + const std::vector>& motors, + std::vector& positions, + std::vector& velocities); private: bool holdPosition_(); diff --git a/cmvr-es/devices/motor/drivers/mujoco/src/mujoco_motor.cpp b/cmvr-es/devices/motor/drivers/mujoco/src/mujoco_motor.cpp index 447e8d18..f04307b9 100644 --- a/cmvr-es/devices/motor/drivers/mujoco/src/mujoco_motor.cpp +++ b/cmvr-es/devices/motor/drivers/mujoco/src/mujoco_motor.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -73,22 +74,33 @@ bool MujocoMotor::brakeRelease() return true; } -bool MujocoMotor::quickStop() +bool MujocoMotor::quickStop(const double deceleration) { + if (!std::isfinite(deceleration) || deceleration <= 0.0) { + return false; + } 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) @@ -276,6 +288,83 @@ bool MujocoMotor::commandCyclicPositionsAtomic( return true; } +bool MujocoMotor::commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities) +{ + if (motors.empty() || motors.size() != velocities.size()) { + return false; + } + std::vector selected; + selected.reserve(motors.size()); + std::shared_ptr world; + for (std::size_t i = 0; i < motors.size(); ++i) { + const auto motor = std::dynamic_pointer_cast(motors[i]); + if (!motor || !std::isfinite(velocities[i])) { + return false; + } + const auto motor_world = motor->worldLocked_(); + if (!motor_world || (world && world != motor_world) || + std::find(selected.begin(), selected.end(), motor.get()) != selected.end()) { + return false; + } + world = motor_world; + selected.push_back(motor.get()); + } + + auto lock_order = selected; + std::sort(lock_order.begin(), lock_order.end(), std::less{}); + std::vector> locks; + locks.reserve(lock_order.size()); + for (auto* motor : lock_order) { + locks.emplace_back(motor->mtx_); + } + std::vector names; + std::vector clamped_velocities; + names.reserve(selected.size()); + clamped_velocities.reserve(selected.size()); + for (std::size_t i = 0; i < selected.size(); ++i) { + if (!selected[i]->initialized_) { + return false; + } + names.push_back(selected[i]->info_.joint_name); + clamped_velocities.push_back(selected[i]->clampQd_(velocities[i])); + } + if (!world->setJointTargetVelocities(names, clamped_velocities)) { + return false; + } + for (auto* motor : selected) { + motor->mode_ = msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY; + } + return true; +} + +bool MujocoMotor::readFeedbacksAtomic( + const std::vector>& motors, + std::vector& positions, + std::vector& velocities) +{ + if (motors.empty()) { + return false; + } + std::shared_ptr world; + std::vector names; + names.reserve(motors.size()); + for (const auto& item : motors) { + const auto motor = std::dynamic_pointer_cast(item); + if (!motor) { + return false; + } + const auto motor_world = motor->worldLocked_(); + if (!motor_world || (world && world != motor_world)) { + return false; + } + world = motor_world; + names.push_back(motor->info_.joint_name); + } + return world->getJointStates(names, positions, velocities); +} + double MujocoMotor::clampQ_(const double q) const { if (std::isfinite(info_.limit_q_lb) && std::isfinite(info_.limit_q_ub) && diff --git a/cmvr-es/devices/motor/drivers/ti5_canopen/include/ti5_motor.h b/cmvr-es/devices/motor/drivers/ti5_canopen/include/ti5_motor.h index d10a4db2..0439dded 100644 --- a/cmvr-es/devices/motor/drivers/ti5_canopen/include/ti5_motor.h +++ b/cmvr-es/devices/motor/drivers/ti5_canopen/include/ti5_motor.h @@ -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(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(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(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(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}; diff --git a/cmvr-es/devices/motor/drivers/ti5_canopen/include/ti5_motor_canopen_protocol.h b/cmvr-es/devices/motor/drivers/ti5_canopen/include/ti5_motor_canopen_protocol.h index cb3951df..57e7e490 100644 --- a/cmvr-es/devices/motor/drivers/ti5_canopen/include/ti5_motor_canopen_protocol.h +++ b/cmvr-es/devices/motor/drivers/ti5_canopen/include/ti5_motor_canopen_protocol.h @@ -31,14 +31,15 @@ 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 quickStop(uint8_t node_id) override; + bool brakeRelease(uint8_t node_id); + bool quickStop(uint8_t node_id, double deceleration = 5.0) override; bool reachedTargetQ(uint8_t node_id) override; double getQ(uint8_t node_id) override; diff --git a/cmvr-es/devices/motor/drivers/ti5_canopen/src/ti5_motor_canopen_protocol.cpp b/cmvr-es/devices/motor/drivers/ti5_canopen/src/ti5_motor_canopen_protocol.cpp index 47fd04c4..8c7cabef 100644 --- a/cmvr-es/devices/motor/drivers/ti5_canopen/src/ti5_motor_canopen_protocol.cpp +++ b/cmvr-es/devices/motor/drivers/ti5_canopen/src/ti5_motor_canopen_protocol.cpp @@ -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 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::max()) { + return false; + } + seedSdoRequest(node_id, CS_WRITE_FOUR_BYTES, CIA402_MAX_PROFILE_VELOCITY_607F, + SUB_INDEX_0, static_cast(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::min() || + ub > std::numeric_limits::max() || + lb < std::numeric_limits::min() || + lb > std::numeric_limits::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(static_cast(lb))); + seedSdoRequest(node_id, CS_WRITE_FOUR_BYTES, CIA402_SOFTWARE_POSITION_LIMIT_607D, + SUB_INDEX_2, static_cast(static_cast(ub))); + return true; } @@ -642,11 +669,22 @@ bool Ti5MotorCanopenProtocol::brakeRelease(uint8_t node_id) { return true; } -bool Ti5MotorCanopenProtocol::quickStop(uint8_t node_id) { +bool Ti5MotorCanopenProtocol::quickStop(uint8_t node_id, const double deceleration) { + const auto* conversion = conversionForNode(node_id); + if (!conversion || !std::isfinite(deceleration) || deceleration <= 0.0) { + return false; + } + const double raw = radPerSecToVelocityRaw(deceleration, *conversion) / + Ti5AccelerationTimeScale; + if (!std::isfinite(raw) || raw < 1.0 || + raw > std::numeric_limits::max()) { + return false; + } + const auto deceleration_raw = radPerSec2ToAccelerationRaw(deceleration, *conversion); // // 开机未使能电机时调用 // seedSdoRequest(node_id, CS_WRITE_TWO_BYTES, CIA402_CONTROL_WORD_6040, SUB_INDEX_0, 0x0F); // 6 抱闸 0 : 立即停机 自由 - seedSdoRequest(node_id, CS_WRITE_FOUR_BYTES, CIA402_QUICK_STOP_DECELERATION_6085, SUB_INDEX_0, 0XFFFFFFF0); + seedSdoRequest(node_id, CS_WRITE_FOUR_BYTES, CIA402_QUICK_STOP_DECELERATION_6085, SUB_INDEX_0, deceleration_raw); seedSdoRequest(node_id, CS_WRITE_TWO_BYTES, CIA402_QUICK_STOP_OPTION_605A, SUB_INDEX_0, 6); seedSdoRequest(node_id, CS_WRITE_TWO_BYTES, CIA402_CONTROL_WORD_6040, SUB_INDEX_0, 0x02, 100); diff --git a/cmvr-es/devices/motor/manager/CMakeLists.txt b/cmvr-es/devices/motor/manager/CMakeLists.txt index 8ea5f495..5ec6a75a 100644 --- a/cmvr-es/devices/motor/manager/CMakeLists.txt +++ b/cmvr-es/devices/motor/manager/CMakeLists.txt @@ -10,6 +10,7 @@ target_link_libraries(motor_manager cmvr_es::device::motor_core cmvr_es::device::motor_bus_runtime PRIVATE + cmvr_es::device::lingkong_can_motor_driver cmvr_es::device::ti5_canopen_motor_driver cmvr_es::device::mujoco_motor_driver cmvr_es::device::ethercat_motor_driver diff --git a/cmvr-es/devices/motor/manager/include/motor_manager.h b/cmvr-es/devices/motor/manager/include/motor_manager.h index 45e8ab3e..53107b46 100644 --- a/cmvr-es/devices/motor/manager/include/motor_manager.h +++ b/cmvr-es/devices/motor/manager/include/motor_manager.h @@ -46,14 +46,28 @@ public: std::shared_ptr getMotor(std::uint8_t node_id) const; std::shared_ptr getMotor(const std::string& joint_name) const; const std::unordered_map>& motorsMap() const; + std::vector> motorsSnapshot() const; bool commandCyclicPositionsAtomic( const std::vector>& motors, const std::vector& positions, const std::vector& velocities) const; + bool commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities) const; + // Torques are per mille of rated torque: 1000 equals rated torque. + bool commandCyclicTorquesAtomic( + const std::vector>& motors, + const std::vector& torques) const; bool readFeedbacksAtomic( const std::vector>& motors, std::vector& positions, std::vector& velocities) const; + // Reads all three quantities from one EtherCAT snapshot; torques are per mille. + bool readFeedbacksAtomic( + const std::vector>& motors, + std::vector& positions, + std::vector& velocities, + std::vector& torques) const; static std::shared_ptr managerFor(const std::string& id); static std::shared_ptr mujocoWorldFor(const std::string& id); diff --git a/cmvr-es/devices/motor/manager/src/motor_manager.cpp b/cmvr-es/devices/motor/manager/src/motor_manager.cpp index 1d1b262e..7452c502 100644 --- a/cmvr-es/devices/motor/manager/src/motor_manager.cpp +++ b/cmvr-es/devices/motor/manager/src/motor_manager.cpp @@ -8,7 +8,6 @@ #include #include -#include "algorithms/kinematics/ik_solver/common/include/urdf_parser.h" #include "common/base/logging/logger.h" #include "common/config/config_files.h" #include "devices/motor/bus_runtime/abstract_motor_bus_runtime.h" @@ -16,12 +15,18 @@ #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" +#include "devices/motor/drivers/lingkong_can/include/lingkong_motor.h" +#include "algorithms/kinematics/ik_solver/common/include/urdf_parser.h" namespace cmvr::device { @@ -264,6 +269,14 @@ std::shared_ptr MotorManager::getMotor(const std::string& joint_n return it->second; } +std::vector> MotorManager::motorsSnapshot() const +{ + std::lock_guard lock(motors_mutex_); + std::vector> result; + for (const auto& entry:motors_by_id_) if (entry.second) result.push_back(entry.second); + return result; +} + const std::unordered_map>& MotorManager::motorsMap() const { return motors_by_joint_; @@ -279,12 +292,23 @@ bool MotorManager::commandCyclicPositionsAtomic( return false; } - if (std::dynamic_pointer_cast(motors.front())) { - return EyouMotor::commandCyclicPositionsAtomic(motors, positions, velocities); + if (std::dynamic_pointer_cast(motors.front())) { + return EthercatMotor::commandCyclicPositionsAtomic(motors, positions, velocities); } if (std::dynamic_pointer_cast(motors.front())) { return MujocoMotor::commandCyclicPositionsAtomic(motors, positions, velocities); } + if (std::dynamic_pointer_cast(motors.front())) { + for (std::size_t i = 0; i < motors.size(); ++i) { + if (!std::dynamic_pointer_cast(motors[i]) || + !std::isfinite(positions[i]) || !std::isfinite(velocities[i])) return false; + } + // Vendor CAN requests are per motor, not synchronized/atomic PDOs. + for (std::size_t i = 0; i < motors.size(); ++i) { + if (!motors[i]->commandCyclicPosition(positions[i], velocities[i])) return false; + } + return true; + } if (std::dynamic_pointer_cast(motors.front())) { // TI5 currently exposes only a per-motor RPDO command. Keep the // fallback here so callers retain one manager-level entry point. @@ -311,17 +335,140 @@ bool MotorManager::commandCyclicPositionsAtomic( return false; } +bool MotorManager::commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities) const +{ + if (motors.empty() || motors.size() != velocities.size()) { + return false; + } + for (std::size_t i = 0; i < motors.size(); ++i) { + if (!motors[i] || !std::isfinite(velocities[i])) { + return false; + } + for (std::size_t previous = 0; previous < i; ++previous) { + if (motors[previous] == motors[i]) { + return false; + } + } + } + if (std::dynamic_pointer_cast(motors.front())) { + return EthercatMotor::commandCyclicVelocitiesAtomic(motors, velocities); + } + if (std::dynamic_pointer_cast(motors.front())) { + return MujocoMotor::commandCyclicVelocitiesAtomic(motors, velocities); + } + if (std::dynamic_pointer_cast(motors.front())) { + for (const auto& motor : motors) { + if (!std::dynamic_pointer_cast(motor)) return false; + } + for (std::size_t i = 0; i < motors.size(); ++i) { + if (!motors[i]->commandCyclicVelocity(velocities[i])) return false; + } + return true; + } + if (std::dynamic_pointer_cast(motors.front())) { + for (const auto& motor : motors) { + if (!std::dynamic_pointer_cast(motor)) { + return false; + } + } + static std::once_flag warning; + std::call_once(warning, []() { + CMVR_LOG(WARNING) + << "[MotorManager] TI5 uses non-atomic cyclic velocity commands"; + }); + for (std::size_t i = 0; i < motors.size(); ++i) { + if (!motors[i]->commandCyclicVelocity(velocities[i])) { + // CAN commands cannot be rolled back; attempt to stop every motor. + for (const auto& motor : motors) { + if (!motor->commandCyclicVelocity(0.0)) { + CMVR_LOG(ERROR) << "[MotorManager] failed to zero TI5 motor: " + << motor->id(); + } + } + return false; + } + } + return true; + } + CMVR_LOG(ERROR) << "[MotorManager] atomic cyclic velocity is unsupported for motor type: " + << motors.front()->typeName(); + return false; +} + +bool MotorManager::commandCyclicTorquesAtomic( + const std::vector>& motors, + const std::vector& torques) const +{ + if (motors.empty() || !motors.front()) { + return false; + } + if (std::dynamic_pointer_cast(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>& motors, std::vector& positions, std::vector& velocities) const { - if (motors.empty()) { + if (motors.empty() || &positions == &velocities) { return false; } + for (std::size_t i = 0; i < motors.size(); ++i) { + if (!motors[i]) { + return false; + } + for (std::size_t previous = 0; previous < i; ++previous) { + if (motors[previous] == motors[i]) { + return false; + } + } + } - if (std::dynamic_pointer_cast(motors.front())) { - return EyouMotor::readFeedbacksAtomic(motors, positions, velocities); + if (std::dynamic_pointer_cast(motors.front())) { + return EthercatMotor::readFeedbacksAtomic(motors, positions, velocities); + } + if (std::dynamic_pointer_cast(motors.front())) { + return MujocoMotor::readFeedbacksAtomic(motors, positions, velocities); + } + if (std::dynamic_pointer_cast(motors.front())) { + std::vector q(motors.size()), qd(motors.size()); + for (std::size_t i = 0; i < motors.size(); ++i) { + auto motor = std::dynamic_pointer_cast(motors[i]); + if (!motor || !motor->readFeedback(q[i], qd[i])) return false; + } + positions = std::move(q); + velocities = std::move(qd); + return true; + } + if (std::dynamic_pointer_cast(motors.front())) { + for (const auto& motor : motors) { + if (!std::dynamic_pointer_cast(motor)) { + return false; + } + } + static std::once_flag warning; + std::call_once(warning, []() { + CMVR_LOG(WARNING) << "[MotorManager] TI5 feedback is read per motor, not atomically"; + }); + std::vector q(motors.size()); + std::vector qd(motors.size()); + for (std::size_t i = 0; i < motors.size(); ++i) { + q[i] = motors[i]->getQ(); + qd[i] = motors[i]->getQd(); + if (!std::isfinite(q[i]) || !std::isfinite(qd[i])) { + return false; + } + } + positions = std::move(q); + velocities = std::move(qd); + return true; } CMVR_LOG(ERROR) << "[MotorManager] atomic feedback is unsupported for motor type: " @@ -329,6 +476,24 @@ bool MotorManager::readFeedbacksAtomic( return false; } +bool MotorManager::readFeedbacksAtomic( + const std::vector>& motors, + std::vector& positions, + std::vector& velocities, + std::vector& torques) const +{ + if (motors.empty() || !motors.front() || &positions == &velocities || + &positions == &torques || &velocities == &torques) { + return false; + } + if (std::dynamic_pointer_cast(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::managerFor(const std::string& id) { std::lock_guard lock(registry_mutex_); @@ -395,9 +560,7 @@ bool MotorManager::applyConfiguredJointLimits_(const config::MotorGroupConfig& g } const auto& model = parser.model(); for (pinocchio::JointIndex joint_id = 1; joint_id < model.njoints; ++joint_id) { - if (model.nqs[joint_id] != 1 || model.nvs[joint_id] != 1) { - continue; - } + if (model.nqs[joint_id] != 1 || model.nvs[joint_id] != 1) continue; config::JointLimitConfig limit; limit.set_joint_name(model.names[joint_id]); limit.set_q_lb(model.lowerPositionLimit[model.idx_qs[joint_id]]); @@ -445,10 +608,15 @@ std::shared_ptr MotorManager::createBusRuntime_( return std::make_shared(); case config::MOTOR_BUS_ETHERCAT: { auto runtime = std::make_shared(); - 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()) @@ -504,6 +672,27 @@ std::vector> MotorManager::createCanMotors_( CMVR_LOG(ERROR) << "[MotorManager] missing CAN config: " << group_cfg.id(); return {}; } + if (group_cfg.vendor() == config::MOTOR_VENDOR_LINGKONG && + group_cfg.protocol() == config::MOTOR_PROTOCOL_LINGKONG_CAN) { + auto client = can_bus_runtime->client(); + if (!client) return {}; + auto protocol = std::make_shared( + [client](const CanFrame& frame) { + return client->sendSingleFrame({frame}) == msgs::ErrorCode::OK; + }, can_bus_runtime->messageManager()); + std::vector> motors; + motors.reserve(motor_cfgs.size()); + for (const auto& cfg : motor_cfgs) { + if (cfg.id() < 1 || cfg.id() > 32) { + CMVR_LOG(ERROR) << "[MotorManager] Lingkong CAN ID must be in [1, 32]"; + return {}; + } + auto motor = std::make_shared(cfg); + if (!motor->setProtocol(protocol)) return {}; + motors.push_back(std::move(motor)); + } + return motors; + } if (group_cfg.vendor() != config::MOTOR_VENDOR_TI5 || group_cfg.protocol() != config::MOTOR_PROTOCOL_CANOPEN) { CMVR_LOG(ERROR) << "[MotorManager] unsupported CAN motor: vendor=" @@ -560,8 +749,12 @@ std::vector> MotorManager::createMujocoMotors_( cfg.joint_name(), mujoco_bus_runtime->mujocoWorld(), static_cast(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()); } @@ -589,7 +782,8 @@ std::vector> 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()) @@ -611,11 +805,18 @@ std::vector> MotorManager::createEthercatMotors_( std::vector> motors; motors.reserve(motor_cfgs.size()); for (const auto& cfg : motor_cfgs) { - auto motor = std::make_shared( - cfg, protocol, std::make_unique(ethercat_bus_runtime)); + std::shared_ptr motor; + if (group_cfg.vendor() == config::MOTOR_VENDOR_EYOU) { + motor = std::make_shared( + cfg, protocol, std::make_unique(ethercat_bus_runtime)); + } else { + motor = std::make_shared( + cfg, protocol, std::make_unique(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)); diff --git a/cmvr-es/devices/motor/motor_protocol_interface.h b/cmvr-es/devices/motor/motor_protocol_interface.h index 6afbcb64..8587282b 100644 --- a/cmvr-es/devices/motor/motor_protocol_interface.h +++ b/cmvr-es/devices/motor/motor_protocol_interface.h @@ -6,6 +6,7 @@ #pragma once #include +#include #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,23 @@ 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; + // deceleration: positive output-axis rad/s^2. + virtual bool quickStop(uint8_t node_id, double deceleration = 5.0) = 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::quiet_NaN(); + } CommProto comm_proto{CommProto::CANOPEN}; protected: }; diff --git a/cmvr-es/service/CMakeLists.txt b/cmvr-es/service/CMakeLists.txt index 31524a06..b069fdb6 100644 --- a/cmvr-es/service/CMakeLists.txt +++ b/cmvr-es/service/CMakeLists.txt @@ -9,6 +9,7 @@ add_library(service grpc/src/grpc_head_service.cpp grpc/src/grpc_dexhand_service.cpp grpc/src/grpc_arm_service.cpp + grpc/src/grpc_motor_service.cpp grpc/src/grpc_agv_service.cpp grpc/src/grpc_hlc_service.cpp ../task/grpc_server_task/src/grpc_server_task.cpp @@ -17,6 +18,7 @@ add_library(service target_include_directories(service PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(service PRIVATE + cmvr_es::device::ethercat_motor_driver cmvr_es::proto osqp cmvr_es::device_manager @@ -33,6 +35,10 @@ add_library(cmvr_es::service ALIAS service) install(TARGETS service LIBRARY DESTINATION lib) if(BUILD_TESTING) + add_executable(motor_service_test grpc/tests/motor_service_test.cpp) + target_include_directories(motor_service_test PRIVATE ${CMAKE_SOURCE_DIR}/cmvr-es/manager/device_manager) + target_link_libraries(motor_service_test PRIVATE cmvr_es::service cmvr_es::device::motor_manager gtest gtest_main pthread) + add_test(NAME motor_service_test COMMAND motor_service_test) enable_testing() add_executable(action_queue_test grpc/action/tests/action_queue_test.cpp diff --git a/cmvr-es/service/grpc/include/grpc_motor_service.h b/cmvr-es/service/grpc/include/grpc_motor_service.h new file mode 100644 index 00000000..d350096e --- /dev/null +++ b/cmvr-es/service/grpc/include/grpc_motor_service.h @@ -0,0 +1,94 @@ +#pragma once + +#include "cmvr/api/motor_service.grpc.pb.h" +#include "devices/motor/abstract_motor.h" +#include "manager/device_manager/include/device_manager.h" + +#include + +namespace cmvr::service { + +class gRPCMotorServiceImpl final : public api::MotorService::Service { +public: + gRPCMotorServiceImpl(); + ~gRPCMotorServiceImpl() override = default; + + grpc::Status ListMotors(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorListResponse* response) override; + grpc::Status GetInfo(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status GetState(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status getMode(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status getQ(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status getQd(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status getTau(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status reachedTargetQ(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status setMode(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status torqueOn(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status torqueOff(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status brakeRelease(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status quickStop(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status calibrateZeroQ(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status commandProfilePosition(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status commandProfileVelocity(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status commandProfileTorque(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status commandCyclicPosition(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status commandCyclicVelocity(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status commandCyclicTorque(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status setLimitQ(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status setLimitQd(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + grpc::Status setLimitQdd(grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) override; + +private: + std::shared_ptr getMotor(const api::MotorRequest* request); + + device::DeviceManager& dmgr_; + // Driver getters and setters share cached data; serialize RPC access only. + std::mutex motor_mutex_; +}; + +} // namespace cmvr::service diff --git a/cmvr-es/service/grpc/src/grpc_motor_service.cpp b/cmvr-es/service/grpc/src/grpc_motor_service.cpp new file mode 100644 index 00000000..56cb41a6 --- /dev/null +++ b/cmvr-es/service/grpc/src/grpc_motor_service.cpp @@ -0,0 +1,879 @@ +#include "service/grpc/include/grpc_motor_service.h" + +#include + +#include "common/base/logging/logger.h" +#include "devices/motor/drivers/ethercat_motor/include/ethercat_motor.h" +#include "devices/motor/manager/include/motor_manager.h" + +#include +#include +#include +#include + +using google::protobuf::util::TimeUtil; + +namespace cmvr::service { + +namespace { + +void fillFeedback(api::CommandHeader_Feedback* feedback, + const bool success, + const std::string& message = {}) +{ + feedback->set_success(success); + feedback->set_error_message(message); + *feedback->mutable_timestamp() = TimeUtil::GetCurrentTime(); +} + +void fillMotorInfo(const std::string& device_id, + const std::shared_ptr& motor, + api::MotorInfo* response) +{ + const auto info = motor->motorInfo(); + response->set_manager_id(device_id); + response->set_node_id(motor->id()); + response->set_joint_name(motor->jointName()); + response->set_driver(motor->typeName()); + response->set_limit_q_lb(info.limit_q_lb); + response->set_limit_q_ub(info.limit_q_ub); + response->set_limit_qd(info.limit_qd); + response->set_limit_qdd(info.limit_qdd); +} + +void fillMotorState(const std::shared_ptr& manager, + const std::shared_ptr& motor, + api::MotorDebugState* response) +{ + std::vector positions, velocities, torques; + bool valid = false; + if (std::dynamic_pointer_cast(motor)) { + valid = manager->readFeedbacksAtomic({motor}, positions, velocities, torques); + } else { + valid = manager->readFeedbacksAtomic({motor}, positions, velocities); + torques.push_back(motor->getTau()); + } + valid = valid && positions.size() == 1 && velocities.size() == 1 + && std::isfinite(positions[0]) && std::isfinite(velocities[0]); + response->set_feedback_valid(valid); + if (valid) { + response->set_position(positions[0]); + response->set_velocity(velocities[0]); + } + response->set_torque_valid(valid && torques.size() == 1 && std::isfinite(torques[0])); + if (response->torque_valid()) { + response->set_torque(torques[0]); + } + response->set_torque_unit("per_mille_rated"); + response->set_mode(motor->getMode()); + + std::uint16_t status_word = 0, error_code = 0; + bool enabled = false, fault = false; + response->set_status_valid(motor->readDiagnosticState(status_word, error_code, enabled, fault)); + if (response->status_valid()) { + response->set_status_word(status_word); + response->set_error_code(error_code); + response->set_enabled(enabled); + response->set_fault(fault); + } + response->set_sampled_at_s(std::chrono::duration( + std::chrono::steady_clock::now().time_since_epoch()).count()); +} + +void validateParameters(const api::MotorRequest* request) +{ + for (double value : {request->q(), request->qd(), request->qdd(), + request->tau(), request->upper(), request->lower()}) { + if (!std::isfinite(value)) { + throw std::runtime_error("Motor parameters must be finite"); + } + } +} + +} // namespace + +gRPCMotorServiceImpl::gRPCMotorServiceImpl() + : dmgr_(device::DeviceManager::getInstance()) +{ +} + +std::shared_ptr gRPCMotorServiceImpl::getMotor( + const api::MotorRequest* request) +{ + const std::string device_id = request->header().device_id(); + auto manager = dmgr_.getDevice(device_id); + if (!manager) { + throw std::runtime_error("MotorManager not found: " + device_id); + } + if (request->node_id() > 255) { + throw std::runtime_error("motor node_id exceeds uint8 range"); + } + auto motor = request->joint_name().empty() + ? manager->getMotor(static_cast(request->node_id())) + : manager->getMotor(request->joint_name()); + if (!motor) { + throw std::runtime_error("Motor not found in selected MotorManager"); + } + return motor; +} + +grpc::Status gRPCMotorServiceImpl::ListMotors( + grpc::ServerContext*, + const api::MotorRequest* request, + api::MotorListResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (ListMotors): request, id=" + << request->header().device_id(); + try { + std::lock_guard lock(motor_mutex_); + const std::string device_id = request->header().device_id(); + auto manager = dmgr_.getDevice(device_id); + if (!manager) { + throw std::runtime_error("MotorManager not found: " + device_id); + } + auto motors = manager->motorsSnapshot(); + std::sort(motors.begin(), motors.end(), [](const auto& lhs, const auto& rhs) { + return lhs->id() < rhs->id(); + }); + for (const auto& motor : motors) { + fillMotorInfo(device_id, motor, response->add_motors()); + } + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (ListMotors): success, id=" + << device_id << ", count=" << motors.size(); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (ListMotors): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::GetInfo( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (GetInfo): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (GetInfo): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (GetInfo): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::GetState( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + auto manager = dmgr_.getDevice(device_id); + fillMotorState(manager, motor, response->mutable_state()); + fillFeedback(response->mutable_header(), true); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (GetState): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::getMode( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (getMode): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + response->mutable_state()->set_mode(motor->getMode()); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (getMode): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (getMode): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::getQ( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (getQ): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + response->mutable_state()->set_position(motor->getQ()); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (getQ): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (getQ): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::getQd( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (getQd): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + response->mutable_state()->set_velocity(motor->getQd()); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (getQd): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (getQd): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::getTau( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (getTau): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + const double torque = motor->getTau(); + response->mutable_state()->set_torque_valid(std::isfinite(torque)); + if (std::isfinite(torque)) { + response->mutable_state()->set_torque(torque); + } + response->mutable_state()->set_torque_unit("per_mille_rated"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (getTau): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (getTau): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::reachedTargetQ( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (reachedTargetQ): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + response->set_reached_target(motor->reachedTargetQ()); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (reachedTargetQ): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (reachedTargetQ): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::setMode( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (setMode): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name() + << ", mode=" << request->mode(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + if (!motor->setMode(static_cast(request->mode()))) { + throw std::runtime_error("setMode returned false"); + } + response->set_driver_acknowledged(true); + response->set_detail("Motor API returned true; completion is not implied"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (setMode): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (setMode): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::torqueOn( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (torqueOn): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + if (!motor->torqueOn()) { + throw std::runtime_error("torqueOn returned false"); + } + response->set_driver_acknowledged(true); + response->set_detail("Motor API returned true; completion is not implied"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (torqueOn): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (torqueOn): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::torqueOff( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (torqueOff): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + if (!motor->torqueOff()) { + throw std::runtime_error("torqueOff returned false"); + } + response->set_driver_acknowledged(true); + response->set_detail("Motor API returned true; completion is not implied"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (torqueOff): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (torqueOff): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::brakeRelease( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (brakeRelease): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + if (!motor->brakeRelease()) { + throw std::runtime_error("brakeRelease returned false"); + } + response->set_driver_acknowledged(true); + response->set_detail("Motor API returned true; completion is not implied"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (brakeRelease): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (brakeRelease): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::quickStop( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (quickStop): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + if (!motor->quickStop()) { + throw std::runtime_error("quickStop returned false"); + } + response->set_driver_acknowledged(true); + response->set_detail("Motor API returned true; completion is not implied"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (quickStop): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (quickStop): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::calibrateZeroQ( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (calibrateZeroQ): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + if (!motor->calibrateZeroQ()) { + throw std::runtime_error("calibrateZeroQ returned false"); + } + response->set_driver_acknowledged(true); + response->set_detail("Motor API returned true; completion is not implied"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (calibrateZeroQ): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (calibrateZeroQ): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::commandProfilePosition( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (commandProfilePosition): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name() + << ", q=" << request->q() + << ", qd=" << request->qd() + << ", qdd=" << request->qdd(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + if (!motor->commandProfilePosition(request->q(), request->qd(), request->qdd())) { + throw std::runtime_error("commandProfilePosition returned false"); + } + response->set_driver_acknowledged(true); + response->set_detail("Motor API returned true; completion is not implied"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (commandProfilePosition): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (commandProfilePosition): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::commandProfileVelocity( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (commandProfileVelocity): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name() + << ", qd=" << request->qd() + << ", qdd=" << request->qdd(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + if (!motor->commandProfileVelocity(request->qd(), request->qdd())) { + throw std::runtime_error("commandProfileVelocity returned false"); + } + response->set_driver_acknowledged(true); + response->set_detail("Motor API returned true; completion is not implied"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (commandProfileVelocity): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (commandProfileVelocity): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::commandProfileTorque( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (commandProfileTorque): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name() + << ", tau=" << request->tau() + << ", torque_slope=" << request->torque_slope(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + if (!motor->commandProfileTorque(request->tau(), request->torque_slope())) { + throw std::runtime_error("commandProfileTorque returned false"); + } + response->set_driver_acknowledged(true); + response->set_detail("Motor API returned true; completion is not implied"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (commandProfileTorque): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (commandProfileTorque): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::commandCyclicPosition( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (commandCyclicPosition): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name() + << ", q=" << request->q() + << ", qd=" << request->qd(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + if (!motor->commandCyclicPosition(request->q(), request->qd())) { + throw std::runtime_error("commandCyclicPosition returned false"); + } + response->set_driver_acknowledged(true); + response->set_detail("Motor API returned true; completion is not implied"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (commandCyclicPosition): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (commandCyclicPosition): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::commandCyclicVelocity( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (commandCyclicVelocity): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name() + << ", qd=" << request->qd(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + if (!motor->commandCyclicVelocity(request->qd())) { + throw std::runtime_error("commandCyclicVelocity returned false"); + } + response->set_driver_acknowledged(true); + response->set_detail("Motor API returned true; completion is not implied"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (commandCyclicVelocity): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (commandCyclicVelocity): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::commandCyclicTorque( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (commandCyclicTorque): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name() + << ", tau=" << request->tau(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + if (!motor->commandCyclicTorque(request->tau())) { + throw std::runtime_error("commandCyclicTorque returned false"); + } + response->set_driver_acknowledged(true); + response->set_detail("Motor API returned true; completion is not implied"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (commandCyclicTorque): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (commandCyclicTorque): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::setLimitQ( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (setLimitQ): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name() + << ", upper=" << request->upper() + << ", lower=" << request->lower(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + if (!motor->setLimitQ(request->upper(), request->lower())) { + throw std::runtime_error("setLimitQ returned false"); + } + response->set_driver_acknowledged(true); + response->set_detail("Motor API returned true; completion is not implied"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (setLimitQ): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (setLimitQ): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::setLimitQd( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (setLimitQd): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name() + << ", qd=" << request->qd(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + if (!motor->setLimitQd(request->qd())) { + throw std::runtime_error("setLimitQd returned false"); + } + response->set_driver_acknowledged(true); + response->set_detail("Motor API returned true; completion is not implied"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (setLimitQd): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (setLimitQd): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +grpc::Status gRPCMotorServiceImpl::setLimitQdd( + grpc::ServerContext* context, + const api::MotorRequest* request, + api::MotorResponse* response) +{ + CMVR_LOG(INFO) << "[gRPCMotorServiceImpl] (setLimitQdd): request, id=" + << request->header().device_id() + << ", node_id=" << request->node_id() + << ", joint_name=" << request->joint_name() + << ", upper=" << request->upper() + << ", lower=" << request->lower(); + try { + std::lock_guard lock(motor_mutex_); + if (context->IsCancelled()) { + return grpc::Status(grpc::StatusCode::CANCELLED, "request cancelled"); + } + const std::string device_id = request->header().device_id(); + auto motor = getMotor(request); + fillMotorInfo(device_id, motor, response->mutable_info()); + validateParameters(request); + motor->setLimitQdd(request->upper(), request->lower()); + response->set_driver_acknowledged(false); + response->set_detail("Void motor API returned; hardware acknowledgement is unavailable"); + fillFeedback(response->mutable_header(), true); + CMVR_LOG(DEBUG) << "[gRPCMotorServiceImpl] (setLimitQdd): success, id=" + << device_id << ", node=" << static_cast(motor->id()); + return grpc::Status::OK; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[gRPCMotorServiceImpl] (setLimitQdd): " << e.what(); + fillFeedback(response->mutable_header(), false, e.what()); + return grpc::Status::OK; + } +} + +} // namespace cmvr::service diff --git a/cmvr-es/service/grpc/tests/motor_service_test.cpp b/cmvr-es/service/grpc/tests/motor_service_test.cpp new file mode 100644 index 00000000..a759e41d --- /dev/null +++ b/cmvr-es/service/grpc/tests/motor_service_test.cpp @@ -0,0 +1,104 @@ +#include "service/grpc/include/grpc_motor_service.h" +#include "service/grpc/include/grpc_system_service.h" +#include "manager/device_manager/include/device_manager.h" +#include "devices/motor/manager/include/motor_manager.h" +#include +#include +using namespace cmvr; + +class FakeDirectMotor final : public device::AbstractMotor { +public: + int writes=0;std::string last;double a=0,b=0,c=0;bool reject=false; + bool native_status=false; + explicit FakeDirectMotor(int id){node_id_=id;info_.id=id;info_.joint_name="fake_J"+std::to_string(id);info_.limit_q_lb=-1;info_.limit_q_ub=1;info_.limit_qd=1;info_.limit_qdd=2;} + std::string typeName()const override{return "FakeDirectMotor";} + double getQ()override{return 1.25;} + double getQd()override{return -0.2;} + double getTau()override{return 35;} + msgs::RunMode getMode()override{return msgs::RUN_MODE_PROFILE_POSITION;} + bool readDriveStatus(std::uint16_t& sw,std::uint16_t& error)override{sw=0x27;error=0;return true;} + bool readDiagnosticState(std::uint16_t& sw,std::uint16_t& error,bool& enabled,bool& fault)override{ + if(!native_status)return AbstractMotor::readDiagnosticState(sw,error,enabled,fault); + sw=0;error=8;enabled=true;fault=true;return true; + } + bool reachedTargetQ()override{return true;} + bool record(const char* method,double x=0,double y=0,double z=0){++writes;last=method;a=x;b=y;c=z;return !reject;} + bool setMode(msgs::RunMode mode)override{return record("setMode",mode);} + bool torqueOn()override{return record("torqueOn");} + bool torqueOff()override{return record("torqueOff");} + bool brakeRelease()override{return record("brakeRelease");} + bool quickStop(double = 5.0)override{return record("quickStop");} + bool calibrateZeroQ()override{return record("calibrateZeroQ");} + bool commandProfilePosition(double q,double qd,double qdd)override{return record("commandProfilePosition",q,qd,qdd);} + bool commandProfileVelocity(double qd,double qdd)override{return record("commandProfileVelocity",qd,qdd);} + bool commandProfileTorque(double tau,std::uint32_t slope)override{return record("commandProfileTorque",tau,slope);} + bool commandCyclicPosition(double q,double qd)override{return record("commandCyclicPosition",q,qd);} + bool commandCyclicVelocity(double qd)override{return record("commandCyclicVelocity",qd);} + bool commandCyclicTorque(double tau)override{return record("commandCyclicTorque",tau);} + bool setLimitQ(double upper,double lower)override{return record("setLimitQ",upper,lower);} + bool setLimitQd(double qd)override{return record("setLimitQd",qd);} + void setLimitQdd(double upper,double lower)override{record("setLimitQdd",upper,lower);} +}; +TEST(MotorService, DirectInterfaceDispatchWithoutPlanningOrStatePreflight){ + config::DeviceManagerConfig cfg;auto& dm=device::DeviceManager::getInstance(cfg); + auto manager=std::make_shared("fake_manager",config::MotorConfig{},"fake"); + auto motor=std::make_shared(0);ASSERT_TRUE(manager->addMotor(motor)); + ASSERT_TRUE(manager->addMotor(std::make_shared(2)));dm.registerDevice(manager); + { + service::gRPCSystemServiceImpl system; + grpc::ServerContext context; + api::GetSystemStatusCommand::Request request; + api::GetSystemStatusCommand::Feedback response; + ASSERT_TRUE(system.GetSystemStatus(&context, &request, &response).ok()); + ASSERT_TRUE(response.header().success()); + ASSERT_EQ(response.device_list_size(), 1); + EXPECT_EQ(response.device_list(0).device_id(), "fake_manager"); + EXPECT_EQ(response.device_list(0).device_type(), api::MotorSystem); + } + service::gRPCMotorServiceImpl service;grpc::ServerBuilder builder;int port=0; + builder.AddListeningPort("127.0.0.1:0",grpc::InsecureServerCredentials(),&port);builder.RegisterService(&service); + auto server=builder.BuildAndStart();ASSERT_TRUE(server); + auto stub=api::MotorService::NewStub(grpc::CreateChannel("127.0.0.1:"+std::to_string(port),grpc::InsecureChannelCredentials())); + api::MotorRequest r;r.mutable_header()->set_device_id("fake_manager");r.set_node_id(0); + r.set_mode(8);r.set_q(2.5);r.set_qd(-0.2);r.set_qdd(0.4);r.set_tau(12.5);r.set_torque_slope(150);r.set_upper(3);r.set_lower(-3); + {grpc::ClientContext c;api::MotorListResponse s;ASSERT_TRUE(stub->ListMotors(&c,r,&s).ok());ASSERT_TRUE(s.header().success());ASSERT_EQ(s.motors_size(),2);EXPECT_EQ(s.motors(0).node_id(),0);} +#define READ(name,check) {grpc::ClientContext c;api::MotorResponse s;ASSERT_TRUE(stub->name(&c,r,&s).ok());ASSERT_TRUE(s.header().success())<writes;grpc::ClientContext c;api::MotorResponse s;ASSERT_TRUE(stub->name(&c,r,&s).ok());ASSERT_TRUE(s.header().success())<writes,before+1);EXPECT_EQ(motor->last,#name);check;} + // The fake reports enabled and moving. Dispatch still reaches its exact API; + // no mode-switch heuristic or enable/calibration preflight is injected. + DIRECT(setMode,EXPECT_DOUBLE_EQ(motor->a,8)); + DIRECT(torqueOn,EXPECT_TRUE(s.driver_acknowledged())); + DIRECT(torqueOff,EXPECT_TRUE(s.driver_acknowledged())); + DIRECT(brakeRelease,EXPECT_TRUE(s.driver_acknowledged())); + DIRECT(quickStop,EXPECT_TRUE(s.driver_acknowledged())); + DIRECT(calibrateZeroQ,EXPECT_TRUE(s.driver_acknowledged())); + DIRECT(commandProfilePosition,EXPECT_DOUBLE_EQ(motor->a,2.5);EXPECT_DOUBLE_EQ(motor->b,-0.2);EXPECT_DOUBLE_EQ(motor->c,0.4)); + DIRECT(commandProfileVelocity,EXPECT_DOUBLE_EQ(motor->a,-0.2);EXPECT_DOUBLE_EQ(motor->b,0.4)); + DIRECT(commandProfileTorque,EXPECT_DOUBLE_EQ(motor->a,12.5);EXPECT_DOUBLE_EQ(motor->b,150)); + DIRECT(commandCyclicPosition,EXPECT_DOUBLE_EQ(motor->a,2.5);EXPECT_DOUBLE_EQ(motor->b,-0.2)); + DIRECT(commandCyclicVelocity,EXPECT_DOUBLE_EQ(motor->a,-0.2)); + DIRECT(commandCyclicTorque,EXPECT_DOUBLE_EQ(motor->a,12.5)); + DIRECT(setLimitQ,EXPECT_DOUBLE_EQ(motor->a,3);EXPECT_DOUBLE_EQ(motor->b,-3)); + DIRECT(setLimitQd,EXPECT_DOUBLE_EQ(motor->a,-0.2)); + DIRECT(setLimitQdd,EXPECT_DOUBLE_EQ(motor->a,3);EXPECT_DOUBLE_EQ(motor->b,-3);EXPECT_FALSE(s.driver_acknowledged())); +#undef DIRECT + motor->reject=true; + {grpc::ClientContext c;api::MotorResponse s;stub->torqueOn(&c,r,&s);EXPECT_FALSE(s.header().success());EXPECT_EQ(s.header().error_message(),"torqueOn returned false");} + r.set_node_id(256); + {grpc::ClientContext c;api::MotorResponse s;stub->getQ(&c,r,&s);EXPECT_FALSE(s.header().success());} + // A native CAN state byte of zero means enabled here, NOT CiA402 disabled. + motor->native_status=true;r.set_node_id(0); + {grpc::ClientContext c;api::MotorResponse s;ASSERT_TRUE(stub->GetState(&c,r,&s).ok()); + ASSERT_TRUE(s.header().success());EXPECT_TRUE(s.state().status_valid()); + EXPECT_TRUE(s.state().enabled());EXPECT_TRUE(s.state().fault()); + EXPECT_EQ(s.state().status_word(),0);EXPECT_EQ(s.state().error_code(),8);} + server->Shutdown();device::DeviceManager::destroyInstance(); +} diff --git a/cmvr-es/simulate/mujoco/mujoco_world/CMakeLists.txt b/cmvr-es/simulate/mujoco/mujoco_world/CMakeLists.txt index ca69f6ca..73157286 100644 --- a/cmvr-es/simulate/mujoco/mujoco_world/CMakeLists.txt +++ b/cmvr-es/simulate/mujoco/mujoco_world/CMakeLists.txt @@ -13,3 +13,10 @@ target_link_libraries(mujoco_world PUBLIC add_library(cmvr_es::mujoco_world ALIAS mujoco_world) install(TARGETS mujoco_world LIBRARY DESTINATION lib) + +if(BUILD_TESTING) + add_executable(mujoco_batch_feedback_test tests/mujoco_batch_feedback_test.cpp) + target_include_directories(mujoco_batch_feedback_test PRIVATE ${CMAKE_SOURCE_DIR}/cmvr-es) + target_link_libraries(mujoco_batch_feedback_test PRIVATE cmvr_es::mujoco_world gtest gtest_main pthread) + add_test(NAME mujoco_batch_feedback_test COMMAND mujoco_batch_feedback_test) +endif() diff --git a/cmvr-es/simulate/mujoco/mujoco_world/include/mujoco_world.h b/cmvr-es/simulate/mujoco/mujoco_world/include/mujoco_world.h index 1ebd4bf9..99099e5f 100644 --- a/cmvr-es/simulate/mujoco/mujoco_world/include/mujoco_world.h +++ b/cmvr-es/simulate/mujoco/mujoco_world/include/mujoco_world.h @@ -54,6 +54,8 @@ public: bool getJointPosition(const std::string& joint_name, double& position) const; bool getJointVelocity(const std::string& joint_name, double& velocity) const; + bool getJointStates(const std::vector& names, + std::vector& positions, std::vector& velocities) const; bool setJointPosition(const std::string& joint_name, double position); bool setJointVelocity(const std::string& joint_name, double velocity); bool setJointTargetPosition(const std::string& joint_name, double position); @@ -66,6 +68,8 @@ public: const std::vector& positions, const std::vector& velocities); bool setJointTargetVelocity(const std::string& joint_name, double velocity); + bool setJointTargetVelocities(const std::vector& names, + const std::vector& velocities); mjModel* model(); mjData* data(); diff --git a/cmvr-es/simulate/mujoco/mujoco_world/src/mujoco_world.cpp b/cmvr-es/simulate/mujoco/mujoco_world/src/mujoco_world.cpp index 0f29ad02..6527c19f 100644 --- a/cmvr-es/simulate/mujoco/mujoco_world/src/mujoco_world.cpp +++ b/cmvr-es/simulate/mujoco/mujoco_world/src/mujoco_world.cpp @@ -277,6 +277,51 @@ bool MujocoWorld::setJointPosition(const std::string& joint_name, const double p return true; } +bool MujocoWorld::getJointStates(const std::vector& names, + std::vector& positions, std::vector& velocities) const +{ + if (names.empty() || &positions == &velocities) return false; + std::lock_guard lock(mutex_); + std::vector joints; + for (const auto& name : names) { + const JointHandle* joint = nullptr; + if (!findJointLocked(name, joint) || + std::find(joints.begin(), joints.end(), joint) != joints.end() || + !std::isfinite(data_->qpos[joint->qpos_adr]) || + !std::isfinite(data_->qvel[joint->qvel_adr])) return false; + joints.push_back(joint); + } + positions.resize(joints.size()); + velocities.resize(joints.size()); + for (std::size_t i = 0; i < joints.size(); ++i) { + positions[i] = data_->qpos[joints[i]->qpos_adr]; + velocities[i] = data_->qvel[joints[i]->qvel_adr]; + } + return true; +} + +bool MujocoWorld::setJointTargetVelocities(const std::vector& names, + const std::vector& velocities) +{ + if (names.empty() || names.size() != velocities.size()) return false; + std::lock_guard lock(mutex_); + std::vector joints; + for (std::size_t i = 0; i < names.size(); ++i) { + JointHandle* joint = nullptr; + if (!std::isfinite(velocities[i]) || !findJointLocked(names[i], joint) || + std::find(joints.begin(), joints.end(), joint) != joints.end()) return false; + joints.push_back(joint); + } + // Validate all entries before changing any command. + for (std::size_t i = 0; i < joints.size(); ++i) { + auto* joint = joints[i]; + if (joint->mode != TargetMode::DirectVelocity) joint->position_reference = data_->qpos[joint->qpos_adr]; + joint->target_velocity = velocities[i]; + joint->mode = TargetMode::DirectVelocity; + } + return true; +} + bool MujocoWorld::setJointVelocity(const std::string& joint_name, const double velocity) { std::lock_guard lock(mutex_); diff --git a/cmvr-es/simulate/mujoco/mujoco_world/tests/mujoco_batch_feedback_test.cpp b/cmvr-es/simulate/mujoco/mujoco_world/tests/mujoco_batch_feedback_test.cpp new file mode 100644 index 00000000..0cce7ca0 --- /dev/null +++ b/cmvr-es/simulate/mujoco/mujoco_world/tests/mujoco_batch_feedback_test.cpp @@ -0,0 +1,42 @@ +#include "simulate/mujoco/mujoco_world/include/mujoco_world.h" +#include +#include +#include +#include +#include + +TEST(MujocoBatchFeedback, ValidatesBatchAndPreservesFeedbackOnFailure) +{ + char path[] = "/tmp/cmvr-mujoco-batch-XXXXXX"; + const int fd = mkstemp(path); + ASSERT_GE(fd, 0); + close(fd); + struct Cleanup { const char* path; ~Cleanup() { std::remove(path); } } cleanup{path}; + { + std::ofstream file(path); + file << R"()"; + } + cmvr::simulate::MujocoWorld world; + cmvr::simulate::MujocoWorld::Options options; + options.model_path = path; + options.allow_state_control_fallback = true; + options.joints = {{"j1", true}, {"j2", true}}; + ASSERT_TRUE(world.load(options)) << world.lastError(); + ASSERT_TRUE(world.setJointPosition("j1", 0.4)); + ASSERT_TRUE(world.setJointPosition("j2", -0.2)); + ASSERT_TRUE(world.setJointVelocity("j1", 0.3)); + ASSERT_TRUE(world.setJointVelocity("j2", -0.1)); + std::vector q, qd; + ASSERT_TRUE(world.getJointStates({"j1", "j2"}, q, qd)); + EXPECT_EQ(q, (std::vector{0.4, -0.2})); + EXPECT_EQ(qd, (std::vector{0.3, -0.1})); + const auto previous = q; + EXPECT_FALSE(world.getJointStates({"j1", "missing"}, q, qd)); + EXPECT_EQ(q, previous); + EXPECT_FALSE(world.getJointStates({"j1", "j1"}, q, qd)); + EXPECT_FALSE(world.getJointStates({"j1"}, q, q)); + EXPECT_FALSE(world.setJointTargetVelocities({"j1", "j2"}, {0.1})); + EXPECT_FALSE(world.setJointTargetVelocities({"j1", "j1"}, {0.1, 0.2})); + EXPECT_FALSE(world.setJointTargetVelocities({"j1", "j2"}, {0.1, std::numeric_limits::quiet_NaN()})); + EXPECT_TRUE(world.setJointTargetVelocities({"j1", "j2"}, {0.1, -0.2})); +} diff --git a/cmvr-es/task/grpc_server_task/include/grpc_server_task.h b/cmvr-es/task/grpc_server_task/include/grpc_server_task.h index 8a24bf61..e6b4469b 100644 --- a/cmvr-es/task/grpc_server_task/include/grpc_server_task.h +++ b/cmvr-es/task/grpc_server_task/include/grpc_server_task.h @@ -59,6 +59,7 @@ private: std::unique_ptr dexhand_service_; std::unique_ptr biohand_service_; std::unique_ptr arm_service_; + std::unique_ptr motor_service_; std::unique_ptr agv_service_; std::unique_ptr hlc_service_; }; diff --git a/cmvr-es/task/grpc_server_task/src/grpc_server_task.cpp b/cmvr-es/task/grpc_server_task/src/grpc_server_task.cpp index 65c91dd4..22d9019b 100644 --- a/cmvr-es/task/grpc_server_task/src/grpc_server_task.cpp +++ b/cmvr-es/task/grpc_server_task/src/grpc_server_task.cpp @@ -10,6 +10,7 @@ #include "common/config/config_files.h" #include "service/grpc/include/grpc_agv_service.h" #include "service/grpc/include/grpc_arm_service.h" +#include "service/grpc/include/grpc_motor_service.h" #include "service/grpc/include/grpc_camera_service.h" #include "service/grpc/include/grpc_dexhand_service.h" #include "service/grpc/include/grpc_head_service.h" @@ -102,6 +103,7 @@ bool GrpcServerTask::start() dexhand_service_ = std::make_unique(); biohand_service_ = std::make_unique(); arm_service_ = std::make_unique(); + motor_service_ = std::make_unique(); agv_service_ = std::make_unique(); hlc_service_ = std::make_unique(); @@ -114,6 +116,7 @@ bool GrpcServerTask::start() builder.RegisterService(dexhand_service_.get()); builder.RegisterService(biohand_service_.get()); builder.RegisterService(arm_service_.get()); + builder.RegisterService(motor_service_.get()); builder.RegisterService(agv_service_.get()); builder.RegisterService(hlc_service_.get()); @@ -255,6 +258,7 @@ void GrpcServerTask::clearServices() hlc_service_.reset(); agv_service_.reset(); arm_service_.reset(); + motor_service_.reset(); biohand_service_.reset(); dexhand_service_.reset(); microphone_service_.reset(); diff --git a/protos/cmvr/api/motor_service.proto b/protos/cmvr/api/motor_service.proto new file mode 100644 index 00000000..26154f89 --- /dev/null +++ b/protos/cmvr/api/motor_service.proto @@ -0,0 +1,88 @@ +syntax = "proto3"; +package cmvr.api; +import "cmvr/api/common.proto"; + +// header.device_id identifies a MotorManager, NOT an individual motor. +// A nonempty joint_name selects by name; otherwise node_id (including 0) is used. +message MotorRequest { + CommandHeader.Request header = 1; + uint32 node_id = 2; + string joint_name = 3; + reserved 4; // Retired UI confirmation flag. + int32 mode = 5; // cmvr.msgs.RunMode numeric values. + double q = 6; // rad + double qd = 7; // rad/s: profile speed or cyclic velocity/feedforward, per driver API. + double qdd = 8; // rad/s^2: profile acceleration parameter. + double tau = 9; // Per mille of rated torque: 1000 = rated torque. + double upper = 10; + double lower = 11; + uint32 torque_slope = 12; // Per mille/s, > 0 for profile torque. + reserved 13 to 16; // Retired gRPC planning parameters. +} +message MotorInfo { + string manager_id = 1; + uint32 node_id = 2; + string joint_name = 3; + string driver = 4; + // Software/configured limits; these are NOT an SDO dictionary readback. + double limit_q_lb = 5; + double limit_q_ub = 6; + double limit_qd = 7; + double limit_qdd = 8; + reserved 9; // Retired planning capability. +} +message MotorDebugState { + double position = 1; // rad + double velocity = 2; // rad/s + bool feedback_valid = 3; + double torque = 4; + bool torque_valid = 5; + string torque_unit = 6; // "per_mille_rated" (not N*m). + int32 mode = 7; + uint32 status_word = 8; + uint32 error_code = 9; + bool enabled = 10; + bool fault = 11; + bool status_valid = 12; + reserved 13, 14; // No current getter in this branch's AbstractMotor contract. + double sampled_at_s = 15; +} +message MotorResponse { + CommandHeader.Feedback header = 1; + MotorInfo info = 2; + MotorDebugState state = 3; + bool reached_target = 4; + // False for void setters; true only means the driver's bool result was true. + bool driver_acknowledged = 5; + string detail = 6; + reserved 7; // Retired background trajectory status. +} +message MotorListResponse { + CommandHeader.Feedback header = 1; + repeated MotorInfo motors = 2; +} +service MotorService { + rpc ListMotors(MotorRequest) returns (MotorListResponse); + rpc GetInfo(MotorRequest) returns (MotorResponse); + rpc GetState(MotorRequest) returns (MotorResponse); + rpc getMode(MotorRequest) returns (MotorResponse); + rpc getQ(MotorRequest) returns (MotorResponse); + rpc getQd(MotorRequest) returns (MotorResponse); + rpc getTau(MotorRequest) returns (MotorResponse); + rpc reachedTargetQ(MotorRequest) returns (MotorResponse); + rpc setMode(MotorRequest) returns (MotorResponse); + rpc torqueOn(MotorRequest) returns (MotorResponse); + rpc torqueOff(MotorRequest) returns (MotorResponse); + rpc brakeRelease(MotorRequest) returns (MotorResponse); + rpc quickStop(MotorRequest) returns (MotorResponse); + rpc calibrateZeroQ(MotorRequest) returns (MotorResponse); + rpc commandProfilePosition(MotorRequest) returns (MotorResponse); + rpc commandProfileVelocity(MotorRequest) returns (MotorResponse); + rpc commandProfileTorque(MotorRequest) returns (MotorResponse); + rpc commandCyclicPosition(MotorRequest) returns (MotorResponse); + rpc commandCyclicVelocity(MotorRequest) returns (MotorResponse); + rpc commandCyclicTorque(MotorRequest) returns (MotorResponse); + rpc setLimitQ(MotorRequest) returns (MotorResponse); + rpc setLimitQd(MotorRequest) returns (MotorResponse); + rpc setLimitQdd(MotorRequest) returns (MotorResponse); +} diff --git a/protos/cmvr/config/motor_config/motor_config.proto b/protos/cmvr/config/motor_config/motor_config.proto index 7c166df9..5f9952b5 100644 --- a/protos/cmvr/config/motor_config/motor_config.proto +++ b/protos/cmvr/config/motor_config/motor_config.proto @@ -12,6 +12,21 @@ message MotorConfigItem { double limit_qdd = 6; double encoder_counts_per_rev = 7; double gear_ratio = 8; + LingkongMotorConfig lingkong = 9; +} + +// Vendor CAN protocol, not CiA301 CANopen. Zero conversion values mean unknown. +message LingkongMotorConfig { + // MG: 66/4096 A/LSB; MF: 33/4096 A/LSB. Do not use for MS power data. + double current_amp_per_lsb = 1; + // Required to convert current to the common API's per-mille rated torque. + double rated_torque_current_a = 2; + // B1 indices 12/14: the supplied protocol manual does not define their units. + // Populate only after confirming the drive firmware's parameter units. + double acceleration_deg_s2_per_lsb = 3; + double speed_limit_deg_s_per_lsb = 4; + uint32 response_timeout_ms = 5; + double reached_position_tolerance_rad = 6; } message MotorList { @@ -81,6 +96,8 @@ enum MotorVendor { MOTOR_VENDOR_TI5 = 1; MOTOR_VENDOR_MUJOCO = 2; MOTOR_VENDOR_EYOU = 3; + MOTOR_VENDOR_TCHL = 4; + MOTOR_VENDOR_LINGKONG = 5; } enum MotorProtocol { @@ -88,6 +105,7 @@ enum MotorProtocol { MOTOR_PROTOCOL_CANOPEN = 1; MOTOR_PROTOCOL_ETHERCAT_CIA402 = 2; MOTOR_PROTOCOL_MUJOCO = 3; + MOTOR_PROTOCOL_LINGKONG_CAN = 4; } message MotorGroupConfig { diff --git a/script/ethercat/start_ethercat.sh b/script/ethercat/start_ethercat.sh old mode 100755 new mode 100644 index c1b9deeb..837a4a12 --- a/script/ethercat/start_ethercat.sh +++ b/script/ethercat/start_ethercat.sh @@ -65,7 +65,7 @@ done SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" IGH_ROOT="${IGH_ROOT:-${REPO_ROOT}/dependency/x86/third_party/ethercat/v1.7.0}" -DEVICE_MODULES="${DEVICE_MODULES:-generic}" +DEVICE_MODULES="${DEVICE_MODULES:-igc}" ETHERCAT_CONF="${ETHERCAT_CONF:-${IGH_ROOT}/etc/ethercat.conf}" ETHERCATCTL="${IGH_ROOT}/sbin/ethercatctl" ETHERCAT="${IGH_ROOT}/bin/ethercat"