From 021ccfb085b72b75d5fee5fee9beb9ab0c37112d Mon Sep 17 00:00:00 2001 From: linbo <1034003879@qq.com> Date: Mon, 9 Nov 2026 15:04:15 +0800 Subject: [PATCH] fix(lingkong): support CAN protocol versions and report actual drive state --- .../arm/motor_robot_arm/CMakeLists.txt | 3 + .../include/lingkong_arm_diagnostics.h | 33 ++ .../motor_robot_arm/include/motor_robot_arm.h | 4 +- .../src/lingkong_arm_diagnostics_test.cpp | 43 +++ .../motor_robot_arm/src/motor_robot_arm.cpp | 8 +- .../drivers/lingkong_can/MANUAL_AUDIT.md | 24 ++ .../drivers/lingkong_can/PROTOCOL_VERSIONS.md | 8 + .../include/lingkong_can_protocol.h | 22 +- .../protocol/lingkong_motor_response.h | 7 + .../src/lingkong_can_protocol.cpp | 89 +++-- .../lingkong_can/src/lingkong_motor.cpp | 2 +- .../src/protocol/lingkong_motor_response.cpp | 16 +- .../tests/lingkong_motor_protocol_test.cpp | 328 +++++++++++++++++- cmvr-es/devices/motor/manager/CMakeLists.txt | 2 +- .../motor/manager/src/motor_manager.cpp | 45 ++- .../src/motor_manager_shutdown_test.cpp | 42 +++ .../config/motor_config/motor_config.proto | 1 + 17 files changed, 621 insertions(+), 56 deletions(-) create mode 100644 cmvr-es/devices/arm/motor_robot_arm/include/lingkong_arm_diagnostics.h create mode 100644 cmvr-es/devices/arm/motor_robot_arm/src/lingkong_arm_diagnostics_test.cpp create mode 100644 cmvr-es/devices/motor/drivers/lingkong_can/MANUAL_AUDIT.md create mode 100644 cmvr-es/devices/motor/drivers/lingkong_can/PROTOCOL_VERSIONS.md diff --git a/cmvr-es/devices/arm/motor_robot_arm/CMakeLists.txt b/cmvr-es/devices/arm/motor_robot_arm/CMakeLists.txt index 4ca9739b..85ecabdd 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/CMakeLists.txt +++ b/cmvr-es/devices/arm/motor_robot_arm/CMakeLists.txt @@ -74,3 +74,6 @@ target_link_libraries(motor_robot_arm_gen2_mujoco_test gtest_main pthread ) + +add_executable(lingkong_arm_diagnostics_test src/lingkong_arm_diagnostics_test.cpp) +target_link_libraries(lingkong_arm_diagnostics_test PRIVATE cmvr_es::device::motor_robot_arm cmvr_es::device::motor_core gtest gtest_main pthread) diff --git a/cmvr-es/devices/arm/motor_robot_arm/include/lingkong_arm_diagnostics.h b/cmvr-es/devices/arm/motor_robot_arm/include/lingkong_arm_diagnostics.h new file mode 100644 index 00000000..33322b83 --- /dev/null +++ b/cmvr-es/devices/arm/motor_robot_arm/include/lingkong_arm_diagnostics.h @@ -0,0 +1,33 @@ +#pragma once +#include +#include +#include +#include "common/types/arm/arm_types.h" +#include "motor/abstract_motor.h" +namespace cmvr::device::detail { +// Only a group containing Lingkong drives opts in; other backends retain their +// own semantics. Never infer enabled state from supply power or command success. +inline void applyLingkongArmDiagnostics(ArmState& state, + const std::vector>& motors) { + if (!std::any_of(motors.begin(), motors.end(), [](const auto& motor) { + return motor && motor->typeName() == "LingkongMotor"; + })) return; + bool all_read = true, all_enabled = true, any_fault = false; + for (const auto& motor : motors) { + uint16_t status=0, error=0; bool enabled=false, fault=false, ok=false; + try { ok = motor && motor->readDiagnosticState(status,error,enabled,fault); } + catch (...) { ok = false; } + all_read &= ok; + all_enabled &= ok && enabled && !fault && error == 0; + any_fault |= !ok || fault || error != 0; + } + state.connected = state.connected && all_read; + state.powered_on = all_read && all_enabled; + state.fault = state.fault || any_fault; + if (!all_read) state.robot_mode = RobotMode::Disconnected; + else if (state.fault) state.robot_mode = RobotMode::Fault; + else if (!all_enabled) state.robot_mode = RobotMode::PowerOff; + if (state.fault && !state.emergency_stopped && !state.protective_stopped) + state.safety_mode = SafetyMode::Fault; +} +} diff --git a/cmvr-es/devices/arm/motor_robot_arm/include/motor_robot_arm.h b/cmvr-es/devices/arm/motor_robot_arm/include/motor_robot_arm.h index 1c869866..73652d52 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/include/motor_robot_arm.h +++ b/cmvr-es/devices/arm/motor_robot_arm/include/motor_robot_arm.h @@ -39,9 +39,7 @@ public: ArmState getRobotState() const override; JointGroupState getJointState() const override; CartesianPose getTcpPose(FrameType frame = FrameType::Base) const override; - RobotMode getRobotMode() const override { - return isFault() ? RobotMode::Fault : (busy() ? RobotMode::Running : RobotMode::Idle); - } + RobotMode getRobotMode() const override { return getRobotState().robot_mode; } SafetyMode getSafetyMode() const override; ControlMode getControlMode() const override { return ControlMode::Position; } diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/lingkong_arm_diagnostics_test.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/lingkong_arm_diagnostics_test.cpp new file mode 100644 index 00000000..1bc8306a --- /dev/null +++ b/cmvr-es/devices/arm/motor_robot_arm/src/lingkong_arm_diagnostics_test.cpp @@ -0,0 +1,43 @@ +#include "arm/motor_robot_arm/include/lingkong_arm_diagnostics.h" +#include +#include +using namespace cmvr::device; +namespace { +class Drive final : public AbstractMotor { +public: + bool enabled=false, fault=false, ok=true, throws=false; uint16_t error=0; + std::string typeName() const override { return "LingkongMotor"; } + bool setLimitQ(double,double) override{return true;} + bool setLimitQd(double) override{return true;} + bool brakeRelease() override{return true;} + bool calibrateZeroQ() override{return true;} + bool readDiagnosticState(uint16_t& s,uint16_t& e,bool& on,bool& f) override { + if(throws)throw std::runtime_error("timeout"); + s=enabled?0x30:0x20;e=error;on=enabled;f=fault;return ok; + } +}; +ArmState initial(){ArmState s;s.connected=true;s.powered_on=true;s.robot_mode=RobotMode::Idle;return s;} +TEST(LingkongArmDiagnostics, AllDisabledOverridesPreviouslyEnabledState){ + auto a=std::make_shared();auto b=std::make_shared();auto c=std::make_shared();auto s=initial(); + detail::applyLingkongArmDiagnostics(s,{a,b,c});EXPECT_TRUE(s.connected);EXPECT_FALSE(s.powered_on);EXPECT_FALSE(s.fault);EXPECT_EQ(s.robot_mode,RobotMode::PowerOff); +} +TEST(LingkongArmDiagnostics, OnlyAllEnabledReportsEnabled){ + auto a=std::make_shared();auto b=std::make_shared();a->enabled=true;auto s=initial(); + detail::applyLingkongArmDiagnostics(s,{a,b});EXPECT_FALSE(s.powered_on); + b->enabled=true;s=initial();detail::applyLingkongArmDiagnostics(s,{a,b});EXPECT_TRUE(s.powered_on);EXPECT_FALSE(s.fault); +} +TEST(LingkongArmDiagnostics, FaultAndHighErrorAreNotHealthy){ + auto a=std::make_shared();a->enabled=true;a->error=0x200;auto s=initial();detail::applyLingkongArmDiagnostics(s,{a}); + EXPECT_FALSE(s.powered_on);EXPECT_TRUE(s.fault);EXPECT_EQ(s.robot_mode,RobotMode::Fault);EXPECT_EQ(s.safety_mode,SafetyMode::Fault); +} +TEST(LingkongArmDiagnostics, MissingReplyAndExceptionsNeverKeepEnabled){ + auto a=std::make_shared();a->enabled=true; + for(bool raises:{false,true}){a->throws=raises;a->ok=false;auto s=initial();EXPECT_NO_THROW(detail::applyLingkongArmDiagnostics(s,{a}));EXPECT_FALSE(s.connected);EXPECT_FALSE(s.powered_on);EXPECT_TRUE(s.fault);EXPECT_EQ(s.robot_mode,RobotMode::Disconnected);} +} +TEST(LingkongArmDiagnostics, MissingAxisIsNotAllEnabled){ + auto a=std::make_shared();a->enabled=true;auto s=initial();detail::applyLingkongArmDiagnostics(s,{a,nullptr});EXPECT_FALSE(s.powered_on);EXPECT_FALSE(s.connected); +} +TEST(LingkongArmDiagnostics, EmptyGroupKeepsOtherBackendBehavior){ + auto s=initial();detail::applyLingkongArmDiagnostics(s,{});EXPECT_TRUE(s.powered_on);EXPECT_TRUE(s.connected); +} +} diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm.cpp index 01e2657b..da3ef663 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm.cpp +++ b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm.cpp @@ -1,4 +1,5 @@ #include "arm/motor_robot_arm/include/motor_robot_arm.h" +#include "arm/motor_robot_arm/include/lingkong_arm_diagnostics.h" #include #include @@ -168,10 +169,13 @@ ArmState MotorRobotArm::getRobotState() const state.protective_stopped = protective_stopped; state.emergency_stopped = emergency_stopped; state.speed_scaling = speed_scaling_.load(); - state.robot_mode = getRobotMode(); + state.robot_mode = isFault() ? RobotMode::Fault : (busy() ? RobotMode::Running : RobotMode::Idle); state.fault = isFault(); state.safety_mode = getSafetyMode(); state.control_mode = ControlMode::Position; + std::vector> diagnostic_motors; + for (const auto& name : joint_names_) diagnostic_motors.push_back(getMotor_(name)); + detail::applyLingkongArmDiagnostics(state, diagnostic_motors); state.actual_joint_state = getJointState(); const auto& q = state.actual_joint_state.position; const auto& qd = state.actual_joint_state.velocity; @@ -179,7 +183,7 @@ ArmState MotorRobotArm::getRobotState() const !std::all_of(q.begin(), q.end(), [](double v) { return std::isfinite(v); }) || !std::all_of(qd.begin(), qd.end(), [](double v) { return std::isfinite(v); })) { state.fault = true; - state.robot_mode = RobotMode::Fault; + state.robot_mode = state.connected ? RobotMode::Fault : RobotMode::Disconnected; return state; } if (!ik_solver_) { diff --git a/cmvr-es/devices/motor/drivers/lingkong_can/MANUAL_AUDIT.md b/cmvr-es/devices/motor/drivers/lingkong_can/MANUAL_AUDIT.md new file mode 100644 index 00000000..531c8fb5 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/lingkong_can/MANUAL_AUDIT.md @@ -0,0 +1,24 @@ +# In-use command audit: supplied V2.36 and V2.38 manuals + +Scope: all commands emitted by LingkongCanProtocol, response correlation, diagnostics, and group shutdown. Unused calibration/reset commands are deliberately not added. + +| Commands | V2.36 | V2.38 | Implementation | +| --- | --- | --- | --- | +| CAN framing | Standard ID 0x140+node; 8 bytes, LE | Same | Shared request/response transport | +| 80 / 88 | Echo acknowledgement; OFF=10, ON=00 | Echo acknowledgement; OFF=20, ON=30 | Verify 9A using selected version, never treat ACK as motion completion | +| 81 | Stop, without closing | Stop, preserves prior control state | Group all-zero stop uses 81 on every axis, including already-OFF drives; exceptions/failures cannot bypass later axes | +| 8C | Byte 1 brake command/state | Same | Shared release command and response matching | +| 9A / 9B | Byte 6 state, byte 7 8-bit error; bus voltage/current 0.01 | State=byte6 high nibble; error=byte6 low nibble + byte7, 12 bits; manual says mV/mA | Selected scaling, full error checks, ERROR state blocks initialization even with zero error bits | +| 9C | int16 Iq, int16 speed in dps | Same layout; Iq A/LSB unspecified | Signed feedback; explicit current conversion only | +| 92 | Signed 56-bit payload, 0.01 degree | Same | Sign extend bit 55, use configured gear ratio | +| A1 | int16 Iq bytes4..5, documented +/-2048 | int16 Iq same bytes; no physical conversion/range stated | Signed frame and explicit rated-current/Iq conversion; retain existing conservative +/-2048 software bound (do not expand physical outputs based on field width) | +| A2 | Bytes2..3 NULL, speed int32 bytes4..7 in 0.01dps | Bytes2..3 torque limit int16, speed unchanged | V2.38 reads C0/30 limit and embeds it; old path leaves NULL | +| A3 / A4 | int32 multi-turn target in 0.01 degree; A4 uint16 speed dps | Same | Shared position conversion/range/limit checks; A4 current-position hold on enable | +| B0/B1 vs C0/C1 | Scalar indices10 torque,12 acceleration,14 speed | Scalar30 torque,32 speed,34 angle,36 current ramp,38 speed ramp; PID triplets10/11/12 | Versioned command/index/width/range checks; parameter reply index matching; scalar API rejects PID triplets | +| Speed limit API | B1/14, explicit unit conversion | C1/32, 0.01 dps | Versioned native speed conversion | +| Acceleration API | B1/12, units not specified | C1/38 ramp, physical units not specified | Requires explicit confirmed conversion; never send V2.38 PID index12 as acceleration; profile qdd retains drive settings as before | +| 19 permanent zero | uint16 offset bytes6..7; repower explicitly required | uint32 offset bytes4..7; encoder type in byte3 (manual gives 0 for single encoder; observed type1 is preserved and accepted); activation timing unspecified | Unsigned decode, version-specific log; ACK only, no immediate position readback, automatic reboot, or zero writes during init | + +Protocol selection remains the EXISTING group `protocol` field: MOTOR_PROTOCOL_LINGKONG_CAN or MOTOR_PROTOCOL_LINGKONG_CAN_V2_38. No new configuration fields. The old enum now selects strict V2.36 ON=00/OFF=10, replacing the earlier permissive site policy. The permissive historical mode has been removed. V2.38 production selection is strict ON=30/OFF=20 and rejects INIT/ERROR/CALIBRATION as enabled. Never select a protocol by voltage or model label alone. + +Unresolved manual/firmware facts: V2.38 manual specifies millivolts, while previously captured approximately 48V device samples (raw about 4800) would decode as approximately 4.8V under that specification. The implementation follows the supplied document without silent rescaling. Confirm this discrepancy with the drive vendor before relying on voltage telemetry. Iq A/LSB and speed-ramp physical units also require firmware-specific confirmation; no default conversion is invented. No hardware motion or ROM writes are used for this audit. diff --git a/cmvr-es/devices/motor/drivers/lingkong_can/PROTOCOL_VERSIONS.md b/cmvr-es/devices/motor/drivers/lingkong_can/PROTOCOL_VERSIONS.md new file mode 100644 index 00000000..a7b01bf1 --- /dev/null +++ b/cmvr-es/devices/motor/drivers/lingkong_can/PROTOCOL_VERSIONS.md @@ -0,0 +1,8 @@ +# Lingkong CAN protocol versions +Existing configuration files remain unchanged. Use the existing group `protocol` field: `MOTOR_PROTOCOL_LINGKONG_CAN` selects strict V2.36 behavior; `MOTOR_PROTOCOL_LINGKONG_CAN_V2_38` selects V2.38. No new configuration fields. Mixed versions use distinct motor groups with the same CAN device/channel and unique motor IDs. Both production selections use the documented version-specific states. V2_36: ON=0x00, OFF=0x10. V2_38: ON=0x30, OFF=0x20, INIT/ERROR/CALIBRATION never count as enabled; 12-bit errors include the low nibble of byte 6. Diagnostics preserve the state in its high-nibble representation. + +V2_38 status voltage/current follow the supplied manual units mV/mA (0.001). Earlier observed firmware used different scaling; verify actual firmware against the manual before relying on telemetry. + +Scalar parameter API takes native indices: V2_36 B0/B1 10/12/14; V2_38 C0/C1 30/32/34/36/38. V2_38 PID triplets 10/11/12 are rejected by the scalar API. setLimitQd uses C1/32 with 0.01 dps units. Acceleration uses C1/38 ONLY with an explicitly confirmed acceleration_deg_s2_per_lsb conversion; the supplied V2.38 manual does not define ramp physical units. Profile motion retains drive acceleration as before. Current/Iq conversion remains explicitly configured because V2.38 does not specify its A/LSB conversion. A1/A3/A4 motion and 92 angle layouts are shared. A2 speed units are shared, but V2.38 adds a torque limit, which is read from C0/30 and included in the command. + +Permanent zero uses 19 in both versions, no immediate position readback, reboot or motion. Reply zero-offset bytes are 6..7 in V2.36 and 4..7 in V2.38. Restart/power-cycle requirements follow the drive firmware. No automatic protocol probing or firmware writes are performed. 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 index 2ec12916..c6b5e409 100644 --- 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 @@ -18,16 +18,27 @@ class LingkongCanProtocol final : public MotorProtocolInterface { public: using Payload = motor::LingkongMotorRequest::Payload; using Send = std::function; + enum ProtocolVersion { V2_36 = 1, V2_38 = 2 }; struct Status { double temperature{0}, voltage{0}, bus_current{0}; - uint8_t motor_state{0}, error{0}; - // Site compatibility policy: only 0x10 is closed; faults always block running. + uint8_t motor_state{0}; + uint16_t error{0}; + ProtocolVersion protocol_version{V2_36}; + bool isClosed() const { + return motor_state == (protocol_version == V2_38 ? 0x20 : 0x10) && error == 0; + } + bool isFault() const { + return error != 0 || (protocol_version == V2_38 && motor_state == 0x10); + } + // Explicitly selected protocol defines the enabled state; faults block motion. // Preserve raw state/error bytes for diagnostics. bool isRunning() const { - return motor_state != 0x10 && error == 0; + if (protocol_version == V2_38) return motor_state == 0x30 && error == 0; + if (protocol_version == V2_36) return motor_state == 0x00 && error == 0; + return false; } }; - LingkongCanProtocol(Send send, std::shared_ptr> manager); + LingkongCanProtocol(Send send, std::shared_ptr> manager, ProtocolVersion version = V2_36); bool initNode(uint8_t node_id) override; bool configureNode(uint8_t node_id, const config::MotorConfigItem& config); bool probe(uint8_t node_id); @@ -46,7 +57,7 @@ public: // 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. + // Explicit API writes permanent zero via 0x19; initialization never writes ROM. bool calibrateZeroQ(uint8_t node_id); bool reachedTargetQ(uint8_t node_id) override; double getQ(uint8_t node_id) override; @@ -84,6 +95,7 @@ private: 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); + ProtocolVersion version_; Send send_; std::shared_ptr> manager_; std::map nodes_; 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 index d38b9238..b25732e3 100644 --- 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 @@ -17,11 +17,18 @@ public: 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) {} + // Configured before receiver startup. V2.38 byte 3 is encoder type, + // whereas the old protocol reserves it as zero. + void setExtendedZeroReply(bool enabled) { + std::lock_guard lock(mutex_); + extended_zero_reply_ = enabled; + } 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}; + bool extended_zero_reply_{false}; mutable std::mutex mutex_; mutable std::condition_variable changed_; mutable bool waiting_{false}, received_{false}; 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 index 5de9b6e1..3e5551a6 100644 --- 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 @@ -22,8 +22,8 @@ std::string hexFrame(const LingkongCanProtocol::Payload& bytes) { } LingkongCanProtocol::LingkongCanProtocol( - Send send, std::shared_ptr> manager) - : send_(std::move(send)), manager_(std::move(manager)) + Send send, std::shared_ptr> manager, ProtocolVersion version) + : version_(version), send_(std::move(send)), manager_(std::move(manager)) { comm_proto = CommProto::CUSTOM; } @@ -31,13 +31,14 @@ LingkongCanProtocol::LingkongCanProtocol( bool LingkongCanProtocol::initNode(uint8_t id) { std::lock_guard lock(mutex_); - if (!send_ || !manager_ || id < 1 || id > 32 || nodes_.count(id) || + if ((version_ != V2_36 && version_ != V2_38) || !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; + response->setExtendedZeroReply(version_ == V2_38); nodes_[id].response = response; return true; } @@ -54,6 +55,7 @@ bool LingkongCanProtocol::configureNode(uint8_t id, const config::MotorConfigIte 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(kRadToDeg * cfg.gear_ratio()) || !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(), @@ -109,7 +111,7 @@ bool LingkongCanProtocol::exchange(uint8_t id, const Payload& request, Payload& << ", command=" << int(request[0]) << ", tx=" << hexFrame(request) << ", timeout_ms=" << (timeout ? timeout : 100); else if (request[0] == 0x88 || request[0] == 0x80 || request[0] == 0x81 || - request[0] == 0xB1 || (request[0] >= 0xA1 && request[0] <= 0xAD)) + request[0] == 0xB1 || request[0] == 0xC1 || (request[0] >= 0xA1 && request[0] <= 0xAD)) CMVR_LOG(INFO) << "[LingkongCanProtocol] node=" << int(id) << ", tx=" << hexFrame(request) << ", rx=" << hexFrame(response) << "; reply is not proof of target completion"; @@ -129,7 +131,7 @@ bool LingkongCanProtocol::probe(uint8_t id) Status status; double q, qd; // Read-only initialization: no NMT, PDO setup, enabling or ROM writes. - return readStatus(id, status) && status.error == 0 && readFeedback(id, q, qd); + return readStatus(id, status) && !status.isFault() && readFeedback(id, q, qd); } bool LingkongCanProtocol::setMode(uint8_t id, msgs::RunMode mode) @@ -182,15 +184,25 @@ bool LingkongCanProtocol::setLimitQ(uint8_t id, double upper, double lower) 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; + auto* n = node(id); + if (!n) return false; + const bool modern = version_ == V2_38; + const bool write = command == 0xB1; + const bool valid = modern ? (index == 30 || index == 32 || index == 34 || index == 36 || index == 38) : parameterIndex(index); + // PID indices 10/11/12 on V2.38 carry three values, not a scalar. + if (!valid) return false; + const unsigned width = (modern ? index == 30 : index == 10) ? 2 : 4; + if (write && width == 2 && (value < -32768 || value > 32767)) return false; + if (modern && write) { + const int32_t limit = index == 30 ? 2000 : index == 32 ? 3000000 : index == 36 ? 30000 : index == 38 ? 600000 : std::numeric_limits::max(); + if (value < 0 || value > limit) return false; + } Payload request{}, response{}; - request[0] = command; + request[0] = modern ? (write ? 0xC1 : 0xC0) : 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 (write) putLe(request, 4, static_cast(value), width); if (!exchange(id, request, response)) return false; - value = static_cast(signedLe(response.data() + 4, index == 10 ? 2 : 4)); + value = static_cast(signedLe(response.data() + 4, width)); return true; } @@ -218,10 +230,15 @@ bool LingkongCanProtocol::setLimitQd(uint8_t id, double value) std::lock_guard lock(mutex_); auto* n = node(id); int32_t raw; + if (n && version_ == V2_38) { + if (!std::isfinite(value) || value <= 0 || !toInt32(value * scale(id) * 100.0, raw) || raw <= 0 || !writeControlParameter(id, 32, raw)) return false; + n->config.set_limit_qd(value); + return true; + } 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; + raw <= 0 || !writeControlParameter(id, version_ == V2_38 ? 32 : 14, raw)) return false; n->config.set_limit_qd(value); return true; } @@ -231,6 +248,8 @@ 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. + // V2.38 calls index 38 a speed ramp but does not specify physical units. + // Require an explicitly confirmed conversion; never send old index 12 (PID). 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) || @@ -238,7 +257,7 @@ bool LingkongCanProtocol::acceleration(uint8_t id, double value) CMVR_LOG(ERROR) << "[LingkongCanProtocol] acceleration parameter units are not configured"; return false; } - return writeControlParameter(id, 12, raw); + return writeControlParameter(id, version_ == V2_38 ? 38 : 12, raw); } void LingkongCanProtocol::setLimitQdd(uint8_t id, double upper, double lower) @@ -302,7 +321,7 @@ bool LingkongCanProtocol::torqueOn(uint8_t id) 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. + if (auto* n = node(id)) n->target_valid = false; // Invalidate any previous target after closing. if (!simple(id, 0x80)) return false; Status status; if (!readStatus(id, status)) { @@ -310,11 +329,11 @@ bool LingkongCanProtocol::torqueOff(uint8_t id) << "; 80 acknowledged but 9A status read failed"; return false; } - if (status.motor_state != 0x10 || status.error != 0) { + if (!status.isClosed()) { CMVR_LOG(ERROR) << "[LingkongCanProtocol] close unconfirmed: node=" << int(id) << ", motor_state=" << int(status.motor_state) << ", error=" << int(status.error) - << "; 80 acknowledged; expected state=16, error=0"; + << "; 80 acknowledged; expected protocol-specific OFF state, error=0"; return false; } return true; @@ -341,8 +360,12 @@ bool LingkongCanProtocol::calibrateZeroQ(uint8_t id) request[0] = 0x19; // Save current position as the permanent power-on zero. if (!exchange(id, request, response)) return false; CMVR_LOG(INFO) << "[LingkongCanProtocol] permanent zero acknowledged: node=" - << int(id) << ", encoder_offset=" << signedLe(response.data() + 4, 4) - << "; power-cycle motor to apply; no automatic reboot or motion"; + << int(id) << ", encoder_type=" << (version_ == V2_38 ? int(response[3]) : 0) + << ", encoder_offset=" << (version_ == V2_38 ? static_cast(signedLe(response.data() + 4, 4)) : static_cast(signedLe(response.data() + 6, 2))) + << (version_ == V2_38 + ? "; saved to ROM; V2.38 manual does not specify activation timing" + : "; power-cycle motor to apply") + << "; no immediate position readback, automatic reboot or motion"; return true; } bool LingkongCanProtocol::clearError(uint8_t id) @@ -350,7 +373,10 @@ 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; + if (!exchange(id, request, response)) return false; + auto* n = node(id); + const bool modern = n && version_ == V2_38; + return response[7] == 0 && (!modern || ((response[6] & 0x0f) == 0 && (response[6] & 0xf0) != 0x10)); } double LingkongCanProtocol::getQ(uint8_t id) @@ -384,10 +410,12 @@ bool LingkongCanProtocol::readStatus(uint8_t id, Status& status) request[0] = 0x9A; if (!exchange(id, request, response)) 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]; + status.protocol_version = version_; + const bool modern = status.protocol_version == V2_38; + status.voltage = signedLe(response.data() + 2, 2) * (modern ? 0.001 : 0.01); + status.bus_current = signedLe(response.data() + 4, 2) * (modern ? 0.001 : 0.01); + status.motor_state = modern ? (response[6] & 0xf0) : response[6]; + status.error = response[7] | (modern ? ((response[6] & 0x0f) << 8) : 0); return true; } bool LingkongCanProtocol::readCurrent(uint8_t id, double& amps) @@ -414,8 +442,8 @@ void LingkongCanProtocol::requireRunning(uint8_t id) { Status status; if (!readStatus(id, status)) throw std::runtime_error("Lingkong: cannot verify drive state (9A read failed); no motion command sent"); - if (status.error) throw std::runtime_error("Lingkong: drive fault, errorState=" + std::to_string(status.error) + "; inspect 9A before motion"); - if (!status.isRunning()) throw std::runtime_error("Lingkong: drive is closed (9A motorState=0x10); call torqueOn explicitly before motion"); + if (status.isFault()) throw std::runtime_error("Lingkong: drive fault, errorState=" + std::to_string(status.error) + "; inspect 9A before motion"); + if (!status.isRunning()) throw std::runtime_error("Lingkong: drive is not enabled (protocol-specific 9A state); call torqueOn explicitly before motion"); } bool LingkongCanProtocol::position(uint8_t id, double q, double qd) @@ -452,6 +480,13 @@ bool LingkongCanProtocol::velocity(uint8_t id, double qd) !toInt32(qd * scale(id) * 100.0, raw)) return false; Payload request{}, response{}; request[0] = 0xA2; + if (version_ == V2_38) { + // V2.38 A2 adds an Iq limit. Preserve the configured drive limit rather + // than accidentally requesting zero torque with the legacy NULL bytes. + int32_t torque_limit = 0; + if (!readControlParameter(id, 30, torque_limit) || torque_limit < 0 || torque_limit > 2000) return false; + putLe(request, 2, static_cast(torque_limit), 2); + } putLe(request, 4, static_cast(raw), 4); n->target_valid = false; requireRunning(id); @@ -466,7 +501,7 @@ bool LingkongCanProtocol::commandProfilePosition(uint8_t id, double q, double qd // writes separate: B1 support must not be a prerequisite for native motion. auto* n = node(id); int32_t raw; - if (!n || !std::isfinite(qd) || qd < 0 || !toInt32(q * scale(id) * 100, raw) || + if (!n || !std::isfinite(qdd) || qdd < 0 || !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; if (qdd != 0) CMVR_LOG(WARNING) << "[LingkongCanProtocol] A3/A4 has no acceleration field; qdd is not sent, retaining drive acceleration"; if (!position(id, q, qd)) return false; @@ -477,7 +512,7 @@ bool LingkongCanProtocol::commandProfileVelocity(uint8_t id, double qd, double q std::lock_guard lock(mutex_); auto* n = node(id); int32_t raw; - if (!n || !toInt32(qd * scale(id) * 100, raw) || + if (!n || !std::isfinite(qdd) || qdd < 0 || !toInt32(qd * scale(id) * 100, raw) || (n->config.limit_qd() > 0 && std::abs(qd) > n->config.limit_qd())) return false; // A2 carries only target speed. Do not implicitly issue B1/index 12. if (qdd != 0) CMVR_LOG(WARNING) << "[LingkongCanProtocol] A2 has no acceleration field; qdd is not sent, retaining drive acceleration"; 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 index 2ae59102..913f16b1 100644 --- a/cmvr-es/devices/motor/drivers/lingkong_can/src/lingkong_motor.cpp +++ b/cmvr-es/devices/motor/drivers/lingkong_can/src/lingkong_motor.cpp @@ -75,7 +75,7 @@ bool LingkongMotor::readDiagnosticState(std::uint16_t& status, std::uint16_t& er status = native.motor_state; // Preserve native state, including HV V3 0x30. error = native.error; enabled = native.isRunning(); - fault = native.error != 0; + fault = native.isFault(); return true; } 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 index bf633b2e..acb0d860 100644 --- 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 @@ -9,12 +9,13 @@ void LingkongMotorResponse::Parse(const uint8_t* bytes, int32_t length, msgs::Ro 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] == 0xB0 || bytes[0] == 0xB1 || bytes[0] == 0xC0 || bytes[0] == 0xC1) && bytes[1] != request_[1]) return; if ((bytes[0] == 0x80 || bytes[0] == 0x81 || bytes[0] == 0x88 || bytes[0] == 0x95) && !std::equal(bytes, bytes + 8, request_.begin())) return; // 0x19 returns a uint32 encoder offset in bytes 4..7, not a request echo. - if (bytes[0] == 0x19 && (bytes[1] != 0 || bytes[2] != 0 || bytes[3] != 0)) return; + if (bytes[0] == 0x19 && (bytes[1] != 0 || bytes[2] != 0 || + (!extended_zero_reply_ && (bytes[3] != 0 || bytes[4] != 0 || bytes[5] != 0)))) return; if (bytes[0] == 0x8C && request_[1] != 0x10 && bytes[1] != request_[1]) return; std::copy(bytes, bytes + 8, response_.begin()); received_ = true; @@ -33,10 +34,17 @@ bool LingkongMotorResponse::exchange(const Payload& request, Payload& response, waiting_ = true; } // Never hold the receive lock across send: fake transports can reply inline. - if (!send()) { + try { + if (!send()) { + std::lock_guard lock(mutex_); + waiting_ = false; + return false; + } + } catch (...) { std::lock_guard lock(mutex_); waiting_ = false; - return false; + received_ = false; + throw; } std::unique_lock lock(mutex_); const bool ok = changed_.wait_for(lock, timeout, [&] { return received_; }); 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 index 81973d26..2734b1ee 100644 --- 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 @@ -30,7 +30,11 @@ protected: std::function mutate; config::MotorConfigItem config; + LingkongCanProtocol::ProtocolVersion version = LingkongCanProtocol::V2_36; + LingkongCanProtocol::Send fake_send; void SetUp() override { + manager = std::make_shared>(); + sent.clear(); config.set_id(1); config.set_joint_name("MG6010E_AXIS_1"); config.set_gear_ratio(6); @@ -40,14 +44,14 @@ protected: 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) { + fake_send = [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] == 0x88) state = 0; - if (reply[0] == 0x80) state = 0x10; + if (reply[0] == 0x88) state = version == LingkongCanProtocol::V2_38 ? 0x30 : 0; + if (reply[0] == 0x80) state = version == LingkongCanProtocol::V2_38 ? 0x20 : 0x10; if (reply[0] == 0x92) put(reply, 1, angle, 7); if (reply[0] == 0x9C || (reply[0] >= 0xA1 && reply[0] <= 0xA8)) { reply[1] = uint8_t(-12); @@ -66,7 +70,8 @@ protected: if (mutate) mutate(reply); manager->Parse(frame.id, reply.data(), reply.size()); return true; - }, manager); + }; + protocol = std::make_shared(fake_send, manager, version); ASSERT_TRUE(protocol->initNode(1)); ASSERT_TRUE(protocol->configureNode(1, config)); } @@ -448,6 +453,7 @@ TEST_F(LingkongTest, FailedHoldRollsBackToClosedAndInvalidatesTarget) { } // namespace TEST_F(LingkongTest, HvState30WithoutFaultInitializesAndReportsRawEnabledState) { + version = LingkongCanProtocol::V2_38; SetUp(); state = 0x30; auto second = config; second.set_id(2); LingkongMotor motor(second); @@ -465,6 +471,7 @@ TEST_F(LingkongTest, HvState30WithoutFaultInitializesAndReportsRawEnabledState) } TEST_F(LingkongTest, HvState30WithAnyFaultNeverDispatchesMotion) { + version = LingkongCanProtocol::V2_38; SetUp(); state = 0x30; for (unsigned bit = 0; bit < 8; ++bit) { error = uint8_t(1u << bit); @@ -474,7 +481,7 @@ TEST_F(LingkongTest, HvState30WithAnyFaultNeverDispatchesMotion) { for (const auto& frame : sent) EXPECT_EQ(frame.data[0], 0x9A); } -TEST_F(LingkongTest, AllNativeStatesFollowNon10NoFaultPolicy) { +TEST_F(LingkongTest, AllV236StatesRequireExactOnWithoutFault) { auto second = config; second.set_id(2); LingkongMotor motor(second); ASSERT_TRUE(motor.setProtocol(protocol)); @@ -484,8 +491,8 @@ TEST_F(LingkongTest, AllNativeStatesFollowNon10NoFaultPolicy) { uint16_t raw, ec; bool enabled, fault; ASSERT_TRUE(motor.readDiagnosticState(raw, ec, enabled, fault)); EXPECT_EQ(raw, value); EXPECT_EQ(ec, 0); - EXPECT_EQ(enabled, value != 0x10); EXPECT_FALSE(fault); - if (value == 0x10) { + EXPECT_EQ(enabled, value == 0x00); EXPECT_FALSE(fault); + if (value != 0x00) { EXPECT_THROW(protocol->commandProfilePosition(1, 0.1, 0.1, 1), std::runtime_error); } else { EXPECT_TRUE(protocol->commandProfilePosition(1, 0.1, 0.1, 1)) << value; @@ -506,7 +513,7 @@ TEST_F(LingkongTest, AllNativeStatesFollowNon10NoFaultPolicy) { TEST_F(LingkongTest, PermanentZeroWritesRomOnceAndAcceptsReturnedOffset) { ASSERT_TRUE(protocol->commandProfilePosition(1, 0.1, 0.1, 0)); sent.clear(); - mutate = [](Payload& p) { if (p[0] == 0x19) put(p, 4, 0xFEDCBA98u, 4); }; + mutate = [](Payload& p) { if (p[0] == 0x19) put(p, 6, 0xBA98u, 2); }; ASSERT_TRUE(protocol->calibrateZeroQ(1)); ASSERT_EQ(sent.size(), 1); EXPECT_EQ(sent[0].data[0], 0x19); @@ -547,3 +554,308 @@ TEST_F(LingkongTest, CloseFailuresReturnFalseWithoutThrowingOrSendingMoreCommand EXPECT_FALSE(protocol->torqueOff(1)); ASSERT_EQ(sent.size(), 1); EXPECT_EQ(sent[0].data[0], 0x80); } + +TEST_F(LingkongTest, V238PackedStatusAndMillivoltUnits) { + version = LingkongCanProtocol::V2_38; + SetUp(); + ASSERT_TRUE(protocol->configureNode(1, config)); + state = 0x32; error = 0; + LingkongCanProtocol::Status s; + ASSERT_TRUE(protocol->readStatus(1, s)); + EXPECT_EQ(s.motor_state, 0x30); + EXPECT_EQ(s.error, 0x200); + EXPECT_FALSE(s.isRunning()); + EXPECT_TRUE(s.isFault()); + EXPECT_DOUBLE_EQ(s.voltage, 4.8); + EXPECT_DOUBLE_EQ(s.bus_current, -0.125); + for (auto raw : {0x00, 0x10, 0x20, 0x40, 0x50}) { + state = raw; + ASSERT_TRUE(protocol->readStatus(1, s)); + EXPECT_FALSE(s.isRunning()); + } + state = 0x30; + ASSERT_TRUE(protocol->readStatus(1, s)); + EXPECT_TRUE(s.isRunning()); + state = 0x20; + ASSERT_TRUE(protocol->readStatus(1, s)); + EXPECT_TRUE(s.isClosed()); +} +TEST_F(LingkongTest, V238UsesCParametersAndRejectsScalarPid) { + version = LingkongCanProtocol::V2_38; + SetUp(); + ASSERT_TRUE(protocol->configureNode(1, config)); + int32_t value = 0; + EXPECT_TRUE(protocol->readControlParameter(1, 32, value)); + EXPECT_EQ(sent.back().data[0], 0xC0); + EXPECT_TRUE(protocol->writeControlParameter(1, 38, 100)); + EXPECT_EQ(sent.back().data[0], 0xC1); + EXPECT_EQ(sent.back().data[1], 38); + EXPECT_FALSE(protocol->writeControlParameter(1, 12, 100)); + EXPECT_FALSE(protocol->writeControlParameter(1, 30, 2001)); + EXPECT_FALSE(protocol->writeControlParameter(1, 32, 3000001)); + EXPECT_TRUE(protocol->setLimitQd(1, 1)); + EXPECT_EQ(sent.back().data[1], 32); + config.mutable_lingkong()->set_acceleration_deg_s2_per_lsb(1); + ASSERT_TRUE(protocol->configureNode(1, config)); + EXPECT_NO_THROW(protocol->setLimitQdd(1, 1, -1)); + EXPECT_EQ(sent.back().data[0], 0xC1); + EXPECT_EQ(sent.back().data[1], 38); +} +TEST_F(LingkongTest, V238OffAndClearVerifyHighErrorBits) { + version = LingkongCanProtocol::V2_38; + SetUp(); + ASSERT_TRUE(protocol->configureNode(1, config)); + mutate = [](Payload& r) { if (r[0] == 0x9A) r[6] = 0x20; }; + EXPECT_TRUE(protocol->torqueOff(1)); + mutate = [](Payload& r) { if (r[0] == 0x9A || r[0] == 0x9B) r[6] = 0x22; }; + EXPECT_FALSE(protocol->torqueOff(1)); + EXPECT_FALSE(protocol->clearError(1)); +} +TEST_F(LingkongTest, ExplicitV236RejectsUndocumentedRunningStates) { + version = LingkongCanProtocol::V2_36; + SetUp(); + ASSERT_TRUE(protocol->configureNode(1, config)); + LingkongCanProtocol::Status s; + state = 0x30; + ASSERT_TRUE(protocol->readStatus(1, s)); + EXPECT_FALSE(s.isRunning()); + state = 0; + ASSERT_TRUE(protocol->readStatus(1, s)); + EXPECT_TRUE(s.isRunning()); +} +TEST_F(LingkongTest, MixedVersionsUseSeparateProtocolInstances) { + auto second = config; + second.set_id(2); + auto modern_protocol = std::make_shared(fake_send, manager, LingkongCanProtocol::V2_38); + ASSERT_TRUE(modern_protocol->initNode(2)); + ASSERT_TRUE(modern_protocol->configureNode(2, second)); + state = 0x20; + LingkongCanProtocol::Status old, modern; + ASSERT_TRUE(protocol->readStatus(1, old)); + ASSERT_TRUE(modern_protocol->readStatus(2, modern)); + EXPECT_FALSE(old.isRunning()); // 0x20 is not an enabled V2.36 state. + EXPECT_TRUE(modern.isClosed()); + EXPECT_DOUBLE_EQ(old.voltage, 48); + EXPECT_DOUBLE_EQ(modern.voltage, 4.8); +} + +TEST_F(LingkongTest, V238EnableAndVelocityPreserveDriveTorqueLimit) { + version = LingkongCanProtocol::V2_38; + SetUp(); + mutate = [](Payload& r) { + if (r[0] == 0x9A) r[6] = 0x30; + if (r[0] == 0xC0 && r[1] == 30) put(r, 4, 1000, 2); + }; + ASSERT_TRUE(protocol->torqueOn(1)); + sent.clear(); + ASSERT_TRUE(protocol->commandCyclicVelocity(1, 0.1)); + ASSERT_EQ(sent.size(), 3); + EXPECT_EQ(sent[0].data[0], 0xC0); + EXPECT_EQ(sent[0].data[1], 30); + EXPECT_EQ(sent[2].data[0], 0xA2); + EXPECT_EQ(sent[2].data[2], 0xE8); + EXPECT_EQ(sent[2].data[3], 0x03); +} +TEST_F(LingkongTest, V238ParameterReplyMustMatchIndex) { + version = LingkongCanProtocol::V2_38; + SetUp(); + mutate = [](Payload& r) { if (r[0] == 0xC0 || r[0] == 0xC1) ++r[1]; }; + int32_t raw = 0; + EXPECT_FALSE(protocol->readControlParameter(1, 32, raw)); + EXPECT_FALSE(protocol->writeControlParameter(1, 38, 100)); +} +TEST_F(LingkongTest, V238PermanentZeroSendsOnly19) { + version = LingkongCanProtocol::V2_38; + SetUp(); + mutate = [](Payload& r) { if (r[0] == 0x19) put(r, 4, 0x89abcdef, 4); }; + sent.clear(); + EXPECT_TRUE(protocol->calibrateZeroQ(1)); + ASSERT_EQ(sent.size(), 1); + EXPECT_EQ(sent[0].data[0], 0x19); +} + +TEST_F(LingkongTest, BothManualsCommonControlAndFeedbackFrames) { + for (auto selected : {LingkongCanProtocol::V2_36, LingkongCanProtocol::V2_38}) { + version = selected; + SetUp(); + state = version == LingkongCanProtocol::V2_38 ? 0x20 : 0x10; + ASSERT_TRUE(protocol->torqueOn(1)); + sent.clear(); + ASSERT_TRUE(protocol->commandProfilePosition(1, kPi/3, kPi/180, 0)); + const auto& f = sent.back(); + EXPECT_EQ(f.data[0], 0xA4); + EXPECT_EQ(f.data[2], 6); + EXPECT_EQ(f.data[3], 0); + EXPECT_EQ(f.data[4], 0xA0); + EXPECT_EQ(f.data[5], 0x8C); + EXPECT_EQ(f.data[6], 0); + EXPECT_EQ(f.data[7], 0); + sent.clear(); + ASSERT_TRUE(protocol->quickStop(1)); + ASSERT_EQ(sent.size(), 1); + EXPECT_EQ(sent[0].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->torqueOff(1)); + LingkongCanProtocol::Status status; + ASSERT_TRUE(protocol->readStatus(1, status)); + EXPECT_TRUE(status.isClosed()); + EXPECT_FALSE(status.isRunning()); + EXPECT_NEAR(protocol->getQ(1), -kPi/3, 1e-12); + EXPECT_NEAR(protocol->getQd(1), -kPi/18, 1e-12); + } +} +TEST_F(LingkongTest, V238ErrorStateBlocksInitializationEvenWithoutErrorBits) { + version = LingkongCanProtocol::V2_38; + SetUp(); + state = 0x10; + EXPECT_FALSE(protocol->probe(1)); +} +TEST_F(LingkongTest, V238EveryHighFaultBitBlocksMotionAndClearSuccess) { + version = LingkongCanProtocol::V2_38; + SetUp(); + for (int bit=0; bit<4; ++bit) { + state = 0x30 | (1 << bit); + EXPECT_THROW(protocol->commandProfilePosition(1, 0.1, 0.1, 0), std::runtime_error); + EXPECT_FALSE(protocol->clearError(1)); + } +} +TEST_F(LingkongTest, V238RampRequiresExplicitUnitsAndNeverWritesPid12) { + version = LingkongCanProtocol::V2_38; + SetUp(); + sent.clear(); + EXPECT_THROW(protocol->setLimitQdd(1, 1, -1), std::runtime_error); + EXPECT_TRUE(sent.empty()); +} +TEST_F(LingkongTest, V238IqConversionRemainsExplicitAndSigned) { + version = LingkongCanProtocol::V2_38; + SetUp(); + config.mutable_lingkong()->set_current_amp_per_lsb(0); + ASSERT_TRUE(protocol->configureNode(1, config)); + double amps; + EXPECT_FALSE(protocol->readCurrent(1, amps)); + config.mutable_lingkong()->set_current_amp_per_lsb(0.002); + ASSERT_TRUE(protocol->configureNode(1, config)); + EXPECT_TRUE(protocol->readCurrent(1, amps)); + EXPECT_DOUBLE_EQ(amps, -409 * 0.002); +} + +TEST_F(LingkongTest, V238AcceptsCapturedEncoderTypeOneZeroReplyWithoutReadback) { + version = LingkongCanProtocol::V2_38; + SetUp(); + mutate = [](Payload& r) { + if (r[0] == 0x19) r = Payload{0x19,0,0,1,0xCC,0x9A,0,0}; + }; + sent.clear(); + EXPECT_TRUE(protocol->calibrateZeroQ(1)); + ASSERT_EQ(sent.size(),1); + EXPECT_EQ(sent[0].data[0],0x19); +} +TEST_F(LingkongTest, V236StillRejectsNonzeroReservedByteInZeroReply) { + version = LingkongCanProtocol::V2_36; + SetUp(); + mutate = [](Payload& r) { if (r[0] == 0x19) r[3] = 1; }; + EXPECT_FALSE(protocol->calibrateZeroQ(1)); +} +TEST_F(LingkongTest, V238ZeroReplyStillValidatesReservedBytes) { + version = LingkongCanProtocol::V2_38; + SetUp(); + for (int byte : {1,2}) { + mutate = [byte](Payload& r) { if (r[0] == 0x19) r[byte] = 1; }; + EXPECT_FALSE(protocol->calibrateZeroQ(1)); + } +} + +TEST_F(LingkongTest, ProductionDefaultIsStrictV236NotHistoricalSitePolicy) { + protocol = std::make_shared(fake_send, manager); + // A fresh manager is required because registration owns response parsers. + manager = std::make_shared>(); + protocol = std::make_shared(fake_send, manager); + ASSERT_TRUE(protocol->initNode(1)); + ASSERT_TRUE(protocol->configureNode(1, config)); + state = 0x30; + EXPECT_THROW(protocol->commandProfilePosition(1,0.1,0.1,0),std::runtime_error); + state = 0; + EXPECT_TRUE(protocol->commandProfilePosition(1,0.1,0.1,0)); +} +TEST_F(LingkongTest, BothVersionsRejectInvalidProfileAccelerationBeforeCan) { + for(auto selected:{LingkongCanProtocol::V2_36,LingkongCanProtocol::V2_38}) { + version=selected;SetUp();sent.clear(); + for(double invalid:{-1.0,std::numeric_limits::quiet_NaN(),std::numeric_limits::infinity()}) { + EXPECT_FALSE(protocol->commandProfilePosition(1,0.1,0.1,invalid)); + EXPECT_FALSE(protocol->commandProfileVelocity(1,0.1,invalid)); + } + EXPECT_TRUE(sent.empty()); + } +} +TEST_F(LingkongTest, V236RejectsAllFiveReservedBytesInZeroAcknowledgement) { + version=LingkongCanProtocol::V2_36;SetUp(); + for(int byte=1;byte<=5;++byte) { + mutate=[byte](Payload& r){if(r[0]==0x19)r[byte]=1;}; + EXPECT_FALSE(protocol->calibrateZeroQ(1)); + } + mutate=[](Payload& r){if(r[0]==0x19)put(r,6,65535,2);}; + EXPECT_TRUE(protocol->calibrateZeroQ(1)); +} +TEST_F(LingkongTest, V238AcceptsEncoderTypeAsDataNotReservedByte) { + version=LingkongCanProtocol::V2_38;SetUp(); + for(auto type:{0,1,2,255}) { + mutate=[type](Payload& r){if(r[0]==0x19){r[3]=type;put(r,4,0xffffffffu,4);}}; + EXPECT_TRUE(protocol->calibrateZeroQ(1)); + } +} +TEST_F(LingkongTest, BothVersionsRecoverAfterTransportThrowsWithoutAutoRetry) { + for(auto selected:{LingkongCanProtocol::V2_36,LingkongCanProtocol::V2_38}) { + version=selected;SetUp(); + mutate=[](Payload&){throw std::runtime_error("fake transport failure");}; + sent.clear();EXPECT_THROW(protocol->getQ(1),std::runtime_error); + EXPECT_EQ(sent.size(),1); + mutate={};EXPECT_NEAR(protocol->getQ(1),-kPi/3,1e-12); + EXPECT_EQ(sent.size(),2); + } +} +TEST_F(LingkongTest, BothVersionsSigned56BitAngleExtremes) { + for(auto selected:{LingkongCanProtocol::V2_36,LingkongCanProtocol::V2_38}) { + version=selected;SetUp(); + for(int64_t value:{-(int64_t(1)<<55),(int64_t(1)<<55)-1,int64_t(-1),int64_t(0)}) { + angle=value; + EXPECT_DOUBLE_EQ(protocol->getQ(1),double(value)/(100.0*(180.0/kPi*6))); + } + } +} +TEST_F(LingkongTest, V238EveryErrorBitIsPreservedAndRejectsClearSuccess) { + version=LingkongCanProtocol::V2_38;SetUp(); + for(int bit=0;bit<12;++bit) { + int mask=1<>8)&15);error=mask&255; + LingkongCanProtocol::Status s;ASSERT_TRUE(protocol->readStatus(1,s)); + EXPECT_EQ(s.error,mask);EXPECT_FALSE(s.isRunning());EXPECT_TRUE(s.isFault()); + EXPECT_FALSE(protocol->clearError(1)); + } +} +TEST_F(LingkongTest, V238AllStateNibblesOnlyOnAndOffAreRecognized) { + version=LingkongCanProtocol::V2_38;SetUp(); + for(int code=0;code<16;++code) { + state=code<<4;error=0;LingkongCanProtocol::Status s; + ASSERT_TRUE(protocol->readStatus(1,s)); + EXPECT_EQ(s.isRunning(),code==3);EXPECT_EQ(s.isClosed(),code==2); + } +} +TEST_F(LingkongTest, BothVersionsParameterCommandsCannotCrossVersions) { + for(auto selected:{LingkongCanProtocol::V2_36,LingkongCanProtocol::V2_38}) { + version=selected;SetUp();sent.clear(); + int32_t value=0;bool modern=version==LingkongCanProtocol::V2_38; + EXPECT_TRUE(protocol->readControlParameter(1,modern?30:10,value)); + EXPECT_EQ(sent.back().data[0],modern?0xC0:0xB0); + EXPECT_TRUE(protocol->writeControlParameter(1,modern?30:10,1000)); + EXPECT_EQ(sent.back().data[0],modern?0xC1:0xB1); + EXPECT_FALSE(protocol->writeControlParameter(1,modern?14:32,1000)); + } +} +TEST_F(LingkongTest, InvalidProtocolSelectionAndOverflowGearAreRejected) { + auto mgr=std::make_shared>(); + auto p=std::make_shared(fake_send,mgr,static_cast(999)); + EXPECT_FALSE(p->initNode(1)); + config.set_gear_ratio(std::numeric_limits::max()); + EXPECT_FALSE(protocol->configureNode(1,config)); +} diff --git a/cmvr-es/devices/motor/manager/CMakeLists.txt b/cmvr-es/devices/motor/manager/CMakeLists.txt index 21839a76..f344a07a 100644 --- a/cmvr-es/devices/motor/manager/CMakeLists.txt +++ b/cmvr-es/devices/motor/manager/CMakeLists.txt @@ -24,4 +24,4 @@ install(TARGETS motor_manager LIBRARY DESTINATION lib) # Fake motors only: shutdown error paths never access physical hardware. add_executable(motor_manager_shutdown_test src/motor_manager_shutdown_test.cpp) target_link_libraries(motor_manager_shutdown_test PRIVATE - cmvr_es::device::motor_manager gtest gtest_main pthread) + cmvr_es::device::motor_manager cmvr_es::device::lingkong_can_motor_driver cmvr_es::device::canbus gtest gtest_main pthread) diff --git a/cmvr-es/devices/motor/manager/src/motor_manager.cpp b/cmvr-es/devices/motor/manager/src/motor_manager.cpp index 706998e9..5813123f 100644 --- a/cmvr-es/devices/motor/manager/src/motor_manager.cpp +++ b/cmvr-es/devices/motor/manager/src/motor_manager.cpp @@ -380,10 +380,39 @@ bool MotorManager::commandCyclicVelocitiesAtomic( 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; + auto stop_all = [&]() { + bool ok = true; + for (const auto& motor : motors) { + try { + if (!motor->quickStop()) ok = false; + } catch (const std::exception& error) { + CMVR_LOG(ERROR) << "[MotorManager] Lingkong stop failed: node=" + << int(motor->id()) << ", " << error.what(); + ok = false; + } catch (...) { + CMVR_LOG(ERROR) << "[MotorManager] Lingkong stop failed: node=" << int(motor->id()); + ok = false; + } + } + return ok; + }; + if (std::all_of(velocities.begin(), velocities.end(), [](double v) { return v == 0.0; })) + return stop_all(); // Both manuals specify 0x81; no mode/enable prerequisite. + try { + for (std::size_t i = 0; i < motors.size(); ++i) { + if (!motors[i]->commandCyclicVelocity(velocities[i])) { + (void)stop_all(); + return false; + } + } + return true; + } catch (const std::exception& error) { + CMVR_LOG(ERROR) << "[MotorManager] Lingkong velocity group failed: " << error.what(); + } catch (...) { + CMVR_LOG(ERROR) << "[MotorManager] Lingkong velocity group failed with unknown exception"; } - return true; + (void)stop_all(); + return false; } if (std::dynamic_pointer_cast(motors.front())) { for (const auto& motor : motors) { @@ -691,13 +720,19 @@ std::vector> MotorManager::createCanMotors_( return {}; } if (group_cfg.vendor() == config::MOTOR_VENDOR_LINGKONG && - group_cfg.protocol() == config::MOTOR_PROTOCOL_LINGKONG_CAN) { + (group_cfg.protocol() == config::MOTOR_PROTOCOL_LINGKONG_CAN || + group_cfg.protocol() == config::MOTOR_PROTOCOL_LINGKONG_CAN_V2_38)) { 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()); + }, can_bus_runtime->messageManager(), + group_cfg.protocol() == config::MOTOR_PROTOCOL_LINGKONG_CAN_V2_38 + ? LingkongCanProtocol::V2_38 : LingkongCanProtocol::V2_36); + CMVR_LOG(INFO) << "[MotorManager] Lingkong protocol selected: group=" << group_cfg.id() + << ", protocol=" << config::MotorProtocol_Name(group_cfg.protocol()) + << ", channel=" << group_cfg.can().channel_id(); std::vector> motors; motors.reserve(motor_cfgs.size()); for (const auto& cfg : motor_cfgs) { diff --git a/cmvr-es/devices/motor/manager/src/motor_manager_shutdown_test.cpp b/cmvr-es/devices/motor/manager/src/motor_manager_shutdown_test.cpp index 4c3eafdd..bf042f52 100644 --- a/cmvr-es/devices/motor/manager/src/motor_manager_shutdown_test.cpp +++ b/cmvr-es/devices/motor/manager/src/motor_manager_shutdown_test.cpp @@ -41,3 +41,45 @@ TEST(MotorManagerShutdown, EmptyManagerStopsSuccessfully) { EXPECT_TRUE(manager.stop()); } } + +#include "motor/drivers/lingkong_can/include/lingkong_motor.h" +#include +TEST(MotorManagerShutdown, LingkongDisabledOrMissingMotorNeverAbortsGroupStop) { + for (auto version : {LingkongCanProtocol::V2_36, LingkongCanProtocol::V2_38}) { + for (int failure : {0, 1, 2, 3}) { + auto messages=std::make_shared>(); + std::vector sent; + auto protocol=std::make_shared([&](const CanFrame& f) { + sent.push_back(f); + if (f.id==0x142 && failure==1) return false; + if (f.id==0x142 && failure==2) throw std::runtime_error("transport failure"); + if (f.id==0x142 && failure==3) return true; + LingkongCanProtocol::Payload reply{}; + std::copy(f.data,f.data+8,reply.begin()); + messages->Parse(f.id,reply.data(),8); + return true; + },messages,version); + MotorManager manager("native_stop",config::MotorConfig{},"test"); + std::vector> motors; + for (int id=1;id<=3;++id) { + config::MotorConfigItem cfg; + cfg.set_id(id);cfg.set_joint_name("native_stop_"+std::to_string(id)); + cfg.set_gear_ratio(1);cfg.set_limit_q_lb(-4);cfg.set_limit_q_ub(4); + cfg.mutable_lingkong()->set_response_timeout_ms(2); + auto motor=std::make_shared(cfg); + ASSERT_TRUE(motor->setProtocol(protocol)); + ASSERT_TRUE(protocol->configureNode(id,cfg)); + motors.push_back(motor); + } + bool ok=false; + EXPECT_NO_THROW(ok=manager.commandCyclicVelocitiesAtomic(motors,{0,0,0})); + EXPECT_EQ(ok,failure==0); + ASSERT_EQ(sent.size(),3); + for (int i=0;i<3;++i) { + EXPECT_EQ(sent[i].id,0x141+i); + EXPECT_EQ(sent[i].data[0],0x81); + for (int b=1;b<8;++b) EXPECT_EQ(sent[i].data[b],0); + } + } + } +} diff --git a/protos/cmvr/config/motor_config/motor_config.proto b/protos/cmvr/config/motor_config/motor_config.proto index 5f9952b5..b173c5e5 100644 --- a/protos/cmvr/config/motor_config/motor_config.proto +++ b/protos/cmvr/config/motor_config/motor_config.proto @@ -106,6 +106,7 @@ enum MotorProtocol { MOTOR_PROTOCOL_ETHERCAT_CIA402 = 2; MOTOR_PROTOCOL_MUJOCO = 3; MOTOR_PROTOCOL_LINGKONG_CAN = 4; + MOTOR_PROTOCOL_LINGKONG_CAN_V2_38 = 5; } message MotorGroupConfig {