From 3e1016041103faf6192e13b2078890935f2650ec Mon Sep 17 00:00:00 2001 From: xtkuang <87661715@qq.com> Date: Fri, 27 Nov 2026 09:35:16 +0800 Subject: [PATCH] feat: port Huayan cabinet IO and bounded SocketCAN receive to dev --- cmvr-es/devices/arm/huayan_arm/CMakeLists.txt | 8 ++ cmvr-es/devices/arm/huayan_arm/README_IO.md | 31 +++++++ cmvr-es/devices/arm/huayan_arm/huayan_arm.cpp | 84 +++++++++++++++++++ cmvr-es/devices/arm/huayan_arm/huayan_arm.h | 2 + .../tests/huayan_cabinet_io_test.cpp | 53 ++++++++++++ .../socket/socket_can_client_raw.cc | 4 +- .../can_client/socket/socket_can_client_raw.h | 3 +- 7 files changed, 183 insertions(+), 2 deletions(-) create mode 100644 cmvr-es/devices/arm/huayan_arm/README_IO.md create mode 100644 cmvr-es/devices/arm/huayan_arm/tests/huayan_cabinet_io_test.cpp diff --git a/cmvr-es/devices/arm/huayan_arm/CMakeLists.txt b/cmvr-es/devices/arm/huayan_arm/CMakeLists.txt index ca88f4fc..01d4be44 100644 --- a/cmvr-es/devices/arm/huayan_arm/CMakeLists.txt +++ b/cmvr-es/devices/arm/huayan_arm/CMakeLists.txt @@ -21,6 +21,7 @@ target_link_libraries(huayan_arm cmvr_es::proto PRIVATE HR_Pro + jsoncpp glog Threads::Threads ) @@ -29,3 +30,10 @@ add_library(cmvr_es::device::huayan_arm ALIAS huayan_arm) install(TARGETS huayan_arm LIBRARY DESTINATION lib) install(FILES ${HUAYAN_ARM_SDK_DIR}/lib/libHR_Pro.so DESTINATION lib) + +if(BUILD_TESTING) + add_executable(huayan_cabinet_io_test tests/huayan_cabinet_io_test.cpp) + set_target_properties(huayan_cabinet_io_test PROPERTIES ENABLE_EXPORTS ON) + target_link_libraries(huayan_cabinet_io_test PRIVATE cmvr_es::device::huayan_arm jsoncpp gtest gtest_main) + add_test(NAME huayan_cabinet_io_test COMMAND huayan_cabinet_io_test) +endif() diff --git a/cmvr-es/devices/arm/huayan_arm/README_IO.md b/cmvr-es/devices/arm/huayan_arm/README_IO.md new file mode 100644 index 00000000..79e93698 --- /dev/null +++ b/cmvr-es/devices/arm/huayan_arm/README_IO.md @@ -0,0 +1,31 @@ +# Cabinet CI/CO IO + +Use `cmvr.api.ArmService.ExecuteJsonCommand`, with the same parameter names as Aubo. +The request header selects the Huayan arm device. The following object is serialized +as the `request_json` string: + +```json +{"command":"cabinet_io","operation":"set_do","index":0,"value":true} +``` + +`index: 0` selects **CO0**, not DO0. `true` writes 1, `false` writes 0. +Writing calls `HRIF_SetBoxCO`; reading uses `HRIF_ReadBoxCO`. +For readback, use: + +```json +{"command":"cabinet_io","operation":"get_do","index":0} +``` + +`get_di` reads the corresponding configurable **CI** input. +The SDK supplies the available CI/CO count; channel numbers start at zero. +`value` must be a JSON boolean for writes. No motion enable is performed. + +The gRPC response uses the existing `header` and `response_json` fields. +The JSON response contains `success`, `command`, `operation`, `index`, `count`, +`io_type` (CI or CO), and `sdk_return_code`. Reads return `value`; successful +writes return `requested_value`, which indicates SDK command success and does not +claim physical readback. Failures return `error_code` and `error_message`. +Aubo-specific `runstate` fields are not fabricated for Huayan. + +Build `huayan_cabinet_io_test` with `BUILD_TESTING=ON` for offline verification. +The test executable replaces the IO SDK symbols and does not connect to hardware. diff --git a/cmvr-es/devices/arm/huayan_arm/huayan_arm.cpp b/cmvr-es/devices/arm/huayan_arm/huayan_arm.cpp index 9eedff74..2de3207c 100644 --- a/cmvr-es/devices/arm/huayan_arm/huayan_arm.cpp +++ b/cmvr-es/devices/arm/huayan_arm/huayan_arm.cpp @@ -1,6 +1,8 @@ #include "huayan_arm.h" #include +#include +#include #include #include #include @@ -112,6 +114,88 @@ HuayanRobot::~HuayanRobot() (void)disconnect(); } + +bool HuayanRobot::executeJsonCommand(const std::string& request_json, std::string& response_json) +{ + Json::Value response(Json::objectValue); + const auto put = [&](const char* key) -> Json::Value& { + return *response.demand(key, key + std::char_traits::length(key)); + }; + const auto serialize = [&]() { + Json::StreamWriterBuilder writer; + writer[std::string("indentation")] = ""; + response_json = Json::writeString(writer, response); + }; + put("success") = false; + const auto fail = [&](const std::string& code, const std::string& message) { + put("error_code") = code; put("error_message") = message; serialize(); + CMVR_LOG(ERROR) << "[HuayanRobot] cabinet_io: " << message; + return false; + }; + Json::Value root; Json::CharReaderBuilder builder; + std::unique_ptr reader(builder.newCharReader()); + std::string error; + if (!reader->parse(request_json.data(), request_json.data() + request_json.size(), &root, &error)) + return fail("invalid_json", "invalid json: " + error); + if (!root.isObject()) return fail("invalid_json", "invalid json: root must be an object"); + const auto member = [&](const char* key) { return root.find(key, key + std::char_traits::length(key)); }; + const auto text = [&](const char* key) { + const auto* v = member(key); + std::string value = v && v->isString() ? v->asString() : std::string{}; + std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) { return std::tolower(c); }); + return value; + }; + const auto command = text("command"); + if (command.empty()) return fail("invalid_argument", "field 'command' is required and must be a non-empty string"); + if (command != "cabinet_io") return fail("unsupported_command", "unsupported json command: " + command); + put("command") = command; + const auto operation = text("operation"); + if (operation.empty()) return fail("invalid_argument", "field 'operation' is required and must be a non-empty string"); + if (operation != "get_di" && operation != "get_do" && operation != "set_do") + return fail("invalid_operation", "unsupported cabinet_io operation: " + operation); + put("operation") = operation; + const auto* index_value = member("index"); + if (!index_value || !index_value->isInt() || index_value->asInt() < 0) + return fail("invalid_argument", "field 'index' is required and must be a non-negative JSON integer"); + const int index = index_value->asInt(); put("index") = index; + const auto* value = member("value"); + if (operation == "set_do" && (!value || !value->isBool())) + return fail("invalid_argument", "field 'value' is required for set_do and must be a JSON boolean"); + std::lock_guard lock(mutex_); + const auto ready = ensureConnected_("cabinet_io"); + if (!ready.ok()) return fail("not_connected", ready.message); + try { + // Same request shape as Aubo; Huayan configurable cabinet ports are CI/CO. + // CO0 is index 0, not the separate general-purpose DO0 terminal. + std::vector ports; + const bool input = operation == "get_di"; + int ret = input ? HRIF_ReadAllBoxCI(box_id_, ports) : HRIF_ReadAllBoxCO(box_id_, ports); + put("io_type") = input ? "CI" : "CO"; put("sdk_return_code") = ret; + if (ret != 0) return fail("sdk_command_failed", "failed to read IO count: sdk ret=" + std::to_string(ret)); + put("count") = static_cast(ports.size()); + if (static_cast(index) >= ports.size()) + return fail("index_out_of_range", "cabinet_io index out of range: index=" + std::to_string(index) + ", count=" + std::to_string(ports.size())); + if (operation == "set_do") { + ret = HRIF_SetBoxCO(box_id_, index, value->asBool() ? 1 : 0); + put("sdk_return_code") = ret; + if (ret != 0) return fail("sdk_command_failed", "cabinet_io set_do failed: sdk ret=" + std::to_string(ret)); + put("requested_value") = value->asBool(); + } else { + int actual = -1; + ret = input ? HRIF_ReadBoxCI(box_id_, index, actual) : HRIF_ReadBoxCO(box_id_, index, actual); + put("sdk_return_code") = ret; + if (ret != 0) return fail("sdk_command_failed", "cabinet_io read failed: sdk ret=" + std::to_string(ret)); + if (actual != 0 && actual != 1) return fail("invalid_io_value", "cabinet_io returned a non-digital value"); + put("value") = actual != 0; + } + put("success") = true; serialize(); + CMVR_LOG(INFO) << "[HuayanRobot] cabinet_io: operation=" << operation << ", index=" << index << ", sdk ret=" << ret; + return true; + } catch (const std::exception& e) { + return fail("sdk_exception", std::string("[HuayanRobot] cabinet_io failed: ") + e.what()); + } +} + bool HuayanRobot::init() { if (ip_.empty()) { diff --git a/cmvr-es/devices/arm/huayan_arm/huayan_arm.h b/cmvr-es/devices/arm/huayan_arm/huayan_arm.h index 0ebccc17..7cd76824 100644 --- a/cmvr-es/devices/arm/huayan_arm/huayan_arm.h +++ b/cmvr-es/devices/arm/huayan_arm/huayan_arm.h @@ -28,6 +28,7 @@ public: ~HuayanRobot() override; std::string typeName() const override { return "HuayanRobot"; } + bool executeJsonCommand(const std::string& request_json, std::string& response_json) override; bool init() override; bool stop() override; @@ -107,6 +108,7 @@ public: bool busy() const override { return busy_.load(); } private: + friend struct HuayanIoTestAccess; struct HrState { int moving{0}; int enabled{0}; diff --git a/cmvr-es/devices/arm/huayan_arm/tests/huayan_cabinet_io_test.cpp b/cmvr-es/devices/arm/huayan_arm/tests/huayan_cabinet_io_test.cpp new file mode 100644 index 00000000..51eff26b --- /dev/null +++ b/cmvr-es/devices/arm/huayan_arm/tests/huayan_cabinet_io_test.cpp @@ -0,0 +1,53 @@ +// Executable SDK symbol overrides: no connection to hardware and no physical IO writes. +#include "huayan_arm.h" +#include +#include +#include +#include +namespace { int calls=0, written=-1, channel=-1, result=0, actual=1; } +extern "C" bool HRIF_IsConnected(unsigned int) { return true; } +extern "C" int HRIF_ReadAllBoxCO(unsigned int,std::vector& v) { ++calls;v={0,0,0,0};return result; } +extern "C" int HRIF_ReadAllBoxCI(unsigned int,std::vector& v) { ++calls;v={0,0};return result; } +extern "C" int HRIF_SetBoxCO(unsigned int,int bit,int value) { ++calls;channel=bit;written=value;return result; } +extern "C" int HRIF_ReadBoxCO(unsigned int,int bit,int& value) { ++calls;channel=bit;value=actual;return result; } +extern "C" int HRIF_ReadBoxCI(unsigned int,int bit,int& value) { ++calls;channel=bit;value=actual;return result; } +namespace cmvr::device { +const Json::Value& get(const Json::Value& r,const char* key) {const auto* p=r.find(key,key+std::char_traits::length(key));if(!p)throw std::runtime_error("missing response field");return *p;} +struct HuayanIoTestAccess {static void connected(HuayanRobot& arm,bool value){arm.connected_=value;}}; +class HuayanCabinetIo : public ::testing::Test { +protected: + config::RobotArmConfig cfg; + std::unique_ptr arm; + void SetUp()override {calls=0;written=-1;channel=-1;result=0;actual=1;cfg.set_id("fake_huayan");arm=std::make_unique(cfg);HuayanIoTestAccess::connected(*arm,true);} + void TearDown()override {HuayanIoTestAccess::connected(*arm,false);arm.reset();} + Json::Value invoke(const std::string& request,bool success) {std::string response;EXPECT_EQ(arm->executeJsonCommand(request,response),success);Json::Value value;Json::CharReaderBuilder reader;std::string error;std::istringstream in(response);EXPECT_TRUE(Json::parseFromStream(reader,in,&value,&error));return value;} +}; +TEST_F(HuayanCabinetIo, SameAuboParametersSetCO0HighAndLow) { + auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":true})",true); + EXPECT_EQ(channel,0);EXPECT_EQ(written,1);EXPECT_TRUE(get(r,"requested_value").asBool());EXPECT_EQ(get(r,"io_type").asString(),"CO"); + invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":false})",true);EXPECT_EQ(written,0); +} +TEST_F(HuayanCabinetIo, ReadActualCOAndCI) { + auto r=invoke(R"({"command":"cabinet_io","operation":"get_do","index":0})",true);EXPECT_TRUE(get(r,"value").asBool());EXPECT_EQ(channel,0); + actual=0;r=invoke(R"({"command":"cabinet_io","operation":"get_di","index":1})",true);EXPECT_FALSE(get(r,"value").asBool());EXPECT_EQ(get(r,"io_type").asString(),"CI"); +} +TEST_F(HuayanCabinetIo, RejectInvalidWithoutSdkCalls) { + for(auto request:{"{","[]",R"({"command":"other"})",R"({"command":"cabinet_io","operation":"set_do","index":0,"value":1})",R"({"command":"cabinet_io","operation":"set_do","index":-1,"value":true})",R"({"command":"cabinet_io","operation":"get_do","index":0.5})"})invoke(request,false); + EXPECT_EQ(calls,0); +} +TEST_F(HuayanCabinetIo, RejectOutOfRangeWithoutWriting) { + auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":4,"value":true})",false); + EXPECT_EQ(get(r,"error_code").asString(),"index_out_of_range");EXPECT_EQ(written,-1); +} +TEST_F(HuayanCabinetIo, PropagateSdkFailure) { + result=123;auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":true})",false); + EXPECT_EQ(get(r,"sdk_return_code").asInt(),123);EXPECT_EQ(written,-1); +} +TEST_F(HuayanCabinetIo, DisconnectedNeverCallsSdk) { + HuayanIoTestAccess::connected(*arm,false);auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":true})",false); + EXPECT_EQ(get(r,"error_code").asString(),"not_connected");EXPECT_EQ(calls,0); +} +TEST_F(HuayanCabinetIo, InvalidFeedbackIsNotReportedAsTrue) { + actual=7;auto r=invoke(R"({"command":"cabinet_io","operation":"get_do","index":0})",false);EXPECT_EQ(get(r,"error_code").asString(),"invalid_io_value"); +} +} diff --git a/cmvr-es/devices/canbus/can_client/socket/socket_can_client_raw.cc b/cmvr-es/devices/canbus/can_client/socket/socket_can_client_raw.cc index caacceb8..80ecc667 100644 --- a/cmvr-es/devices/canbus/can_client/socket/socket_can_client_raw.cc +++ b/cmvr-es/devices/canbus/can_client/socket/socket_can_client_raw.cc @@ -200,7 +200,8 @@ namespace cmvr { ErrorCode SocketCanClientRaw::receive(std::vector *const frames, int32_t *const frame_num) { - return receive(frames, frame_num, std::chrono::milliseconds{-1}); + // Periodically return to CanReceiver stop checks, even on an idle bus. + return receive(frames, frame_num, std::chrono::milliseconds{100}); } ErrorCode SocketCanClientRaw::receive(std::vector *const frames, @@ -214,6 +215,7 @@ namespace cmvr { if (frames == nullptr) { return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED; } + frames->clear(); if (!is_started_) { CMVR_LOG(ERROR) << "Nvidia can client is not init! Please init first!"; return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED; diff --git a/cmvr-es/devices/canbus/can_client/socket/socket_can_client_raw.h b/cmvr-es/devices/canbus/can_client/socket/socket_can_client_raw.h index e602238c..ae51747c 100644 --- a/cmvr-es/devices/canbus/can_client/socket/socket_can_client_raw.h +++ b/cmvr-es/devices/canbus/can_client/socket/socket_can_client_raw.h @@ -54,7 +54,7 @@ namespace cmvr { int32_t *const frame_num) override; /** - * @brief Receive messages + * @brief Receive messages with a bounded 100 ms wait so receivers can stop * @param frames The messages to receive. * @param frame_num The amount of messages to receive. * @return The status of the receiving action @@ -78,6 +78,7 @@ namespace cmvr { */ std::string getErrorString(const int32_t status) override; private: + friend class SocketCanClientRawTestPeer; int dev_handler_ = -1; cmvr::msgs::CANCardParameter::CANChannelId port_; cmvr::msgs::CANCardParameter::CANInterface interface_;