From 2ecd74b0444a9ee915d4e422ab6d9c8ac336c8f3 Mon Sep 17 00:00:00 2001 From: linbo <1034003879@qq.com> Date: Fri, 30 Oct 2026 16:42:42 +0800 Subject: [PATCH 1/2] fix(arm): configure Lingkong three-axis control and use configured AUBO frames --- .../config/devices/arm/lingkong_arm.pb.txt | 30 ++++ .../devices/motor/lingkong_motors.pb.txt | 43 ++++-- cmvr-es/config/manager/device_manager.pb.txt | 6 + cmvr-es/devices/arm/aubo_arm/src/aubo_arm.cpp | 133 ++---------------- .../src/lingkong_can_protocol.cpp | 19 ++- .../tests/lingkong_motor_protocol_test.cpp | 60 ++++++++ 6 files changed, 155 insertions(+), 136 deletions(-) create mode 100644 cmvr-es/config/devices/arm/lingkong_arm.pb.txt diff --git a/cmvr-es/config/devices/arm/lingkong_arm.pb.txt b/cmvr-es/config/devices/arm/lingkong_arm.pb.txt new file mode 100644 index 00000000..3fab18da --- /dev/null +++ b/cmvr-es/config/devices/arm/lingkong_arm.pb.txt @@ -0,0 +1,30 @@ +# Three-axis joint-only group. MoveJ positions follow joint_names order (rad). +# CAN commands are sent per axis; this is not hardware-triggered synchronization. +arm { + robot_arms { + id: "lingkong_arm" + motor { + motor_system_id: "lingkong_can_motors" + motor_group_ids: "lingkong_can_motors" + dof: 3 + joint_names: "MG4005E_AXIS_1" + joint_names: "MG4005E_AXIS_2" + joint_names: "MG4005E_AXIS_3" + upd_freq: 50 + } + motion { + joint_trajectory_smoother { + sample_period_s: 0.02 + quintic_bspline { + control_point_spacing_rad: 0.1 + } + } + 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 + } + } + } +} diff --git a/cmvr-es/config/devices/motor/lingkong_motors.pb.txt b/cmvr-es/config/devices/motor/lingkong_motors.pb.txt index 83a7853f..d6636f83 100644 --- a/cmvr-es/config/devices/motor/lingkong_motors.pb.txt +++ b/cmvr-es/config/devices/motor/lingkong_motors.pb.txt @@ -1,7 +1,6 @@ -# One MG6010E-i6 V3, selected by device_manager as lingkong_can_motors. -# CAN ID 1 verified by read-only status/angle queries on this installation. -# Bring up can0 at the drive's configured bitrate (manual default 1 Mbps). +# Three MG4005E-i10 V3 motors on can0, CAN node IDs 1/2/3. # All public q/qd values refer to OUTPUT shaft radians/radians per second. +# SOFTWARE limits retained from the previous single-motor installation. motor { id: "lingkong_motors" motor_groups { @@ -13,9 +12,8 @@ motor { motors { motors { id: 1 - joint_name: "MG6010E_AXIS_1" - gear_ratio: 6 - # Example SOFTWARE position/speed limits; confirm for the installation. + joint_name: "MG4005E_AXIS_1" + gear_ratio: 10 limit_q_lb: -3.14 limit_q_ub: 3.14 limit_qd: 10 @@ -23,10 +21,35 @@ motor { 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. - # B0 parameter queries received no reply on this drive. Leave B1 - # parameter unit settings unset until firmware support is verified. - # Native A2/A3/A4 commands preserve the drive's acceleration setting. + # Rated current and B1 parameter conversions remain unspecified. + } + } + motors { + id: 2 + joint_name: "MG4005E_AXIS_2" + gear_ratio: 10 + limit_q_lb: -3.14 + limit_q_ub: 3.14 + limit_qd: 10 + lingkong { + current_amp_per_lsb: 0.01611328125 # MG: 66/4096 A/LSB + response_timeout_ms: 100 + reached_position_tolerance_rad: 0.001 + # Rated current and B1 parameter conversions remain unspecified. + } + } + motors { + id: 3 + joint_name: "MG4005E_AXIS_3" + gear_ratio: 10 + limit_q_lb: -3.14 + limit_q_ub: 3.14 + limit_qd: 10 + lingkong { + current_amp_per_lsb: 0.01611328125 # MG: 66/4096 A/LSB + response_timeout_ms: 100 + reached_position_tolerance_rad: 0.001 + # Rated current and B1 parameter conversions remain unspecified. } } } diff --git a/cmvr-es/config/manager/device_manager.pb.txt b/cmvr-es/config/manager/device_manager.pb.txt index ab9c89fe..8babf1c2 100644 --- a/cmvr-es/config/manager/device_manager.pb.txt +++ b/cmvr-es/config/manager/device_manager.pb.txt @@ -239,6 +239,12 @@ device_manager { config_file: "devices/motor/lingkong_motors.pb.txt" enable: true } + devices { + id: "lingkong_arm" + type: DEVICE_TYPE_ROBOT_ARM + config_file: "devices/arm/lingkong_arm.pb.txt" + enable: true + } devices { id: "tchl_joint_motors" type: DEVICE_TYPE_MOTOR_SYSTEM diff --git a/cmvr-es/devices/arm/aubo_arm/src/aubo_arm.cpp b/cmvr-es/devices/arm/aubo_arm/src/aubo_arm.cpp index 06df334c..f7d3f70c 100644 --- a/cmvr-es/devices/arm/aubo_arm/src/aubo_arm.cpp +++ b/cmvr-es/devices/arm/aubo_arm/src/aubo_arm.cpp @@ -290,26 +290,6 @@ SafetyMode toPublicSafetyMode( return SafetyMode::Unknown; } -std::vector listAuboWorldFrames( - const arcs::common_interface::SyncMovePtr& sync_move) -{ - if (!sync_move) { - return {}; - } - - std::set frame_names{"world", "base", "flange", "tcp"}; - std::vector pending(frame_names.begin(), frame_names.end()); - for (std::size_t index = 0; index < pending.size(); ++index) { - for (const auto& child : sync_move->frameGetChildren(pending[index])) { - if (!child.empty() && sync_move->frameExist(child) && - frame_names.insert(child).second) { - pending.push_back(child); - } - } - } - return {frame_names.begin(), frame_names.end()}; -} - CartesianPose auboPoseFromVector(const std::vector& values, const std::string& context) { @@ -324,14 +304,6 @@ CartesianPose auboPoseFromVector(const std::vector& values, }; } -void insertFrameName(std::set& frame_names, - const std::string& frame_name) -{ - if (!frame_name.empty()) { - frame_names.insert(frame_name); - } -} - bool isAuboTcpFrame(const arcs::common_interface::SyncMovePtr& sync_move, const std::string& frame_name) { @@ -871,110 +843,21 @@ bool AuboArm::isFault() const Result AuboArm::listBaseFrame(std::vector& frame_names) const { frame_names.clear(); - const auto ready = ensureConnected_("ListBaseFrame"); - if (!ready.ok()) { - return ready; + // Listing configured frames does not require a controller connection. + if (!vendor_cfg_.base_frame().empty()) { + frame_names.push_back(vendor_cfg_.base_frame()); } - -#if defined(CMVR_HAS_AUBO_SDK) - try { - // Frame discovery can be slow on older controllers. Keep its longer - // timeout and possible disconnect isolated from state/control RPCs. - arcs::aubo_sdk::RpcClient frame_client; - frame_client.setRequestTimeout(10000); - frame_client.connect(ip_, port_); - frame_client.login(username_, password_); - const auto robot_names = frame_client.getRobotNames(); - if (robot_names.empty()) { - return Result::failure( - ArmErrorCode::RobotNotReady, - "[AuboArm] robot name list is empty"); - } - const auto robot_interface = - frame_client.getRobotInterface(robot_names.front()); - if (!robot_interface || !robot_interface->getSyncMove()) { - return Result::failure( - ArmErrorCode::RobotNotReady, - "[AuboArm] world-frame interface is unavailable"); - } - std::set available_frames{"world", "base"}; - insertFrameName(available_frames, vendor_cfg_.base_frame()); - try { - const auto discovered_frames = - listAuboWorldFrames(robot_interface->getSyncMove()); - available_frames.insert( - discovered_frames.begin(), discovered_frames.end()); - } catch (const std::exception& e) { - // Older Aubo controller releases do not expose - // SyncMove.frameGetChildren even though SDK 0.27.1 declares it. - // Keep the built-in/configured frames usable instead of failing - // the whole gRPC request with JSON-RPC -32601. - CMVR_LOG(WARNING) - << "[AuboArm] ListBaseFrame dynamic discovery unavailable; " - "using built-in/configured frames: " - << e.what(); - } - frame_names.assign(available_frames.begin(), available_frames.end()); - return Result::success(); - } catch (const std::exception& e) { - return Result::failure( - ArmErrorCode::CommandFailed, - std::string("[AuboArm] ListBaseFrame failed: ") + e.what()); - } -#else - return unsupported_("ListBaseFrame"); -#endif + return Result::success(); } Result AuboArm::listTCPFrame(std::vector& frame_names) const { frame_names.clear(); - const auto ready = ensureConnected_("ListTCPFrame"); - if (!ready.ok()) { - return ready; + // Do not enumerate SDK frames or add names absent from the configuration. + if (!vendor_cfg_.tool_frame().empty()) { + frame_names.push_back(vendor_cfg_.tool_frame()); } - -#if defined(CMVR_HAS_AUBO_SDK) - try { - const auto robot_names = sdk_->rpc_client->getRobotNames(); - if (robot_names.empty()) { - return Result::failure( - ArmErrorCode::RobotNotReady, - "[AuboArm] robot name list is empty"); - } - const auto robot_interface = - sdk_->rpc_client->getRobotInterface(robot_names.front()); - if (!robot_interface || !robot_interface->getSyncMove()) { - return Result::failure( - ArmErrorCode::RobotNotReady, - "[AuboArm] world-frame interface is unavailable"); - } - const auto sync_move = robot_interface->getSyncMove(); - std::set available_frames{"tool0", "flange", "tcp"}; - insertFrameName(available_frames, vendor_cfg_.tool_frame()); - try { - for (const auto& frame_name : listAuboWorldFrames(sync_move)) { - if (frame_name != "flange" && frame_name != "tcp" && - isAuboTcpFrame(sync_move, frame_name)) { - available_frames.insert(frame_name); - } - } - } catch (const std::exception& e) { - CMVR_LOG(WARNING) - << "[AuboArm] ListTCPFrame dynamic discovery unavailable; " - "using built-in/configured frames: " - << e.what(); - } - frame_names.assign(available_frames.begin(), available_frames.end()); - return Result::success(); - } catch (const std::exception& e) { - return Result::failure( - ArmErrorCode::CommandFailed, - std::string("[AuboArm] ListTCPFrame failed: ") + e.what()); - } -#else - return unsupported_("ListTCPFrame"); -#endif + return Result::success(); } Result AuboArm::torqueOn() 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 2790897e..1d7ceea5 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 @@ -472,7 +472,24 @@ 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. - if (!position(id, q, std::abs(qd))) return false; + auto* n = node(id); + if (!n || !std::isfinite(q) || !std::isfinite(qd)) return false; + const double conversion = scale(id); + if (!std::isfinite(conversion) || conversion <= 0) return false; + + // A4's smallest non-zero ceiling is 1 motor degree/s. Keep the planned + // position reference even below that resolution; never pass zero to + // position(), where it selects the configured maximum speed. In particular + // the final zero-velocity sample must remain an A4 position hold, not A3, + // a maximum-speed catch-up, a torque-off, or a new measured-position target. + // This is a software cyclic-position adapter, not hardware-synchronized CSP. + const double minimum_speed = 1.0 / conversion; + const double requested_speed = std::max(std::abs(qd), minimum_speed); + if (n->config.limit_qd() > 0 && requested_speed > n->config.limit_qd()) return false; + // Avoid rounding the exact one-unit lower bound down to zero in position(). + const double speed = std::max(requested_speed, + std::nextafter(minimum_speed, std::numeric_limits::infinity())); + if (!position(id, q, speed)) return false; return true; } bool LingkongCanProtocol::commandCyclicVelocity(uint8_t id, double qd) 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 f3de6a71..0af07bac 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 @@ -299,6 +299,66 @@ TEST_F(LingkongTest, ReachedTargetUsesRealMultiTurnPosition) { ASSERT_TRUE(protocol->quickStop(1)); EXPECT_FALSE(protocol->reachedTargetQ(1)); } +TEST_F(LingkongTest, CyclicLowSpeedAndEndpointKeepExplicitMinimumCeiling) { + config.set_gear_ratio(10); + ASSERT_TRUE(protocol->configureNode(1, config)); + for (double speed : {1e-10, -1e-10, 0.0, -0.0}) { + sent.clear(); + ASSERT_TRUE(protocol->commandCyclicPosition(1, 0.5, speed)); + ASSERT_EQ(sent.size(), 2); + EXPECT_EQ(sent.front().data[0], 0x9A); + EXPECT_EQ(sent.back().data[0], 0xA4); + EXPECT_EQ(sent.back().data[2], 1); + EXPECT_EQ(sent.back().data[3], 0); + Payload expected{}; put(expected, 4, std::llround(0.5 * 10 * 18000 / kPi), 4); + for (int i = 4; i < 8; ++i) EXPECT_EQ(sent.back().data[i], expected[i]); + } +} + +TEST_F(LingkongTest, CyclicPositionPreservesDirectionAndRepresentableSpeed) { + for (double speed : {0.1, -0.1}) { + sent.clear(); + ASSERT_TRUE(protocol->commandCyclicPosition(1, -0.5, speed)); + ASSERT_EQ(sent.size(), 2); + EXPECT_EQ(sent.back().data[0], 0xA4); + EXPECT_EQ(sent.back().data[2], 34); + EXPECT_EQ(sent.back().data[3], 0); + Payload expected{}; put(expected, 4, std::llround(-0.5 * 6 * 18000 / kPi), 4); + for (int i = 4; i < 8; ++i) EXPECT_EQ(sent.back().data[i], expected[i]); + } +} + +TEST_F(LingkongTest, CyclicPositionRejectsUnrepresentableLimitAndInvalidSpeed) { + EXPECT_FALSE(protocol->commandCyclicPosition(1, 0.1, std::numeric_limits::quiet_NaN())); + EXPECT_FALSE(protocol->commandCyclicPosition(1, 0.1, std::numeric_limits::infinity())); + EXPECT_FALSE(protocol->commandCyclicPosition(1, 0.1, 2.0)); + config.set_limit_qd(0.0001); + ASSERT_TRUE(protocol->configureNode(1, config)); + EXPECT_FALSE(protocol->commandCyclicPosition(1, 0.1, 0)); + EXPECT_TRUE(sent.empty()); +} + +TEST_F(LingkongTest, ThreeCyclicAxesRetainIndependentEndpointTargets) { + for (int id = 1; id <= 3; ++id) { + if (id != 1) ASSERT_TRUE(protocol->initNode(id)); + auto axis = config; + axis.set_id(id); + axis.set_gear_ratio(10); + ASSERT_TRUE(protocol->configureNode(id, axis)); + } + for (int id = 1; id <= 3; ++id) { + sent.clear(); + const double target = (id - 2) * 0.5; + ASSERT_TRUE(protocol->commandCyclicPosition(id, target, 0)); + ASSERT_EQ(sent.size(), 2); + EXPECT_EQ(sent.back().id, 0x140 + id); + EXPECT_EQ(sent.back().data[0], 0xA4); + EXPECT_EQ(sent.back().data[2], 1); + Payload expected{}; put(expected, 4, std::llround(target * 10 * 18000 / kPi), 4); + for (int i = 4; i < 8; ++i) EXPECT_EQ(sent.back().data[i], expected[i]); + } +} + TEST_F(LingkongTest, ShortAndUnsolicitedPacketsAreIgnored) { auto* parser = manager->GetMutableProtocolDataById(0x141); Payload old{}; old[0] = 0x92; From de124daa8aa7b09f14370d00809c21e160f133e3 Mon Sep 17 00:00:00 2001 From: xtkuang <87661715@qq.com> Date: Mon, 2 Nov 2026 17:30:34 +0800 Subject: [PATCH 2/2] fix(lingkong): support permanent zero and robust motor shutdown Treat non-0x10 native states as running only when the error byte is zero, while retaining raw diagnostics and blocking motion on faults. Save zero with CAN 0x19 and validate its offset reply without position readback or automatic reboot. Propagate calibration failures to the arm API. Return shutdown failures without throwing and continue motor/bus cleanup after per-device errors. Keep the three-node Lingkong configuration. Validation: 35 fake-transport protocol tests and 2 motor-manager shutdown tests passed; full make install completed. No physical zero writes or motion tests were performed for these changes. --- .../devices/motor/lingkong_motors.pb.txt | 2 +- .../motor_robot_arm/src/motor_robot_arm.cpp | 5 +- .../include/lingkong_can_protocol.h | 5 + .../src/lingkong_can_protocol.cpp | 28 ++++- .../lingkong_can/src/lingkong_motor.cpp | 4 +- .../src/protocol/lingkong_motor_response.cpp | 2 + .../tests/lingkong_motor_protocol_test.cpp | 107 +++++++++++++++++- cmvr-es/devices/motor/manager/CMakeLists.txt | 5 + .../motor/manager/src/motor_manager.cpp | 28 ++++- .../src/motor_manager_shutdown_test.cpp | 43 +++++++ 10 files changed, 211 insertions(+), 18 deletions(-) create mode 100644 cmvr-es/devices/motor/manager/src/motor_manager_shutdown_test.cpp diff --git a/cmvr-es/config/devices/motor/lingkong_motors.pb.txt b/cmvr-es/config/devices/motor/lingkong_motors.pb.txt index d6636f83..5e8f83a6 100644 --- a/cmvr-es/config/devices/motor/lingkong_motors.pb.txt +++ b/cmvr-es/config/devices/motor/lingkong_motors.pb.txt @@ -1,4 +1,4 @@ -# Three MG4005E-i10 V3 motors on can0, CAN node IDs 1/2/3. +# Three Lingkong motors on can0, CAN node IDs 1/2/3. # All public q/qd values refer to OUTPUT shaft radians/radians per second. # SOFTWARE limits retained from the previous single-motor installation. motor { 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 39007c18..01e2657b 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 @@ -312,7 +312,10 @@ Result MotorRobotArm::calibrateZeroQ(const std::string& joint_name) if (!motor) { return Result::failure(ArmErrorCode::RobotNotReady, "motor not found for joint: " + joint_name); } - motor->calibrateZeroQ(); + if (!motor->calibrateZeroQ()) { + return Result::failure(ArmErrorCode::CommandFailed, + "failed to set zero for joint: " + joint_name); + } return Result::success(); } 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 1666b243..2ec12916 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 @@ -21,6 +21,11 @@ public: 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. + // Preserve raw state/error bytes for diagnostics. + bool isRunning() const { + return motor_state != 0x10 && error == 0; + } }; LingkongCanProtocol(Send send, std::shared_ptr> manager); bool initNode(uint8_t node_id) override; 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 1d7ceea5..5de9b6e1 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 @@ -129,7 +129,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) && readFeedback(id, q, qd); + return readStatus(id, status) && status.error == 0 && readFeedback(id, q, qd); } bool LingkongCanProtocol::setMode(uint8_t id, msgs::RunMode mode) @@ -305,8 +305,18 @@ bool LingkongCanProtocol::torqueOff(uint8_t id) if (auto* n = node(id)) n->target_valid = false; // 0x80 clears multi-turn count. if (!simple(id, 0x80)) return false; Status status; - if (!readStatus(id, status)) throw std::runtime_error("Lingkong: shutdown acknowledged but 9A status read failed"); - if (status.motor_state != 0x10) throw std::runtime_error("Lingkong: 80 acknowledged but drive is not closed (9A)"); + if (!readStatus(id, status)) { + CMVR_LOG(ERROR) << "[LingkongCanProtocol] close unconfirmed: node=" << int(id) + << "; 80 acknowledged but 9A status read failed"; + return false; + } + if (status.motor_state != 0x10 || status.error != 0) { + 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"; + return false; + } return true; } bool LingkongCanProtocol::quickStop(uint8_t id, double /*deceleration*/) @@ -327,7 +337,13 @@ bool LingkongCanProtocol::calibrateZeroQ(uint8_t id) { std::lock_guard lock(mutex_); if (auto* n = node(id)) n->target_valid = false; - return simple(id, 0x95); + Payload request{}, response{}; + 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"; + return true; } bool LingkongCanProtocol::clearError(uint8_t id) { @@ -366,7 +382,7 @@ 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; + 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; @@ -399,7 +415,7 @@ 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.motor_state != 0) throw std::runtime_error("Lingkong: drive is closed (9A motorState=0x10); call torqueOn explicitly before motion"); + if (!status.isRunning()) throw std::runtime_error("Lingkong: drive is closed (9A motorState=0x10); call torqueOn explicitly before motion"); } bool LingkongCanProtocol::position(uint8_t id, double q, double qd) 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 de4ed8af..2ae59102 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 @@ -72,9 +72,9 @@ bool LingkongMotor::readDiagnosticState(std::uint16_t& status, std::uint16_t& er 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. + status = native.motor_state; // Preserve native state, including HV V3 0x30. error = native.error; - enabled = native.motor_state == 0; + enabled = native.isRunning(); fault = native.error != 0; 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 a1dc5309..bf633b2e 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 @@ -13,6 +13,8 @@ void LingkongMotorResponse::Parse(const uint8_t* bytes, int32_t length, msgs::Ro 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] == 0x8C && request_[1] != 0x10 && bytes[1] != request_[1]) return; std::copy(bytes, bytes + 8, response_.begin()); received_ = true; 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 0af07bac..81973d26 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 @@ -142,7 +142,7 @@ TEST_F(LingkongTest, NativeStatusIsNotDecodedAsCia402) { 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); + EXPECT_FALSE(enabled); EXPECT_TRUE(fault); EXPECT_EQ(ec, 8); } TEST_F(LingkongTest, PositionAndNegativeSpeedPackets) { @@ -166,7 +166,7 @@ TEST_F(LingkongTest, EnableHoldsCurrentPositionAndOtherOperationsStayExplicit) { ASSERT_TRUE(protocol->torqueOff(1)); EXPECT_EQ(sent[6].data[0], 0x80); EXPECT_EQ(sent.back().data[0], 0x9A); 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->calibrateZeroQ(1)); EXPECT_EQ(sent.back().data[0], 0x19); ASSERT_TRUE(protocol->clearError(1)); EXPECT_EQ(sent.back().data[0], 0x9B); EXPECT_EQ(sent.size(), 12); EXPECT_TRUE(protocol->setMode(1, msgs::RUN_MODE_CYCLIC_SYNC_POSITION)); @@ -384,7 +384,7 @@ TEST_F(LingkongTest, RunAndCloseEchoMustBeConfirmedByRealStatus) { mutate = [](Payload& p) { if (p[0] == 0x9A) p[6] = 0x10; }; EXPECT_THROW(protocol->torqueOn(1), std::runtime_error); mutate = [](Payload& p) { if (p[0] == 0x9A) p[6] = 0; }; - EXPECT_THROW(protocol->torqueOff(1), std::runtime_error); + EXPECT_FALSE(protocol->torqueOff(1)); } TEST_F(LingkongTest, NativeA3AndA4DoNotRequireModeSelectionOrB1) { @@ -446,3 +446,104 @@ TEST_F(LingkongTest, FailedHoldRollsBackToClosedAndInvalidatesTarget) { EXPECT_FALSE(protocol->reachedTargetQ(1)); } } // namespace + +TEST_F(LingkongTest, HvState30WithoutFaultInitializesAndReportsRawEnabledState) { + state = 0x30; + auto second = config; second.set_id(2); + LingkongMotor motor(second); + ASSERT_TRUE(motor.setProtocol(protocol)); + ASSERT_TRUE(motor.init()); + uint16_t sw, ec; bool enabled, fault; + ASSERT_TRUE(motor.readDiagnosticState(sw, ec, enabled, fault)); + EXPECT_EQ(sw, 0x30); EXPECT_EQ(ec, 0); + EXPECT_TRUE(enabled); EXPECT_FALSE(fault); + for (const auto& frame : sent) + EXPECT_TRUE(frame.data[0] == 0x9A || frame.data[0] == 0x92 || frame.data[0] == 0x9C); + sent.clear(); + EXPECT_TRUE(protocol->commandProfilePosition(1, 0.1, 0.1, 1)); + ASSERT_EQ(sent.size(), 2); EXPECT_EQ(sent.back().data[0], 0xA4); +} + +TEST_F(LingkongTest, HvState30WithAnyFaultNeverDispatchesMotion) { + state = 0x30; + for (unsigned bit = 0; bit < 8; ++bit) { + error = uint8_t(1u << bit); + EXPECT_FALSE(protocol->probe(1)); + EXPECT_THROW(protocol->commandProfilePosition(1, 0.1, 0.1, 1), std::runtime_error); + } + for (const auto& frame : sent) EXPECT_EQ(frame.data[0], 0x9A); +} + +TEST_F(LingkongTest, AllNativeStatesFollowNon10NoFaultPolicy) { + auto second = config; second.set_id(2); + LingkongMotor motor(second); + ASSERT_TRUE(motor.setProtocol(protocol)); + for (unsigned value = 0; value <= 255; ++value) { + state = uint8_t(value); error = 0; + ASSERT_TRUE(motor.init()) << value; + 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_THROW(protocol->commandProfilePosition(1, 0.1, 0.1, 1), std::runtime_error); + } else { + EXPECT_TRUE(protocol->commandProfilePosition(1, 0.1, 0.1, 1)) << value; + } + for (unsigned bit = 0; bit < 8; ++bit) { + error = uint8_t(1u << bit); + EXPECT_FALSE(protocol->probe(1)); + ASSERT_TRUE(motor.readDiagnosticState(raw, ec, enabled, fault)); + EXPECT_EQ(raw, value); EXPECT_EQ(ec, error); + EXPECT_FALSE(enabled); EXPECT_TRUE(fault); + sent.clear(); + EXPECT_THROW(protocol->commandProfilePosition(1, 0.1, 0.1, 1), std::runtime_error); + ASSERT_EQ(sent.size(), 1); EXPECT_EQ(sent[0].data[0], 0x9A); + } + } +} + +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); }; + ASSERT_TRUE(protocol->calibrateZeroQ(1)); + ASSERT_EQ(sent.size(), 1); + EXPECT_EQ(sent[0].data[0], 0x19); + for (unsigned i = 1; i < 8; ++i) EXPECT_EQ(sent[0].data[i], 0); + EXPECT_FALSE(protocol->reachedTargetQ(1)); + EXPECT_EQ(sent.size(), 1); // No reboot, motion, retries or redundant ROM writes. +} + +TEST_F(LingkongTest, PermanentZeroRequiresValidAcknowledgement) { + respond = false; + EXPECT_FALSE(protocol->calibrateZeroQ(1)); + respond = true; + mutate = [](Payload& p) { if (p[0] == 0x19) p[0] = 0x95; }; + EXPECT_FALSE(protocol->calibrateZeroQ(1)); + for (unsigned byte = 1; byte <= 3; ++byte) { + mutate = [byte](Payload& p) { if (p[0] == 0x19) p[byte] = 1; }; + EXPECT_FALSE(protocol->calibrateZeroQ(1)); + } + ASSERT_EQ(sent.size(), 5); + for (const auto& frame : sent) EXPECT_EQ(frame.data[0], 0x19); +} + +TEST_F(LingkongTest, CloseFailuresReturnFalseWithoutThrowingOrSendingMoreCommands) { + for (const uint8_t returned : {0x00, 0x20, 0x30, 0xFF}) { + mutate = [returned](Payload& p) { if (p[0] == 0x9A) p[6] = returned; }; + sent.clear(); + EXPECT_FALSE(protocol->torqueOff(1)); + ASSERT_EQ(sent.size(), 2); + EXPECT_EQ(sent[0].data[0], 0x80); EXPECT_EQ(sent[1].data[0], 0x9A); + } + mutate = [](Payload& p) { if (p[0] == 0x9A) p[0] = 0; }; + EXPECT_FALSE(protocol->torqueOff(1)); + mutate = {}; error = 8; + EXPECT_FALSE(protocol->torqueOff(1)); + error = 0; + EXPECT_TRUE(protocol->torqueOff(1)); + respond = false; sent.clear(); + EXPECT_FALSE(protocol->torqueOff(1)); + ASSERT_EQ(sent.size(), 1); EXPECT_EQ(sent[0].data[0], 0x80); +} diff --git a/cmvr-es/devices/motor/manager/CMakeLists.txt b/cmvr-es/devices/motor/manager/CMakeLists.txt index 5ec6a75a..21839a76 100644 --- a/cmvr-es/devices/motor/manager/CMakeLists.txt +++ b/cmvr-es/devices/motor/manager/CMakeLists.txt @@ -20,3 +20,8 @@ target_link_libraries(motor_manager add_library(cmvr_es::device::motor_manager ALIAS motor_manager) 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) diff --git a/cmvr-es/devices/motor/manager/src/motor_manager.cpp b/cmvr-es/devices/motor/manager/src/motor_manager.cpp index 7452c502..706998e9 100644 --- a/cmvr-es/devices/motor/manager/src/motor_manager.cpp +++ b/cmvr-es/devices/motor/manager/src/motor_manager.cpp @@ -204,21 +204,39 @@ bool MotorManager::init() bool MotorManager::stop() { + bool success = true; { std::lock_guard lock(motors_mutex_); for (const auto& [joint_name, motor] : motors_by_joint_) { - (void)joint_name; - if (motor) { - motor->torqueOff(); + if (!motor) continue; + try { + if (!motor->torqueOff()) { + success = false; + CMVR_LOG(ERROR) << "[MotorManager] close unconfirmed during stop: " << joint_name; + } + } catch (const std::exception& e) { + success = false; + CMVR_LOG(ERROR) << "[MotorManager] close failed during stop: " << joint_name << ": " << e.what(); + } catch (...) { + success = false; + CMVR_LOG(ERROR) << "[MotorManager] unknown close exception during stop: " << joint_name; } } } + // Always stop every bus, even if a drive fails to acknowledge closing. for (auto& bus_runtime : bus_runtimes_) { - if (bus_runtime) { + if (!bus_runtime) continue; + try { bus_runtime->stop(); + } catch (const std::exception& e) { + success = false; + CMVR_LOG(ERROR) << "[MotorManager] bus stop failed: " << e.what(); + } catch (...) { + success = false; + CMVR_LOG(ERROR) << "[MotorManager] unknown bus stop exception"; } } - return true; + return success; } bool MotorManager::addMotor(const std::shared_ptr& motor) 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 new file mode 100644 index 00000000..4c3eafdd --- /dev/null +++ b/cmvr-es/devices/motor/manager/src/motor_manager_shutdown_test.cpp @@ -0,0 +1,43 @@ +#include "include/motor_manager.h" +#include +#include +using namespace cmvr; +using namespace cmvr::device; +namespace { +class ShutdownMotor final : public AbstractMotor { +public: + enum Outcome { Ok, Reject, Throw, Unknown }; + Outcome outcome; int calls=0; + ShutdownMotor(int id, Outcome value):outcome(value) { + node_id_=id; info_.id=id; info_.joint_name="shutdown_test_"+std::to_string(id); + } + std::string typeName() const override { return "ShutdownMotor"; } + bool setLimitQ(double,double) override { return true; } + bool setLimitQd(double) override { return true; } + bool brakeRelease() override { return true; } + bool calibrateZeroQ() override { return true; } + bool torqueOff() override { + ++calls; + if(outcome==Throw) throw std::runtime_error("80 acknowledged but drive is not closed (9A)"); + if(outcome==Unknown) throw 7; + return outcome==Ok; + } +}; +TEST(MotorManagerShutdown, ContinuesAllMotorsAfterFailuresAndNeverThrows) { + MotorManager manager("shutdown",config::MotorConfig{},"test"); + auto a=std::make_shared(1,ShutdownMotor::Throw); + auto b=std::make_shared(2,ShutdownMotor::Reject); + auto c=std::make_shared(3,ShutdownMotor::Ok); + auto d=std::make_shared(4,ShutdownMotor::Unknown); + for(const auto& motor:{a,b,c,d}) ASSERT_TRUE(manager.addMotor(motor)); + EXPECT_FALSE(manager.stop()); + for(const auto& motor:{a,b,c,d}) EXPECT_EQ(motor->calls,1); + for(const auto& motor:{a,b,c,d}) motor->outcome=ShutdownMotor::Ok; + EXPECT_TRUE(manager.stop()); + for(const auto& motor:{a,b,c,d}) EXPECT_EQ(motor->calls,2); +} +TEST(MotorManagerShutdown, EmptyManagerStopsSuccessfully) { + MotorManager manager("empty",config::MotorConfig{},"test"); + EXPECT_TRUE(manager.stop()); +} +}