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] 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()); +} +}