diff --git a/cmvr-es/config/devices/agv/agv.pb.txt b/cmvr-es/config/devices/agv/agv.pb.txt index a22209e9..51babcce 100644 --- a/cmvr-es/config/devices/agv/agv.pb.txt +++ b/cmvr-es/config/devices/agv/agv.pb.txt @@ -20,7 +20,7 @@ agv { port_push: 19301 recv_timeout_ms: 1000 control_nick_name: "cmvr-es" - enable_state_push: true + enable_state_push: false state_push_interval_ms: 200 state_push_included_fields: "x" state_push_included_fields: "y" diff --git a/cmvr-es/config/devices/biohead/bio_head_usb.pb.txt b/cmvr-es/config/devices/biohead/bio_head_usb.pb.txt new file mode 100644 index 00000000..2c0193cd --- /dev/null +++ b/cmvr-es/config/devices/biohead/bio_head_usb.pb.txt @@ -0,0 +1,41 @@ +# Reference calibration from frozen source-channel-config.json and source-servo-config.json. +# USB path was enumerated on 192.168.0.234; opening may require user-managed permissions. +# Creating/initializing this device never moves to home automatically. +bio_head { + id: "usb_head" + serial_port: "/dev/serial/by-id/usb-CherryUSB_RTT_CDC_ACM_FS_000000000001-if00" + baud_rate: 115200 + usb_erpc { + response_timeout_ms: 2000 + joints { + id: "eye_l_up" + min_position_rad: -1.0 + max_position_rad: 1.0 + home_position_rad: 0.0 + } + joints { + id: "eye_l_lower" + min_position_rad: -0.35 + max_position_rad: 0.55 + home_position_rad: 0.0 + } + joints { + id: "eye_l_v" + min_position_rad: -1.5 + max_position_rad: 1.0 + home_position_rad: 0.0 + } + joints { + id: "eye_l_h" + min_position_rad: -0.65 + max_position_rad: 0.70 + home_position_rad: 0.0 + } + joints { + id: "pwm8_local" + min_position_rad: -1.5 + max_position_rad: 0.393 + home_position_rad: -1.0 + } + } +} diff --git a/cmvr-es/config/manager/device_manager.pb.txt b/cmvr-es/config/manager/device_manager.pb.txt index b838ed69..6fed9e38 100644 --- a/cmvr-es/config/manager/device_manager.pb.txt +++ b/cmvr-es/config/manager/device_manager.pb.txt @@ -278,4 +278,10 @@ device_manager { config_file: "devices/arm/lingkong_mixed_arm.pb.txt" enable: false } + devices { + id: "usb_head" + type: DEVICE_TYPE_BIO_HEAD_ROBOT + config_file: "devices/biohead/bio_head_usb.pb.txt" + enable: false + } } diff --git a/cmvr-es/devices/biohead/CMakeLists.txt b/cmvr-es/devices/biohead/CMakeLists.txt index d4b28155..324b743c 100644 --- a/cmvr-es/devices/biohead/CMakeLists.txt +++ b/cmvr-es/devices/biohead/CMakeLists.txt @@ -1 +1,2 @@ -add_subdirectory(biohead_esp32) \ No newline at end of file +add_subdirectory(biohead_esp32) +add_subdirectory(biohead_usb) diff --git a/cmvr-es/devices/biohead/abstract_joint_head.h b/cmvr-es/devices/biohead/abstract_joint_head.h new file mode 100644 index 00000000..dad70908 --- /dev/null +++ b/cmvr-es/devices/biohead/abstract_joint_head.h @@ -0,0 +1,100 @@ +#ifndef CMVR_ES_ABSTRACT_JOINT_HEAD_H +#define CMVR_ES_ABSTRACT_JOINT_HEAD_H + +#include +#include +#include +#include +#include + +#include "abstract_biohead.h" + +namespace cmvr::device { + +enum class HeadMotionMode : int32_t { Immediate = 0, SCurve = 1, Follow = 2 }; +enum class HeadCommandOutcome : uint32_t { + None = 0, Acknowledged = 1, Rejected = 2, Unknown = 3 +}; + +struct HeadJointInfo { + std::string id; + double min_position_rad{0.0}; + double max_position_rad{0.0}; + double home_position_rad{0.0}; +}; + +struct HeadJointTarget { + std::string id; + double position_rad{0.0}; +}; + +struct HeadExpressionPreset { + std::string id; + std::string name; + std::vector targets; +}; + +struct HeadJointState { + std::string id; + double target_position_rad{0.0}; + bool target_valid{false}; +}; + +struct HeadJointSnapshot { + bool connected{false}; + bool expression_baseline_ready{false}; + HeadCommandOutcome last_command_outcome{HeadCommandOutcome::None}; + std::string last_error; + // Last acknowledged command targets, never measured mechanical positions. + std::vector joints; +}; + +class AbstractJointHead : public AbstractBiohead { +public: + ~AbstractJointHead() override = default; + + virtual const std::vector& jointInfo() const = 0; + virtual HeadJointSnapshot jointState() const = 0; + virtual void moveJoints(const std::vector& targets) = 0; + virtual void home(const std::function& cancelled = {}) = 0; + virtual void setMotionMode(HeadMotionMode mode) = 0; + virtual void setMotionConstraints(const std::string& id, double velocity_rad_s, + double acceleration_rad_s2, double jerk_rad_s3) = 0; + virtual void setPositionGain(const std::string& id, double gain) = 0; + virtual void setUpdatePeriodMs(uint32_t period_ms) = 0; + virtual const std::vector& expressions() const = 0; + virtual void setExpression(const std::vector& targets, + double transition_duration_s, + const std::function& cancelled) = 0; + virtual HeadExpressionPreset playExpression(const std::string& selector, bool by_name, + double transition_duration_s, + const std::function& cancelled) = 0; + virtual void reconnect() = 0; + // Stops future host frames only; this is not a firmware or hardware stop. + virtual void cancelExpression() noexcept = 0; + + void getState(RobotState&) override { unsupported("measured joint state"); } + void eStop() override { unsupported("hardware emergency stop"); } + void setExpressionPose(FacialExpressionState&, double = 0, double = 0) override + { unsupported("legacy normalized facial expression"); } + void streamFacialPose(FacialExpressionState&, double, double) override + { unsupported("legacy normalized expression stream"); } + void speakstart() override { unsupported("SpeakStart"); } + void speakstop() override { unsupported("SpeakStop"); } + void expressionHappy() override { unsupported("Happy"); } + void expressionSurprised() override { unsupported("Surprise"); } + void expressionTired() override { unsupported("ExpressionTired"); } + void expressionAngry() override { unsupported("ExpressionAngry"); } + void expressionSadness() override { unsupported("ExpressionSadness"); } + void expressionYawn() override { unsupported("ExpressionYawn"); } + +private: + [[noreturn]] static void unsupported(const char* operation) + { + throw std::runtime_error(std::string("Joint head does not support ") + operation); + } +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_ABSTRACT_JOINT_HEAD_H diff --git a/cmvr-es/devices/biohead/biohead_factory.h b/cmvr-es/devices/biohead/biohead_factory.h new file mode 100644 index 00000000..d42e04b8 --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_factory.h @@ -0,0 +1,24 @@ +#ifndef CMVR_ES_BIOHEAD_FACTORY_H +#define CMVR_ES_BIOHEAD_FACTORY_H + +#include + +#include "cmvr/config/biohead_config/biohead_config.pb.h" +#include "abstract_biohead.h" +#include "biohead_esp32/include/biohead_esp32.h" +#include "biohead_usb/include/usb_biohead.h" + +namespace cmvr::device { + +class BioHeadFactory { +public: + static std::shared_ptr create(const config::BioHeadRobotConfig& config) + { + if (config.has_usb_erpc()) return std::make_shared(config); + return std::make_shared(config); + } +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_BIOHEAD_FACTORY_H diff --git a/cmvr-es/devices/biohead/biohead_usb/CMakeLists.txt b/cmvr-es/devices/biohead/biohead_usb/CMakeLists.txt new file mode 100644 index 00000000..d0afd0d0 --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_usb/CMakeLists.txt @@ -0,0 +1,84 @@ +option(CMVR_HEAD_BUILD_TESTING "Build head-only offline tests" OFF) + +set(CMVR_HEAD_ERPC_ROOT + "${PROJECT_SOURCE_DIR}/dependency/${ARCH}/third_party/erpc/v1.14.0" + CACHE PATH "Official eRPC 1.14.0 SDK prefix") + +foreach(required lib/liberpc.a include/erpc/erpc_version.h) + if(NOT EXISTS "${CMVR_HEAD_ERPC_ROOT}/${required}") + message(FATAL_ERROR + "Missing eRPC SDK file: ${CMVR_HEAD_ERPC_ROOT}/${required}") + endif() +endforeach() + +find_package(Threads REQUIRED) + +add_library(cmvr_head_erpc_sdk STATIC IMPORTED) + +set_target_properties(cmvr_head_erpc_sdk PROPERTIES + IMPORTED_LOCATION "${CMVR_HEAD_ERPC_ROOT}/lib/liberpc.a" + INTERFACE_INCLUDE_DIRECTORIES "${CMVR_HEAD_ERPC_ROOT}/include/erpc" + INTERFACE_LINK_LIBRARIES Threads::Threads) + +add_library(head_usb SHARED + src/usb_head_erpc_client.cpp + src/usb_head_serial_transport.cpp + src/usb_biohead.cpp) + +target_include_directories(head_usb + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) + +target_link_libraries(head_usb PRIVATE + cmvr_es::hardware + cmvr_es::proto + cmvr_es::logging + cmvr_head_erpc_sdk) + +add_library(cmvr::device::head_usb ALIAS head_usb) + +install(TARGETS head_usb LIBRARY DESTINATION lib) + +if(BUILD_TESTING OR CMVR_HEAD_BUILD_TESTING) + enable_testing() + + add_executable(usb_head_erpc_client_test + tests/usb_head_erpc_client_test.cpp) + + target_link_libraries(usb_head_erpc_client_test PRIVATE + cmvr::device::head_usb pthread) + + add_test( + NAME usb_head_erpc_client_test + COMMAND usb_head_erpc_client_test) + + add_executable(usb_head_serial_transport_test + tests/usb_head_serial_transport_test.cpp) + + target_link_libraries(usb_head_serial_transport_test PRIVATE + cmvr::device::head_usb pthread) + + add_test( + NAME usb_head_serial_transport_test + COMMAND usb_head_serial_transport_test) + + add_executable(usb_biohead_test + tests/usb_biohead_test.cpp) + + target_link_libraries(usb_biohead_test PRIVATE + cmvr::device::head_usb + cmvr_es::proto + gtest + gtest_main + pthread) + + add_test( + NAME usb_biohead_test + COMMAND usb_biohead_test) + + set_tests_properties( + usb_head_erpc_client_test + usb_head_serial_transport_test + usb_biohead_test + PROPERTIES ENVIRONMENT + "LD_LIBRARY_PATH=${CMAKE_BINARY_DIR}:${CMAKE_SOURCE_DIR}/output/lib:${CMAKE_SOURCE_DIR}/dependency/${ARCH}/third_party/grpc/v1.76.0/lib") +endif() \ No newline at end of file diff --git a/cmvr-es/devices/biohead/biohead_usb/README.txt b/cmvr-es/devices/biohead/biohead_usb/README.txt new file mode 100644 index 00000000..39b72601 --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_usb/README.txt @@ -0,0 +1,100 @@ +USB 头部设备与表情 gRPC +===================== + +本模块沿用 cmvr_es 的 BioHeadService、DeviceManager、设备工厂、配置、日志和控制仲裁。 +USB eRPC 与 Linux 串口实现均位于本头部目录,不修改公共 hardware 实现。 + +数据来源 +-------- +六个预设来自上位机 data/usb_cdc/expressions.json 的冻结快照: +中立、微笑、疲倦、惊讶、生气、当前姿态。 +SHA256: 419d7dd7f8dcbd8da49708eade3efeedf3d739dfceb75479be36e9464602093f +完整 UUID、中文名称和原始 double 保存在 include/head_expression_presets.h。 +“当前姿态”是一个已保存预设名称,不是实时机械测量。 + +通道映射与单位 +-------------- +G1H1 / 鼻子嘴角 -> eye_l_up +G1H2 / 眼球左右 -> eye_l_lower +G1H3 / 眼皮上下 -> eye_l_v +G1H4 / 眼球上下 -> eye_l_h +G3H1 / 嘴巴 -> pwm8_local +所有位置单位 rad;速度 rad/s,加速度 rad/s^2,jerk rad/s^3,更新周期 ms。 + +启动、离线与恢复 +---------------- +设备 ID 为 usb_head;配置位于 devices/biohead/bio_head_usb.pb.txt。 +串口使用 /dev/serial/by-id/usb-CherryUSB_RTT_CDC_ACM_FS_000000000001-if00。 +init 只进行空 move([]) 协议探测,预期返回 -22;不自动下发位置或 home。 +配置有效但连接失败时仍注册离线设备,可以查询预设和错误信息。 +start 不自动重试;使用 reconnect 显式恢复,重连会清除表情起始基线。 +同一串口须由一个控制程序独占;TIOCEXCL 不能撤销此前已经打开的 GUI 句柄。 +运行 cmvr_es 的账户需要对该 tty 设备具有读写权限。 + +gRPC 方法(服务名 cmvr.api.BioHeadService) +---------------------------------------- +1. GetHeadJointState:查询连接、错误、最近 ACK 目标、6 个预设与能力标记。 +2. ControlHeadJoints:单路/批量目标、模式、约束、增益、周期、home、重连、主机取消。 +3. SetHeadExpression:调用方提供完整五路目标和 0.2~5.0 秒过渡时间。 +4. PlayHeadExpression:按预设 ID 或名称调用,明确提供 0.2~5.0 秒过渡时间。 + +状态请求: +{"header":{"device_id":"usb_head"}} + +显式重连(无位置动作): +{"header":{"device_id":"usb_head"},"reconnect":{}} + +建立表情基线(会将五路移动到配置原位,必须由调用方明确执行): +{"header":{"device_id":"usb_head"},"home":{}} + +调用预设微笑: +{"header":{"device_id":"usb_head"},"expression_name":"微笑","transition_duration_s":0.4} + +自定义五路表情示例(会产生动作,请按实际标定设置): +{ + "header":{"device_id":"usb_head"}, + "targets":[ + {"id":"eye_l_up","position_rad":0.0}, + {"id":"eye_l_lower","position_rad":0.0}, + {"id":"eye_l_v","position_rad":0.0}, + {"id":"eye_l_h","position_rad":0.0}, + {"id":"pwm8_local","position_rad":-1.0} + ], + "transition_duration_s":0.4 +} + +请求停止后续主机表情帧: +{"header":{"device_id":"usb_head"},"cancel_expression":{}} + +执行语义 +-------- +表情以本次连接中已获得 ACK 的完整五路 Immediate 目标作为起点。 +home 会显式设置 Immediate、20 ms 周期,再发送完整五路原位;启动不会自动 home。 +过渡使用 20 ms、五次 minimum-jerk,先验证全部帧,慢 ACK 后跳过过期中间帧。 +正常成功必须收到实际发送各帧的 ACK,包括最终目标帧;不表示机械实际到位。 +上下文取消/deadline、主机 cancel、stop 会阻止后续帧;已经发送的板端动作不能撤销。 +取消、断线、未知或失败结果会清除基线;没有基线时表情 RPC 明确失败,不猜测起始位置。 +模式、周期属于设备全局参数;一次请求内完整操作互斥,忙时拒绝,不在锁后排队晚发动作。 + +旧快捷 Happy/Surprise/ExpressionTired/ExpressionAngry 分别调用微笑/惊讶/疲倦/生气, +使用 0.6 秒默认过渡并经过同一执行器、取消检查和基线检查。 +旧归一化 SetExpression/StreamExpression 与这套五路 rad 语义不同,USB 后端明确拒绝。 +没有来源参数的 Sadness/Yawn 不回退为其他表情。 + +停止与反馈边界 +-------------- +服务 1 没有位置测量或硬件停止/急停命令。 +connected 只表示串口句柄状态,target_valid 表示缓存目标有效,不代表机械测量。 +EmergencyStop 对 USB 会请求停止后续主机帧,但明确报告不支持硬件急停。 +stop 关闭本头部连接并返回 false,表示无法确认硬件已停止。 +公共 SystemService/StopAll 保持原项目实现,没有在本次修改中改变;不能据其通用成功标志 +推断本头部已完成硬件急停,应使用头部能力标记和独立的物理安全机制。 + +构建与离线测试 +-------------- +启用头部专用选项 CMVR_HEAD_BUILD_TESTING=ON,无需开启其他模块的 BUILD_TESTING。 +构建目标:cmvr_es、usb_head_erpc_client_test、usb_head_serial_transport_test、 +usb_biohead_test、grpc_head_joint_service_test。 +三个设备测试位于构建目录 cmvr-es/devices/biohead/biohead_usb; +真实 loopback gRPC 测试位于构建目录 cmvr-es/service,仅使用 mock 设备。 +所有自动化测试均不执行真实舵机运动。 diff --git a/cmvr-es/devices/biohead/biohead_usb/include/head_expression_presets.h b/cmvr-es/devices/biohead/biohead_usb/include/head_expression_presets.h new file mode 100644 index 00000000..a4e77755 --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_usb/include/head_expression_presets.h @@ -0,0 +1,62 @@ +#ifndef CMVR_ES_HEAD_EXPRESSION_PRESETS_H +#define CMVR_ES_HEAD_EXPRESSION_PRESETS_H + +#include "devices/biohead/abstract_joint_head.h" + +namespace cmvr::device { + +// Frozen cmvr-head-client expressions.json; do not substitute package defaults. +// SHA256: 419d7dd7f8dcbd8da49708eade3efeedf3d739dfceb75479be36e9464602093f +// updated_at: 2026-11-10T10:15:47+08:00 +inline const std::vector& headExpressionPresets() +{ + static const std::vector presets{ + {"0de8a527543e423abab593484926dd1c", u8"中立", { + {"eye_l_up", 0.0}, + {"eye_l_lower", 0.0}, + {"eye_l_v", 0.0}, + {"eye_l_h", 0.0}, + {"pwm8_local", -1.0}, + }}, + {"ad8f669a78d54d30a2356512b0802c1d", u8"微笑", { + {"eye_l_up", 0.2329999953508377}, + {"eye_l_lower", -0.00041940261144191027}, + {"eye_l_v", -0.00041940261144191027}, + {"eye_l_h", -0.00041940261144191027}, + {"pwm8_local", -1.121000051498413}, + }}, + {"516bc0f0e76647109411cbf92e5c86fc", u8"疲倦", { + {"eye_l_up", -0.991}, + {"eye_l_lower", 0.322}, + {"eye_l_v", -1.015}, + {"eye_l_h", 0.004}, + {"pwm8_local", -0.537}, + }}, + {"5e68f9b26f4d4f8580dead7777c6501b", u8"惊讶", { + {"eye_l_up", -1.0}, + {"eye_l_lower", -0.0004194026121000505}, + {"eye_l_v", 0.999890384765}, + {"eye_l_h", -0.0004194026121000505}, + {"pwm8_local", -0.0004194026121000505}, + }}, + {"44821d9fa6df4fc78558666db32656e1", u8"生气", { + {"eye_l_up", -1.0}, + {"eye_l_lower", 0.5497252979258}, + {"eye_l_v", 0.999890384765}, + {"eye_l_h", 0.6999468312800001}, + {"pwm8_local", -1.400129282005}, + }}, + {"8f97ed10b5b44012b004183ba61c839c", u8"当前姿态", { + {"eye_l_up", -0.0004194026121000505}, + {"eye_l_lower", -0.0004194026121000505}, + {"eye_l_v", -0.0004194026121000505}, + {"eye_l_h", -0.65}, + {"pwm8_local", -1.0}, + }}, + }; + return presets; +} + +} // namespace cmvr::device + +#endif // CMVR_ES_HEAD_EXPRESSION_PRESETS_H diff --git a/cmvr-es/devices/biohead/biohead_usb/include/usb_biohead.h b/cmvr-es/devices/biohead/biohead_usb/include/usb_biohead.h new file mode 100644 index 00000000..dabe471f --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_usb/include/usb_biohead.h @@ -0,0 +1,87 @@ +#ifndef CMVR_ES_USB_BIOHEAD_H +#define CMVR_ES_USB_BIOHEAD_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cmvr/config/biohead_config/biohead_config.pb.h" +#include "devices/biohead/abstract_joint_head.h" +#include "usb_head_erpc_client.h" + +namespace cmvr::device { + +class UsbBioHead final : public AbstractJointHead { +public: + explicit UsbBioHead(const config::BioHeadRobotConfig& config); + UsbBioHead(const config::BioHeadRobotConfig& config, + std::unique_ptr<::cmvr::AbstractSerialTransport> transport); + ~UsbBioHead() override; + + std::string typeName() const override { return "UsbBioHead"; } + // Configuration was validated by construction. init() makes one no-target + // connection attempt but returns true even offline so DeviceManager keeps + // this device registered. Query connected/last_error for hardware readiness. + bool init() override; + // Lifecycle activation never implicitly reconnects or sends motion targets. + bool start() override; + // Closes host transport. Returns false because firmware cannot confirm a stop. + bool stop() override; + + const std::vector& jointInfo() const override; + HeadJointSnapshot jointState() const override; + void moveJoints(const std::vector& targets) override; + void home(const std::function& cancelled = {}) override; + void setMotionMode(HeadMotionMode mode) override; + void setMotionConstraints(const std::string& id, double velocity_rad_s, + double acceleration_rad_s2, double jerk_rad_s3) override; + void setPositionGain(const std::string& id, double gain) override; + void setUpdatePeriodMs(uint32_t period_ms) override; + const std::vector& expressions() const override; + void setExpression(const std::vector& targets, double transition_duration_s, + const std::function& cancelled) override; + HeadExpressionPreset playExpression(const std::string& selector, bool by_name, + double transition_duration_s, + const std::function& cancelled) override; + void reconnect() override; + void cancelExpression() noexcept override; + void eStop() override; + void expressionHappy() override; + void expressionSurprised() override; + void expressionTired() override; + void expressionAngry() override; + +private: + std::unique_lock lockCommand(); + size_t indexOf(const std::string& id) const; + float checkedPosition(const HeadJointInfo& joint, double position_rad) const; + void executeLocked(const char* operation, const std::function& execute); + void invalidateTargetsLocked(); + void connectLocked(); + bool expressionReadyLocked() const; + using EncodedTargets = std::vector>; + EncodedTargets encodeTargetsLocked(const std::vector& targets, + bool complete) const; + void rememberTargetsLocked(const EncodedTargets& targets); + void checkCancelled(uint64_t generation, const std::function& cancelled) const; + + std::string port_name_; + int baud_rate_{115200}; + std::vector joints_; + std::unordered_map joint_index_; + mutable std::mutex operation_mutex_; + UsbHeadErpcClient client_; + HeadJointSnapshot snapshot_; + std::vector immediate_targets_; + std::optional motion_mode_; + std::atomic cancel_generation_{0}; +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_USB_BIOHEAD_H diff --git a/cmvr-es/devices/biohead/biohead_usb/include/usb_head_erpc_client.h b/cmvr-es/devices/biohead/biohead_usb/include/usb_head_erpc_client.h new file mode 100644 index 00000000..af590f36 --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_usb/include/usb_head_erpc_client.h @@ -0,0 +1,71 @@ +#ifndef CMVR_ES_USB_HEAD_ERPC_CLIENT_H +#define CMVR_ES_USB_HEAD_ERPC_CLIENT_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "hardware/include/abstract_serial_transport.h" + +namespace cmvr::device { + + class UsbHeadErpcClient final { + public: + using Target = std::pair; + + explicit UsbHeadErpcClient( + std::unique_ptr<::cmvr::AbstractSerialTransport> serial, + std::chrono::milliseconds timeout = + std::chrono::milliseconds(2000)); + + UsbHeadErpcClient( + std::unique_ptr<::cmvr::AbstractSerialTransport> serial, + std::chrono::milliseconds timeout, + std::uint32_t sequence_seed); + + ~UsbHeadErpcClient(); + + UsbHeadErpcClient(const UsbHeadErpcClient&) = delete; + + UsbHeadErpcClient& operator=( + const UsbHeadErpcClient&) = delete; + + void open( + const std::string& port_name, + int baud_rate = 115200); + + void close(); + + bool isOpen() const; + + bool setConstraints( + const std::string& id, + float velocity_rad_s, + float acceleration_rad_s2, + float jerk_rad_s3); + + bool setPositionGain( + const std::string& id, + float gain); + + bool setMode(std::int32_t mode); + + bool setUpdatePeriodMs(std::uint32_t period_ms); + + std::int32_t move(const std::vector& targets); + + std::int32_t moveJ(const std::vector& angles_rad); + + private: + struct Impl; + std::unique_ptr impl_; + }; + +} // namespace cmvr::device + +#endif // CMVR_ES_USB_HEAD_ERPC_CLIENT_H \ No newline at end of file diff --git a/cmvr-es/devices/biohead/biohead_usb/include/usb_head_serial_transport.h b/cmvr-es/devices/biohead/biohead_usb/include/usb_head_serial_transport.h new file mode 100644 index 00000000..6429ba6f --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_usb/include/usb_head_serial_transport.h @@ -0,0 +1,47 @@ +#ifndef CMVR_ES_USB_HEAD_SERIAL_TRANSPORT_H +#define CMVR_ES_USB_HEAD_SERIAL_TRANSPORT_H + +#include +#include +#include + +#include "hardware/include/abstract_serial_transport.h" + +namespace cmvr::device { + +// Head-local Linux transport. It does not change the shared serial interface or +// the behavior of other device drivers. Only the configured port is opened. +class UsbHeadSerialTransport final : public ::cmvr::AbstractSerialTransport { +public: + explicit UsbHeadSerialTransport( + std::chrono::milliseconds io_timeout = std::chrono::milliseconds(2000)); + ~UsbHeadSerialTransport() override; + + bool open(const Config& config) override; + bool close() noexcept override; + bool isOpen() const override; + bool flushInput() override; + bool write(const std::vector& data) override; + // The smaller of timeout and the constructor's I/O budget is used. One + // fixed deadline covers all fragments and interrupted poll/read calls. + bool read(std::size_t min_size, std::chrono::milliseconds timeout, + std::vector& out_buffer) override; + std::string lastError() const override; + +private: + using Clock = std::chrono::steady_clock; + + bool closeUnlocked() noexcept; + bool waitReady(short events, Clock::time_point deadline); + void setSystemError(const char* operation, int error_number); + + const std::chrono::milliseconds io_timeout_; + int fd_{-1}; + bool exclusive_{false}; + std::string last_error_; + mutable std::mutex io_mutex_; +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_USB_HEAD_SERIAL_TRANSPORT_H diff --git a/cmvr-es/devices/biohead/biohead_usb/src/usb_biohead.cpp b/cmvr-es/devices/biohead/biohead_usb/src/usb_biohead.cpp new file mode 100644 index 00000000..2ff406f8 --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_usb/src/usb_biohead.cpp @@ -0,0 +1,485 @@ +#include "../include/usb_biohead.h" +#include "../include/head_expression_presets.h" +#include "../include/usb_head_serial_transport.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "common/base/logging/logger.h" + +namespace cmvr::device { +namespace { + +class ExpressionCancelled final : public std::runtime_error { +public: + ExpressionCancelled() : std::runtime_error( + "Expression cancelled; future host frames stopped, not a hardware emergency stop") {} +}; + +std::chrono::milliseconds responseTimeout(const config::BioHeadRobotConfig& config) +{ + const auto timeout = config.usb_erpc().response_timeout_ms(); + if (timeout > 30000) { + throw std::invalid_argument("USB head response_timeout_ms must be <= 30000"); + } + return std::chrono::milliseconds(timeout == 0 ? 2000 : timeout); +} + +float positiveFloat(double value, const char* name) +{ + const float encoded = static_cast(value); + if (!std::isfinite(value) || value <= 0 || !std::isfinite(encoded) || encoded <= 0) { + throw std::invalid_argument(std::string(name) + " must be a positive finite float32"); + } + return encoded; +} + +} // namespace + +UsbBioHead::UsbBioHead(const config::BioHeadRobotConfig& config) + : UsbBioHead(config, std::make_unique(responseTimeout(config))) {} + +UsbBioHead::UsbBioHead(const config::BioHeadRobotConfig& config, + std::unique_ptr<::cmvr::AbstractSerialTransport> transport) + : port_name_(config.serial_port()), + baud_rate_(config.baud_rate() == 0 ? 115200 : config.baud_rate()), + client_(std::move(transport), responseTimeout(config)) +{ + id_ = config.id(); + if (id_.empty() || port_name_.empty() || baud_rate_ <= 0 || !config.has_usb_erpc()) { + throw std::invalid_argument("USB head requires id, serial_port, baud_rate and usb_erpc"); + } + if (!config.servo_groups().empty()) { + throw std::invalid_argument("USB head cannot use legacy ESP32 servo_groups"); + } + if (config.usb_erpc().joints_size() < 1 || config.usb_erpc().joints_size() > 5) { + throw std::invalid_argument("USB eRPC service 1 requires 1..5 configured joints"); + } + for (const auto& cfg : config.usb_erpc().joints()) { + HeadJointInfo joint{cfg.id(), cfg.min_position_rad(), cfg.max_position_rad(), + cfg.home_position_rad()}; + if (joint.id.empty() || joint.id.size() > 64 || joint.id.find('\0') != std::string::npos + || joint_index_.count(joint.id) + || !std::isfinite(joint.min_position_rad) + || !std::isfinite(joint.max_position_rad) + || joint.min_position_rad >= joint.max_position_rad + || joint.min_position_rad < -1.5707963 || joint.max_position_rad > 1.5707963) { + throw std::invalid_argument("Invalid or duplicate USB head joint: " + joint.id); + } + checkedPosition(joint, joint.home_position_rad); + joint_index_.emplace(joint.id, joints_.size()); + joints_.push_back(joint); + snapshot_.joints.push_back({joint.id, 0.0, false}); + immediate_targets_.push_back(false); + } +} + +UsbBioHead::~UsbBioHead() +{ + try { client_.close(); } catch (...) {} +} + +bool UsbBioHead::init() +{ + std::lock_guard lock(operation_mutex_); + if (client_.isOpen()) return true; + try { + connectLocked(); + return true; + } catch (const std::exception& error) { + try { client_.close(); } catch (...) {} + snapshot_.last_command_outcome = HeadCommandOutcome::Unknown; + snapshot_.last_error = error.what(); + CMVR_LOG(WARNING) << "[UsbBioHead] (init): registered offline; explicit reconnect required: " + << error.what() << ", id=" << id_; + // Keep the strictly validated device available for queries and an + // explicit reconnect RPC after hot-plug or external permission repair. + // This is object initialization success, not hardware readiness. + return true; + } +} + +void UsbBioHead::connectLocked() +{ + invalidateTargetsLocked(); + try { + client_.open(port_name_, baud_rate_); + if (client_.move({}) != -22) { + throw std::runtime_error("Unexpected USB eRPC service-1 no-target probe result"); + } + snapshot_.last_command_outcome = HeadCommandOutcome::None; + snapshot_.last_error.clear(); + CMVR_LOG(INFO) << "[UsbBioHead] (connect): connected without motion, id=" << id_; + } catch (const std::exception& error) { + try { client_.close(); } catch (...) {} + snapshot_.last_command_outcome = HeadCommandOutcome::Unknown; + snapshot_.last_error = error.what(); + throw; + } +} + +void UsbBioHead::reconnect() +{ + cancelExpression(); + auto lock = lockCommand(); + invalidateTargetsLocked(); + try { + client_.close(); + connectLocked(); + } catch (const std::exception& error) { + snapshot_.last_command_outcome = HeadCommandOutcome::Unknown; + snapshot_.last_error = error.what(); + throw; + } +} + +bool UsbBioHead::start() { return true; } + +bool UsbBioHead::stop() +{ + cancelExpression(); + std::lock_guard lock(operation_mutex_); + try { client_.close(); } catch (...) {} + invalidateTargetsLocked(); + snapshot_.last_command_outcome = HeadCommandOutcome::Unknown; + snapshot_.last_error = "Host link closed; eRPC service 1 has no device-side stop command"; + CMVR_LOG(WARNING) << "[UsbBioHead] (stop): " << snapshot_.last_error << ", id=" << id_; + return false; +} + +const std::vector& UsbBioHead::jointInfo() const { return joints_; } + +HeadJointSnapshot UsbBioHead::jointState() const +{ + std::unique_lock lock(operation_mutex_, std::try_to_lock); + if (!lock.owns_lock()) throw std::runtime_error("USB head is busy; retry state query"); + auto result = snapshot_; + result.connected = client_.isOpen(); + result.expression_baseline_ready = result.connected && expressionReadyLocked(); + return result; +} + +std::unique_lock UsbBioHead::lockCommand() +{ + std::unique_lock lock(operation_mutex_, std::try_to_lock); + if (!lock.owns_lock()) throw std::runtime_error("USB head is busy; command was not sent"); + return lock; +} + +size_t UsbBioHead::indexOf(const std::string& id) const +{ + const auto it = joint_index_.find(id); + if (it == joint_index_.end()) throw std::invalid_argument("Unknown head joint: " + id); + return it->second; +} + +float UsbBioHead::checkedPosition(const HeadJointInfo& joint, double position_rad) const +{ + if (!std::isfinite(position_rad) || position_rad < joint.min_position_rad + || position_rad > joint.max_position_rad) { + throw std::invalid_argument("Position outside configured limits: " + joint.id); + } + float encoded = static_cast(position_rad); + if (!std::isfinite(encoded) || (position_rad != 0 && encoded == 0)) { + throw std::invalid_argument("Position is not representable as a non-underflowing float32"); + } + // Quantize boundary values inward by one ULP instead of crossing a soft limit. + if (encoded < joint.min_position_rad) { + encoded = std::nextafter(encoded, std::numeric_limits::infinity()); + } + if (encoded > joint.max_position_rad) { + encoded = std::nextafter(encoded, -std::numeric_limits::infinity()); + } + if (!std::isfinite(encoded) || encoded < joint.min_position_rad + || encoded > joint.max_position_rad) { + throw std::invalid_argument("Joint limits contain no usable float32 target: " + joint.id); + } + return encoded; +} + +void UsbBioHead::executeLocked(const char* operation, + const std::function& execute) +{ + if (!client_.isOpen()) throw std::runtime_error("USB head is disconnected; command not sent"); + int32_t result; + try { + result = execute(); + } catch (const std::exception& error) { + try { client_.close(); } catch (...) {} + invalidateTargetsLocked(); + snapshot_.last_command_outcome = HeadCommandOutcome::Unknown; + snapshot_.last_error = std::string(operation) + ": result unknown: " + error.what(); + throw std::runtime_error(snapshot_.last_error); + } + if (result != 0) { + invalidateTargetsLocked(); + snapshot_.last_command_outcome = HeadCommandOutcome::Rejected; + snapshot_.last_error = std::string(operation) + ": firmware rejected, result=" + + std::to_string(result) + "; partial execution is possible"; + throw std::runtime_error(snapshot_.last_error); + } + snapshot_.last_command_outcome = HeadCommandOutcome::Acknowledged; + snapshot_.last_error.clear(); +} + +void UsbBioHead::invalidateTargetsLocked() +{ + for (auto& state : snapshot_.joints) state.target_valid = false; + std::fill(immediate_targets_.begin(), immediate_targets_.end(), false); + motion_mode_.reset(); + snapshot_.expression_baseline_ready = false; +} + +UsbBioHead::EncodedTargets UsbBioHead::encodeTargetsLocked( + const std::vector& targets, bool complete) const +{ + if (targets.empty() || targets.size() > joints_.size()) { + throw std::invalid_argument("Expected a nonempty subset of configured joints"); + } + std::set selected; + std::vector> encoded; + encoded.reserve(targets.size()); + for (const auto& target : targets) { + const auto index = indexOf(target.id); + if (!selected.insert(index).second) throw std::invalid_argument("Duplicate joint: " + target.id); + encoded.emplace_back(target.id, checkedPosition(joints_[index], target.position_rad)); + } + if (complete && (joints_.size() != 5 || selected.size() != 5)) { + throw std::invalid_argument("Timed expression requires all five configured joints"); + } + return encoded; +} + +void UsbBioHead::rememberTargetsLocked(const EncodedTargets& encoded) +{ + for (const auto& target : encoded) { + const auto index = indexOf(target.first); + auto& state = snapshot_.joints[index]; + state.target_position_rad = target.second; + state.target_valid = true; + immediate_targets_[index] = motion_mode_ && *motion_mode_ == HeadMotionMode::Immediate; + } +} + +void UsbBioHead::moveJoints(const std::vector& targets) +{ + auto lock = lockCommand(); + const auto encoded = encodeTargetsLocked(targets, false); + executeLocked("move", [&] { return client_.move(encoded); }); + rememberTargetsLocked(encoded); +} + +void UsbBioHead::home(const std::function& cancelled) +{ + auto lock = lockCommand(); + const auto generation = cancel_generation_.load(); + std::vector targets; + for (const auto& joint : joints_) targets.push_back({joint.id, joint.home_position_rad}); + const auto encoded = encodeTargetsLocked(targets, false); + try { + checkCancelled(generation, cancelled); + executeLocked("home.setMode", [&] { return client_.setMode(0) ? 0 : -1; }); + motion_mode_ = HeadMotionMode::Immediate; + checkCancelled(generation, cancelled); + executeLocked("home.setUpdatePeriodMs", [&] { return client_.setUpdatePeriodMs(20) ? 0 : -1; }); + checkCancelled(generation, cancelled); + executeLocked("home.move", [&] { return client_.move(encoded); }); + rememberTargetsLocked(encoded); + checkCancelled(generation, cancelled); + } catch (const ExpressionCancelled& error) { + invalidateTargetsLocked(); + snapshot_.last_command_outcome = HeadCommandOutcome::Unknown; + snapshot_.last_error = error.what(); + throw; + } +} + +void UsbBioHead::setMotionMode(HeadMotionMode mode) +{ + auto lock = lockCommand(); + const auto value = static_cast(mode); + if (value < 0 || value > 2) throw std::invalid_argument("Unsupported head motion mode"); + executeLocked("setMode", [&] { return client_.setMode(value) ? 0 : -1; }); + if (mode != HeadMotionMode::Immediate) invalidateTargetsLocked(); + motion_mode_ = mode; +} + +void UsbBioHead::setMotionConstraints(const std::string& id, double velocity_rad_s, + double acceleration_rad_s2, double jerk_rad_s3) +{ + auto lock = lockCommand(); + indexOf(id); + const auto velocity = positiveFloat(velocity_rad_s, "velocity_rad_s"); + const auto acceleration = positiveFloat(acceleration_rad_s2, "acceleration_rad_s2"); + const auto jerk = positiveFloat(jerk_rad_s3, "jerk_rad_s3"); + executeLocked("setConstraints", [&] { + return client_.setConstraints(id, velocity, acceleration, jerk) ? 0 : -1; + }); +} + +void UsbBioHead::setPositionGain(const std::string& id, double gain) +{ + auto lock = lockCommand(); + indexOf(id); + const auto encoded = static_cast(gain); + if (!std::isfinite(gain) || gain < 0 || !std::isfinite(encoded) + || (gain != 0 && encoded == 0)) { + throw std::invalid_argument("position_gain must be a nonnegative finite float32"); + } + executeLocked("setPositionGain", [&] { return client_.setPositionGain(id, encoded) ? 0 : -1; }); +} + +void UsbBioHead::setUpdatePeriodMs(uint32_t period_ms) +{ + auto lock = lockCommand(); + if (period_ms == 0 || period_ms > 100) { + throw std::invalid_argument("update period must be in [1, 100] ms"); + } + executeLocked("setUpdatePeriodMs", [&] { return client_.setUpdatePeriodMs(period_ms) ? 0 : -1; }); +} + +bool UsbBioHead::expressionReadyLocked() const +{ + if (!motion_mode_ || *motion_mode_ != HeadMotionMode::Immediate || joints_.size() != 5) return false; + for (const char* id : {"eye_l_up", "eye_l_lower", "eye_l_v", "eye_l_h", "pwm8_local"}) { + const auto found = joint_index_.find(id); + if (found == joint_index_.end() || !snapshot_.joints[found->second].target_valid + || !immediate_targets_[found->second]) return false; + } + return true; +} + +const std::vector& UsbBioHead::expressions() const +{ + return headExpressionPresets(); +} + +void UsbBioHead::cancelExpression() noexcept { cancel_generation_.fetch_add(1); } + +void UsbBioHead::eStop() +{ + cancelExpression(); + throw std::runtime_error("Future host expression frames cancelled; eRPC service 1 has no hardware emergency stop"); +} + +void UsbBioHead::checkCancelled(uint64_t generation, const std::function& cancelled) const +{ + if (cancel_generation_.load() != generation || (cancelled && cancelled())) throw ExpressionCancelled(); +} + +void UsbBioHead::setExpression(const std::vector& targets, double duration_s, + const std::function& cancelled) +{ + auto lock = lockCommand(); + const auto generation = cancel_generation_.load(); + bool changed_settings = false; + try { + checkCancelled(generation, cancelled); + if (!std::isfinite(duration_s) || duration_s < 0.2 || duration_s > 5.0) { + throw std::invalid_argument("Expression duration must be finite and in [0.2, 5] seconds"); + } + const auto destination = encodeTargetsLocked(targets, true); + if (!client_.isOpen() || !expressionReadyLocked()) { + throw std::runtime_error("Expression requires a full five-joint Immediate ACK baseline; call home first"); + } + const auto count = static_cast(std::ceil(duration_s * 1000.0 / 20.0)); + std::vector frames; + frames.reserve(count); + // Validate and encode every frame before changing any firmware settings. + for (size_t frame_index = 1; frame_index <= count; ++frame_index) { + checkCancelled(generation, cancelled); + const double progress = static_cast(frame_index) / static_cast(count); + const double blend = progress * progress * progress * (10.0 + progress * (-15.0 + 6.0 * progress)); + EncodedTargets frame; + frame.reserve(destination.size()); + for (const auto& target : destination) { + const auto joint_index = indexOf(target.first); + const double start = snapshot_.joints[joint_index].target_position_rad; + const double end = target.second; + const double value = frame_index == count ? end : start + (end - start) * blend; + frame.emplace_back(target.first, checkedPosition(joints_[joint_index], value)); + } + frames.push_back(std::move(frame)); + } + checkCancelled(generation, cancelled); + changed_settings = true; + executeLocked("expression.setMode", [&] { return client_.setMode(0) ? 0 : -1; }); + motion_mode_ = HeadMotionMode::Immediate; + checkCancelled(generation, cancelled); + executeLocked("expression.setUpdatePeriodMs", [&] { return client_.setUpdatePeriodMs(20) ? 0 : -1; }); + using Clock = std::chrono::steady_clock; + const auto started = Clock::now(); + size_t index = 1; + while (index <= count) { + checkCancelled(generation, cancelled); + const auto due = started + std::chrono::duration_cast( + std::chrono::duration(duration_s * static_cast(index) / count)); + while (Clock::now() < due) { + checkCancelled(generation, cancelled); + std::this_thread::sleep_for(std::min(due - Clock::now(), + std::chrono::duration_cast(std::chrono::milliseconds(5)))); + } + checkCancelled(generation, cancelled); + const auto elapsed = std::chrono::duration(Clock::now() - started).count(); + // Skip expired intermediate frames after delayed scheduling; never burst them. + const auto latest_due = static_cast(std::floor(elapsed * count / duration_s)); + index = std::min(count, std::max(index, latest_due)); + const auto& frame = frames[index - 1]; + checkCancelled(generation, cancelled); + executeLocked("expression.move", [&] { return client_.move(frame); }); + rememberTargetsLocked(frame); + checkCancelled(generation, cancelled); + if (index == count) break; // The exact final frame must receive an ACK. + const auto after_ack = std::chrono::duration(Clock::now() - started).count(); + index = std::min(count, std::max(index + 1, + static_cast(std::floor(after_ack * count / duration_s)) + 1)); + } + } catch (const ExpressionCancelled& error) { + invalidateTargetsLocked(); + snapshot_.last_command_outcome = HeadCommandOutcome::Unknown; + snapshot_.last_error = error.what(); + throw; + } catch (const std::exception& error) { + if (changed_settings) { + invalidateTargetsLocked(); + if (snapshot_.last_command_outcome != HeadCommandOutcome::Rejected + && snapshot_.last_command_outcome != HeadCommandOutcome::Unknown) { + snapshot_.last_command_outcome = HeadCommandOutcome::Unknown; + snapshot_.last_error = error.what(); + } + } + throw; + } +} + +HeadExpressionPreset UsbBioHead::playExpression(const std::string& selector, bool by_name, + double duration_s, + const std::function& cancelled) +{ + const auto& presets = expressions(); + if (selector.empty()) throw std::invalid_argument("Head expression selector must not be empty"); + const auto matches = std::count_if(presets.begin(), presets.end(), [&](const auto& preset) { + return (by_name ? preset.name : preset.id) == selector; + }); + if (matches != 1) { + throw std::invalid_argument(matches == 0 ? "Unknown head expression: " + selector + : "Ambiguous head expression: " + selector); + } + const auto found = std::find_if(presets.begin(), presets.end(), [&](const auto& preset) { + return (by_name ? preset.name : preset.id) == selector; + }); + setExpression(found->targets, duration_s, cancelled); + return *found; +} + +void UsbBioHead::expressionHappy() { playExpression(u8"微笑", true, 0.6, {}); } +void UsbBioHead::expressionSurprised() { playExpression(u8"惊讶", true, 0.6, {}); } +void UsbBioHead::expressionTired() { playExpression(u8"疲倦", true, 0.6, {}); } +void UsbBioHead::expressionAngry() { playExpression(u8"生气", true, 0.6, {}); } + +} // namespace cmvr::device diff --git a/cmvr-es/devices/biohead/biohead_usb/src/usb_head_erpc_client.cpp b/cmvr-es/devices/biohead/biohead_usb/src/usb_head_erpc_client.cpp new file mode 100644 index 00000000..04e8d3ae --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_usb/src/usb_head_erpc_client.cpp @@ -0,0 +1,914 @@ +#include "../include/usb_head_erpc_client.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "erpc_basic_codec.hpp" +#include "erpc_client_manager.h" +#include "erpc_crc16.hpp" +#include "erpc_framed_transport.hpp" +#include "erpc_version.h" + +namespace cmvr::device { +namespace { + +static_assert( + ERPC_VERSION_NUMBER == 11400, + "USB head requires eRPC 1.14.0"); + +// 将项目串口接入官方 FramedTransport。 +// 帧封装、CRC 和类型编解码由官方 SDK 处理。 +class SdkFramedSerialTransport final : public erpc::FramedTransport { +public: + using Clock = std::chrono::steady_clock; + + static constexpr std::size_t kFrameHeaderSize = 6; + static constexpr std::size_t kMaxBodySize = 4096; + + explicit SdkFramedSerialTransport( + ::cmvr::AbstractSerialTransport& serial); + + ~SdkFramedSerialTransport() override = default; + + SdkFramedSerialTransport( + const SdkFramedSerialTransport&) = delete; + + SdkFramedSerialTransport& operator=( + const SdkFramedSerialTransport&) = delete; + + void beginTransaction( + Clock::time_point deadline, + std::size_t expected_reply_body_size); + + void endTransaction() noexcept; + void reset() noexcept; + + const std::string& lastError() const noexcept + { + return last_error_; + } + + erpc_status_t send(erpc::MessageBuffer* message) override; + erpc_status_t receive(erpc::MessageBuffer* message) override; + +protected: + erpc_status_t underlyingSend( + const std::uint8_t* data, + std::uint32_t size) override; + + erpc_status_t underlyingReceive( + std::uint8_t* data, + std::uint32_t size) override; + + erpc_status_t underlyingReceive( + erpc::MessageBuffer* message, + std::uint32_t size, + std::uint32_t offset) override; + +private: + erpc_status_t checkReady(); + + erpc_status_t fail( + erpc_status_t status, + std::string message); + + erpc_status_t sdkFailure( + erpc_status_t status, + const char* operation); + + ::cmvr::AbstractSerialTransport& serial_; + + // 官方 CRC 实现,初始值与现有控制板一致。 + erpc::Crc16 crc_{0xEF4A}; + + Clock::time_point deadline_{}; + std::size_t expected_reply_body_size_{0}; + bool transaction_active_{false}; + + std::vector pending_; + std::string last_error_; +}; + +SdkFramedSerialTransport::SdkFramedSerialTransport( + ::cmvr::AbstractSerialTransport& serial) + : serial_(serial) +{ + setCrc16(&crc_); +} + +void SdkFramedSerialTransport::beginTransaction( + Clock::time_point deadline, + std::size_t expected_reply_body_size) +{ + if (transaction_active_) { + throw std::logic_error( + "An eRPC transaction is already active"); + } + + if (expected_reply_body_size < 8 + || expected_reply_body_size > kMaxBodySize) { + throw std::invalid_argument( + "Invalid expected eRPC reply body size"); + } + + if (!pending_.empty()) { + throw std::runtime_error( + "Unexpected bytes remain before eRPC request"); + } + + last_error_.clear(); + deadline_ = deadline; + expected_reply_body_size_ = expected_reply_body_size; + transaction_active_ = true; +} + +void SdkFramedSerialTransport::endTransaction() noexcept +{ + transaction_active_ = false; + deadline_ = {}; + expected_reply_body_size_ = 0; +} + +void SdkFramedSerialTransport::reset() noexcept +{ + endTransaction(); + pending_.clear(); + last_error_.clear(); +} + +erpc_status_t SdkFramedSerialTransport::fail( + erpc_status_t status, + std::string message) +{ + last_error_ = std::move(message); + return status; +} + +erpc_status_t SdkFramedSerialTransport::checkReady() +{ + if (!transaction_active_) { + return fail( + kErpcStatus_InvalidArgument, + "eRPC transaction deadline is not established"); + } + + if (Clock::now() >= deadline_) { + return fail( + kErpcStatus_Timeout, + "USB head transaction deadline exceeded"); + } + + if (!serial_.isOpen()) { + return fail( + kErpcStatus_ConnectionClosed, + "USB head serial transport is not open"); + } + + return kErpcStatus_Success; +} + +erpc_status_t SdkFramedSerialTransport::sdkFailure( + erpc_status_t status, + const char* operation) +{ + if (status != kErpcStatus_Success && last_error_.empty()) { + last_error_ = + std::string("Official eRPC ") + operation + + " failed, status=" + + std::to_string(static_cast(status)); + + if (status == kErpcStatus_CrcCheckFailed) { + last_error_ += " (frame CRC mismatch)"; + } + } + + return status; +} + +erpc_status_t SdkFramedSerialTransport::send( + erpc::MessageBuffer* message) +{ + try { + const auto ready = checkReady(); + + if (ready != kErpcStatus_Success) { + return ready; + } + + if (!message + || !message->get() + || message->getUsed() < kFrameHeaderSize + 8 + || message->getUsed() > message->getLength() + || message->getUsed() - kFrameHeaderSize > kMaxBodySize) { + return fail( + kErpcStatus_InvalidArgument, + "Invalid or oversized eRPC request buffer"); + } + + return sdkFailure( + erpc::FramedTransport::send(message), + "send"); + } catch (const std::exception& error) { + return fail( + kErpcStatus_SendFailed, + std::string("USB head send failed: ") + error.what()); + } catch (...) { + return fail( + kErpcStatus_SendFailed, + "Unknown USB head send failure"); + } +} + +erpc_status_t SdkFramedSerialTransport::receive( + erpc::MessageBuffer* message) +{ + try { + const auto ready = checkReady(); + + if (ready != kErpcStatus_Success) { + return ready; + } + + const auto required = + kFrameHeaderSize + expected_reply_body_size_; + + if (!message + || !message->get() + || message->getLength() < required) { + return fail( + kErpcStatus_MemoryError, + "eRPC reply buffer is too small"); + } + + erpc::MessageBuffer bounded( + message->get(), + static_cast(required)); + + const auto status = + erpc::FramedTransport::receive(&bounded); + + if (status != kErpcStatus_Success) { + message->setUsed(0); + return sdkFailure(status, "receive"); + } + + if (bounded.getUsed() != required) { + message->setUsed(0); + return fail( + kErpcStatus_ReceiveFailed, + "USB head reply length mismatch"); + } + + if (!pending_.empty()) { + message->setUsed(0); + return fail( + kErpcStatus_ReceiveFailed, + "USB head received unexpected trailing bytes"); + } + + const auto after_receive = checkReady(); + + if (after_receive != kErpcStatus_Success) { + message->setUsed(0); + return after_receive; + } + + message->setUsed(bounded.getUsed()); + return kErpcStatus_Success; + } catch (const std::exception& error) { + if (message) { + message->setUsed(0); + } + + return fail( + kErpcStatus_ReceiveFailed, + std::string("USB head receive failed: ") + error.what()); + } catch (...) { + if (message) { + message->setUsed(0); + } + + return fail( + kErpcStatus_ReceiveFailed, + "Unknown USB head receive failure"); + } +} + +erpc_status_t SdkFramedSerialTransport::underlyingSend( + const std::uint8_t* data, + std::uint32_t size) +{ + const auto ready = checkReady(); + + if (ready != kErpcStatus_Success) { + return ready; + } + + if (!data + || size < kFrameHeaderSize + || size > kFrameHeaderSize + kMaxBodySize) { + return fail( + kErpcStatus_InvalidArgument, + "Invalid eRPC frame write size"); + } + + const std::vector bytes(data, data + size); + + if (!serial_.write(bytes)) { + return fail( + Clock::now() >= deadline_ + ? kErpcStatus_Timeout + : kErpcStatus_SendFailed, + "USB head write failed: " + serial_.lastError()); + } + + return checkReady(); +} + +erpc_status_t SdkFramedSerialTransport::underlyingReceive( + erpc::MessageBuffer* message, + std::uint32_t size, + std::uint32_t offset) +{ + if (!message + || !message->get() + || offset > message->getLength() + || size > message->getLength() - offset) { + return fail( + kErpcStatus_MemoryError, + "Invalid eRPC receive buffer bounds"); + } + + if (offset == 0) { + if (size != kFrameHeaderSize) { + return fail( + kErpcStatus_ReceiveFailed, + "Unexpected eRPC frame header size"); + } + } else if (offset != kFrameHeaderSize + || size != expected_reply_body_size_) { + return fail( + kErpcStatus_ReceiveFailed, + "USB head reply length mismatch"); + } + + return erpc::FramedTransport::underlyingReceive( + message, size, offset); +} + +erpc_status_t SdkFramedSerialTransport::underlyingReceive( + std::uint8_t* data, + std::uint32_t size) +{ + if (!data || size > kMaxBodySize) { + return fail( + kErpcStatus_InvalidArgument, + "Invalid eRPC receive size"); + } + + while (pending_.size() < size) { + const auto ready = checkReady(); + + if (ready != kErpcStatus_Success) { + return ready; + } + + const auto remaining = deadline_ - Clock::now(); + + if (remaining <= Clock::duration::zero()) { + return fail( + kErpcStatus_Timeout, + "USB head reply deadline exceeded"); + } + + auto wait = + std::chrono::duration_cast( + remaining); + + if (wait.count() == 0) { + wait = std::chrono::milliseconds(1); + } + + std::vector chunk; + + if (!serial_.read(size - pending_.size(), wait, chunk) + || chunk.empty()) { + return fail( + Clock::now() >= deadline_ + ? kErpcStatus_Timeout + : kErpcStatus_ReceiveFailed, + "USB head reply incomplete: " + serial_.lastError()); + } + + if (pending_.size() > kMaxBodySize + kFrameHeaderSize + || chunk.size() + > kMaxBodySize + kFrameHeaderSize - pending_.size()) { + return fail( + kErpcStatus_ReceiveFailed, + "USB head reply exceeds receive limit"); + } + + pending_.insert( + pending_.end(), chunk.begin(), chunk.end()); + } + + const auto ready = checkReady(); + + if (ready != kErpcStatus_Success) { + return ready; + } + + std::memcpy(data, pending_.data(), size); + pending_.erase(pending_.begin(), pending_.begin() + size); + + return kErpcStatus_Success; +} + +// 官方 Codec 负责类型编解码;这里保留严格的 bool ACK 检查。 +class StrictCodec final : public erpc::BasicCodec { +public: + using erpc::BasicCodec::read; + + void read(bool& value) override + { + std::uint8_t encoded{0}; + erpc::BasicCodec::read(encoded); + + if (isStatusOk() && encoded > 1) { + updateStatus(kErpcStatus_InvalidArgument); + } + + value = encoded == 1; + } +}; + +class CodecFactory final : public erpc::CodecFactory { +public: + erpc::Codec* create() override + { + return new (std::nothrow) StrictCodec; + } + + void dispose(erpc::Codec* codec) override + { + delete codec; + } +}; + +class BufferFactory final : public erpc::MessageBufferFactory { +public: + erpc::MessageBuffer create() override + { + auto* data = new (std::nothrow) std::uint8_t[4102]; + return erpc::MessageBuffer(data, data ? 4102 : 0); + } + + void dispose(erpc::MessageBuffer* buffer) override + { + delete[] buffer->get(); + } +}; + +class ClientManager final : public erpc::ClientManager { +public: + explicit ClientManager(std::uint32_t seed) + { + m_sequence = seed; + } + + void begin(std::uint8_t method) + { + method_ = method; + } + + erpc::RequestContext createRequest(bool oneway) override + { + if (m_sequence + == std::numeric_limits::max()) { + m_sequence = 0; + } + + return erpc::ClientManager::createRequest(oneway); + } + +protected: + void verifyReply(erpc::RequestContext& request) override + { + auto* codec = request.getCodec(); + + codec->reset(m_transport->reserveHeaderSize()); + + erpc::message_type_t type{}; + std::uint32_t service{}; + std::uint32_t method{}; + std::uint32_t sequence{}; + + codec->startReadMessage( + type, service, method, sequence); + + if (codec->isStatusOk() + && (type != erpc::message_type_t::kReplyMessage + || service != 1 + || method != method_ + || sequence != request.getSequence())) { + codec->updateStatus(kErpcStatus_ExpectedReply); + } + } + +private: + std::uint8_t method_{0}; +}; + +void checkId(const std::string& id) +{ + if (id.empty() + || id.size() > 64 + || id.find('\0') != std::string::npos) { + throw std::invalid_argument( + "USB head servo ID must contain 1..64 non-NUL bytes"); + } +} + +void checkFinite(float value) +{ + if (!std::isfinite(value)) { + throw std::invalid_argument( + "USB head arguments must be finite float32 values"); + } +} + +} // namespace + +struct UsbHeadErpcClient::Impl { + using Clock = std::chrono::steady_clock; + + std::unique_ptr<::cmvr::AbstractSerialTransport> serial; + std::chrono::milliseconds timeout; + mutable std::mutex mutex; + + std::string port; + int baud{0}; + + SdkFramedSerialTransport transport; + CodecFactory codec_factory; + BufferFactory buffer_factory; + ClientManager manager; + + Impl( + std::unique_ptr<::cmvr::AbstractSerialTransport> wire, + std::chrono::milliseconds budget, + std::uint32_t seed) + : serial(std::move(wire)), + timeout(budget), + transport(*serial), + manager(seed) + { + manager.setTransport(&transport); + manager.setCodecFactory(&codec_factory); + manager.setMessageBufferFactory(&buffer_factory); + } + + void failClosed() noexcept + { + transport.reset(); + + try { + serial->close(); + } catch (...) { + } + } + + void checkStatus(erpc::Codec& codec) + { + if (!codec.isStatusOk()) { + throw std::runtime_error( + "Official eRPC status=" + + std::to_string( + static_cast(codec.getStatus())) + + ": " + transport.lastError()); + } + } + + template + Result invoke( + std::uint8_t method, + EncodeArguments encode_arguments) + { + static_assert( + std::is_same_v + || std::is_same_v, + "Head service returns only bool or int32"); + + std::lock_guard lock(mutex); + + if (!serial->isOpen()) { + throw std::runtime_error( + "USB head is not connected"); + } + + const auto deadline = Clock::now() + timeout; + + try { + transport.beginTransaction( + deadline, method <= 4 ? 9 : 12); + + manager.begin(method); + + Result result{}; + + { + auto request = manager.createRequest(false); + + struct ReleaseRequest { + ClientManager& manager; + erpc::RequestContext& request; + + ~ReleaseRequest() + { + manager.releaseRequest(request); + } + } release{manager, request}; + + auto* codec = request.getCodec(); + + if (!codec) { + throw std::runtime_error( + "Cannot allocate eRPC request buffer/codec"); + } + + codec->startWriteMessage( + erpc::message_type_t::kInvocationMessage, + 1, + method, + request.getSequence()); + + encode_arguments(*codec); + checkStatus(*codec); + + manager.performRequest(request); + checkStatus(*codec); + + codec->read(result); + checkStatus(*codec); + } + + if (Clock::now() >= deadline) { + throw std::runtime_error( + "USB head reply deadline exceeded"); + } + + transport.endTransaction(); + return result; + } catch (const std::exception& error) { + const std::string reason = error.what(); + + failClosed(); + + throw std::runtime_error( + "USB head method " + std::to_string(method) + + " result unconfirmed; disconnected without retry. " + "Command may already have taken effect: " + + reason); + } catch (...) { + failClosed(); + throw; + } + } +}; + +UsbHeadErpcClient::UsbHeadErpcClient( + std::unique_ptr<::cmvr::AbstractSerialTransport> serial, + std::chrono::milliseconds timeout) + : UsbHeadErpcClient( + std::move(serial), + timeout, + std::random_device{}()) +{ +} + +UsbHeadErpcClient::UsbHeadErpcClient( + std::unique_ptr<::cmvr::AbstractSerialTransport> serial, + std::chrono::milliseconds timeout, + std::uint32_t seed) +{ + if (!serial || timeout.count() <= 0) { + throw std::invalid_argument( + "USB head transport and positive timeout are required"); + } + + impl_ = std::make_unique( + std::move(serial), timeout, seed); +} + +UsbHeadErpcClient::~UsbHeadErpcClient() +{ + try { + close(); + } catch (...) { + } +} + +void UsbHeadErpcClient::open( + const std::string& port, + int baud) +{ + if (port.empty() || baud <= 0) { + throw std::invalid_argument( + "USB head serial port and positive baud rate are required"); + } + + std::lock_guard lock(impl_->mutex); + + if (impl_->serial->isOpen()) { + if (port != impl_->port || baud != impl_->baud) { + throw std::logic_error( + "Close USB head before changing serial configuration"); + } + + return; + } + + impl_->transport.reset(); + + try { + if (!impl_->serial->open({port, baud})) { + throw std::runtime_error( + "Cannot open USB head port: " + + impl_->serial->lastError()); + } + + if (!impl_->serial->flushInput()) { + throw std::runtime_error( + "Cannot clear USB head input: " + + impl_->serial->lastError()); + } + + impl_->port = port; + impl_->baud = baud; + } catch (...) { + impl_->failClosed(); + throw; + } +} + +void UsbHeadErpcClient::close() +{ + std::lock_guard lock(impl_->mutex); + + impl_->transport.reset(); + + if (impl_->serial->isOpen() + && !impl_->serial->close()) { + throw std::runtime_error( + "Cannot close USB head port: " + + impl_->serial->lastError()); + } +} + +bool UsbHeadErpcClient::isOpen() const +{ + std::lock_guard lock(impl_->mutex); + return impl_->serial->isOpen(); +} + +bool UsbHeadErpcClient::setConstraints( + const std::string& id, + float velocity, + float acceleration, + float jerk) +{ + checkId(id); + checkFinite(velocity); + checkFinite(acceleration); + checkFinite(jerk); + + if (velocity <= 0 || acceleration <= 0 || jerk <= 0) { + throw std::invalid_argument( + "USB head motion limits must be positive"); + } + + return impl_->invoke(1, [&](erpc::Codec& codec) { + codec.writeString( + static_cast(id.size()), + id.c_str()); + + codec.write(velocity); + codec.write(acceleration); + codec.write(jerk); + }); +} + +bool UsbHeadErpcClient::setPositionGain( + const std::string& id, + float gain) +{ + checkId(id); + checkFinite(gain); + + if (gain < 0) { + throw std::invalid_argument( + "USB head position gain must be nonnegative"); + } + + return impl_->invoke(2, [&](erpc::Codec& codec) { + codec.writeString( + static_cast(id.size()), + id.c_str()); + + codec.write(gain); + }); +} + +bool UsbHeadErpcClient::setMode(std::int32_t mode) +{ + if (mode < 0 || mode > 2) { + throw std::invalid_argument( + "USB head mode must be 0, 1 or 2"); + } + + return impl_->invoke(3, [&](erpc::Codec& codec) { + codec.write(mode); + }); +} + +bool UsbHeadErpcClient::setUpdatePeriodMs( + std::uint32_t period) +{ + if (period < 1 || period > 100) { + throw std::invalid_argument( + "USB head update period must be 1..100 ms"); + } + + return impl_->invoke(4, [&](erpc::Codec& codec) { + codec.write(period); + }); +} + +std::int32_t UsbHeadErpcClient::move( + const std::vector& targets) +{ + if (targets.size() > 5) { + throw std::invalid_argument( + "USB head supports at most five targets"); + } + + std::set seen; + + for (const auto& target : targets) { + checkId(target.first); + checkFinite(target.second); + + if (!seen.insert(target.first).second) { + throw std::invalid_argument( + "USB head servo ID repeated in target batch"); + } + } + + return impl_->invoke( + 5, + [&](erpc::Codec& codec) { + codec.startWriteList( + static_cast(targets.size())); + + for (const auto& target : targets) { + codec.writeString( + static_cast( + target.first.size()), + target.first.c_str()); + + codec.write(target.second); + } + }); +} + +std::int32_t UsbHeadErpcClient::moveJ( + const std::vector& angles) +{ + if (angles.size() > 5) { + throw std::invalid_argument( + "USB head supports at most five joint targets"); + } + + for (const auto value : angles) { + checkFinite(value); + } + + return impl_->invoke( + 6, + [&](erpc::Codec& codec) { + codec.startWriteList( + static_cast(angles.size())); + + for (const auto value : angles) { + codec.write(value); + } + }); +} + +} // namespace cmvr::device \ No newline at end of file diff --git a/cmvr-es/devices/biohead/biohead_usb/src/usb_head_serial_transport.cpp b/cmvr-es/devices/biohead/biohead_usb/src/usb_head_serial_transport.cpp new file mode 100644 index 00000000..e762a8bd --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_usb/src/usb_head_serial_transport.cpp @@ -0,0 +1,266 @@ +#include "../include/usb_head_serial_transport.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace cmvr::device { +namespace { + +using Clock = std::chrono::steady_clock; + +template +int retryInterrupted(Operation operation, Clock::time_point deadline) +{ + for (;;) { + if (Clock::now() >= deadline) { + errno = ETIMEDOUT; + return -1; + } + const int result = operation(); + if (result >= 0 || errno != EINTR) return result; + } +} + +} // namespace + +UsbHeadSerialTransport::UsbHeadSerialTransport(std::chrono::milliseconds io_timeout) + : io_timeout_(io_timeout) +{ + if (io_timeout_.count() <= 0 || + io_timeout_ > std::chrono::duration_cast(Clock::duration::max() / 2)) { + throw std::invalid_argument("USB head I/O timeout is invalid"); + } +} + +UsbHeadSerialTransport::~UsbHeadSerialTransport() +{ + close(); +} + +void UsbHeadSerialTransport::setSystemError(const char* operation, int error_number) +{ + last_error_ = std::string(operation) + ": " + std::strerror(error_number); +} + +bool UsbHeadSerialTransport::open(const Config& config) +{ + std::lock_guard lock(io_mutex_); + last_error_.clear(); + if (config.port_name.empty() || config.port_name.find('\0') != std::string::npos || + config.baud_rate <= 0) { + last_error_ = "USB head requires a nonempty serial port and positive baud rate"; + return false; + } + if (!closeUnlocked()) return false; + + const auto deadline = Clock::now() + io_timeout_; + fd_ = retryInterrupted([&] { + return ::open(config.port_name.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC); + }, deadline); + if (fd_ < 0) { + setSystemError("Cannot open USB head serial port", errno); + return false; + } + + try { + auto fail = [&](const char* operation) { + const int saved_errno = errno; + closeUnlocked(); + setSystemError(operation, saved_errno); + return false; + }; + if (retryInterrupted([&] { return ::ioctl(fd_, TIOCEXCL); }, deadline) != 0) { + return fail("Cannot acquire exclusive USB head serial access"); + } + exclusive_ = true; + termios2 options{}; + if (retryInterrupted([&] { return ::ioctl(fd_, TCGETS2, &options); }, deadline) != 0) { + return fail("Cannot query USB head serial attributes"); + } + + options.c_iflag = 0; + options.c_oflag = 0; + options.c_lflag = 0; + options.c_cflag &= ~(CSIZE | PARENB | PARODD | CSTOPB | CRTSCTS | CBAUD | CIBAUD); + options.c_cflag |= CS8 | CLOCAL | CREAD | BOTHER; + options.c_cc[VMIN] = 0; + options.c_cc[VTIME] = 0; + options.c_ispeed = static_cast(config.baud_rate); + options.c_ospeed = static_cast(config.baud_rate); + if (retryInterrupted([&] { return ::ioctl(fd_, TCSETS2, &options); }, deadline) != 0) { + return fail("Cannot apply USB head raw 8N1 attributes"); + } + if (retryInterrupted([&] { return ::ioctl(fd_, TCFLSH, TCIOFLUSH); }, deadline) != 0) { + return fail("Cannot flush USB head serial buffers"); + } + return true; + } catch (...) { + closeUnlocked(); + throw; + } +} + +bool UsbHeadSerialTransport::close() noexcept +{ + try { + std::lock_guard lock(io_mutex_); + last_error_.clear(); + return closeUnlocked(); + } catch (...) { + return false; + } +} + +bool UsbHeadSerialTransport::closeUnlocked() noexcept +{ + if (fd_ < 0) return true; + const int owned_fd = fd_; + const bool release_exclusive = exclusive_; + fd_ = -1; + exclusive_ = false; + + int release_error = 0; + if (release_exclusive && retryInterrupted([&] { + return ::ioctl(owned_fd, TIOCNXCL); + }, Clock::now() + io_timeout_) != 0 && errno != EIO && errno != ENODEV) { + release_error = errno; + } + // On Linux close() releases the descriptor even for EINTR. Retrying could + // close an unrelated descriptor subsequently reused by another thread. + const int result = ::close(owned_fd); + const int close_error = result == 0 ? 0 : errno; + try { + if (close_error) setSystemError("Cannot close USB head serial port", close_error); + else if (release_error) setSystemError("Cannot release USB head serial exclusive mode", release_error); + } catch (...) { } + return close_error == 0 && release_error == 0; +} + +bool UsbHeadSerialTransport::isOpen() const +{ + std::lock_guard lock(io_mutex_); + return fd_ >= 0; +} + +bool UsbHeadSerialTransport::flushInput() +{ + std::lock_guard lock(io_mutex_); + last_error_.clear(); + if (fd_ < 0) { + last_error_ = "USB head serial port is not open"; + return false; + } + if (retryInterrupted([&] { return ::ioctl(fd_, TCFLSH, TCIFLUSH); }, + Clock::now() + io_timeout_) != 0) { + setSystemError("Cannot flush USB head serial input", errno); + return false; + } + return true; +} + +bool UsbHeadSerialTransport::waitReady(short events, Clock::time_point deadline) +{ + for (;;) { + const auto now = Clock::now(); + if (now >= deadline) { + last_error_ = "USB head serial I/O deadline exceeded"; + return false; + } + const auto remaining = std::chrono::ceil(deadline - now); + const int wait_ms = static_cast(std::min(remaining.count(), INT_MAX)); + pollfd descriptor{fd_, events, 0}; + const int result = ::poll(&descriptor, 1, wait_ms); + if (result < 0) { + if (errno == EINTR) continue; + setSystemError("USB head serial poll failed", errno); + return false; + } + if (result == 0) continue; + if (descriptor.revents & (POLLERR | POLLHUP | POLLNVAL)) { + last_error_ = "USB head serial port disconnected or invalid"; + return false; + } + if (descriptor.revents & events) return true; + } +} + +bool UsbHeadSerialTransport::write(const std::vector& data) +{ + std::lock_guard lock(io_mutex_); + last_error_.clear(); + if (fd_ < 0) { + last_error_ = "USB head serial port is not open"; + return false; + } + const auto deadline = Clock::now() + io_timeout_; + std::size_t offset = 0; + while (offset < data.size()) { + if (Clock::now() >= deadline) { + last_error_ = "USB head serial write deadline exceeded; bytes may already have been sent"; + return false; + } + const auto written = ::write(fd_, data.data() + offset, data.size() - offset); + if (written > 0) { + offset += static_cast(written); + continue; + } + if (written < 0 && errno == EINTR) continue; + if (written < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { + if (!waitReady(POLLOUT, deadline)) return false; + continue; + } + if (written == 0) last_error_ = "USB head serial write made no progress"; + else setSystemError("USB head serial write failed", errno); + return false; + } + return true; +} + +bool UsbHeadSerialTransport::read(std::size_t min_size, std::chrono::milliseconds timeout, + std::vector& out_buffer) +{ + std::lock_guard lock(io_mutex_); + last_error_.clear(); + out_buffer.clear(); + if (fd_ < 0) { + last_error_ = "USB head serial port is not open"; + return false; + } + if (timeout.count() <= 0 || min_size > 65536) { + last_error_ = "USB head serial read requires positive timeout and at most 65536 bytes"; + return false; + } + const auto deadline = Clock::now() + std::min(timeout, io_timeout_); + out_buffer.reserve(min_size); + std::array bytes{}; + while (out_buffer.size() < min_size) { + if (!waitReady(POLLIN, deadline)) return false; + const auto count = ::read(fd_, bytes.data(), bytes.size()); + if (count > 0) { + out_buffer.insert(out_buffer.end(), bytes.begin(), bytes.begin() + count); + continue; + } + if (count < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) continue; + if (count == 0) last_error_ = "USB head serial peer closed or read made no progress"; + else setSystemError("USB head serial read failed", errno); + return false; + } + return true; +} + +std::string UsbHeadSerialTransport::lastError() const +{ + std::lock_guard lock(io_mutex_); + return last_error_; +} + +} // namespace cmvr::device diff --git a/cmvr-es/devices/biohead/biohead_usb/tests/generate_erpc_vectors.py b/cmvr-es/devices/biohead/biohead_usb/tests/generate_erpc_vectors.py new file mode 100644 index 00000000..5b20ad71 --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_usb/tests/generate_erpc_vectors.py @@ -0,0 +1,120 @@ +"""Regenerate fixed C++ vectors with the source NXP eRPC Python SDK oracle. + +Usage: python generate_erpc_vectors.py --sdk-dir /path/to/runtime_deps +The C++ test consumes the checked-in output; Python/serial are not runtime deps. +""" +import argparse +from pathlib import Path +import sys + +parser = argparse.ArgumentParser() +parser.add_argument("--sdk-dir", type=Path, required=True) +parser.add_argument("--output", type=Path, + default=Path(__file__).with_name("usb_head_erpc_vectors.h")) +args = parser.parse_args() +sys.path.insert(0, str(args.sdk_dir)) + +from erpc.basic_codec import BasicCodec +from erpc.codec import MessageInfo, MessageType +from erpc.transport import FramedTransport + + +class OracleTransport(FramedTransport): + def __init__(self): + super().__init__() + self.packet = b"" + + def _base_send(self, packet): + self.packet = bytes(packet) + + +def frame(body): + transport = OracleTransport() + transport.send(body) + return transport.packet.hex() + + +def message(method, sequence, values, *, reply=False): + codec = BasicCodec() + codec.start_write_message(MessageInfo( + MessageType.kReplyMessage if reply else MessageType.kInvocationMessage, + 1, method, sequence)) + for kind, value in values: + if kind == "targets": + codec.start_write_list(len(value)) + for name, angle in value: + codec.write_string(name) + codec.write_float(angle) + elif kind == "angles": + codec.start_write_list(len(value)) + for angle in value: + codec.write_float(angle) + else: + getattr(codec, "write_" + kind)(value) + return bytes(codec.buffer) + + +cases = [ + (1, [("string", "eye_l_h"), ("float", 2.5), ("float", 20), ("float", 80)], True), + (2, [("string", "eye_l_h"), ("float", 3.5)], True), + (3, [("int32", 2)], True), + (4, [("uint32", 17)], True), + (5, [("targets", [("eye_l_h", 0.1), ("pwm8_local", -0.8)])], 0), + (6, [("angles", [0.1, -0.2, 0.3, -0.4, -0.8])], 0), + (5, [("targets", [])], -22), +] + + +def pair(method, sequence, values, result): + request = frame(message(method, sequence, values)) + reply = frame(message(method, sequence, + [("bool" if method < 5 else "int32", result)], reply=True)) + return request, reply + + +lines = [ + "// Generated by generate_erpc_vectors.py with the NXP eRPC Python SDK.", + "// Fixed wire vectors, independent of the C++ implementation under test.", + "#ifndef CMVR_ES_USB_HEAD_ERPC_VECTORS_H", + "#define CMVR_ES_USB_HEAD_ERPC_VECTORS_H", + "namespace cmvr::device::test {", + "struct RpcVector { const char* request; const char* reply; };", + "inline constexpr RpcVector kCalls[] = {", +] +for sequence, (method, values, result) in enumerate(cases, 1): + request, reply = pair(method, sequence, values, result) + lines.append(f' {{"{request}", "{reply}"}},') +lines.append("};") + +mode_request, mode_reply = pair(3, 1, [("int32", 2)], True) +lines.append(f'inline constexpr RpcVector kMode = {{"{mode_request}", "{mode_reply}"}};') +false_request, false_reply = pair(3, 1, [("int32", 2)], False) +lines.append(f'inline constexpr RpcVector kRejected = {{"{false_request}", "{false_reply}"}};') +lines.append("inline constexpr RpcVector kBadReplies[] = {") +reply_body = message(3, 1, [("bool", True)], reply=True) +for field, offset in [("type", 0), ("method", 1), ("service", 2), ("version", 3), + ("sequence", 4), ("boolean", 8)]: + body = bytearray(reply_body) + body[offset] = 2 if field == "boolean" else body[offset] ^ 1 + lines.append(f' {{"{mode_request}", "{frame(body)}"}}, // {field}') +lines.append(f' {{"{mode_request}", "{frame(reply_body + bytes([0]))}"}}, // length') +for field, index in [("header CRC", 0), ("body CRC", -1)]: + packet = bytearray.fromhex(mode_reply) + packet[index] ^= 1 + lines.append(f' {{"{mode_request}", "{packet.hex()}"}}, // {field}') +lines.append(f' {{"{mode_request}", "{mode_reply[:6]}"}}, // truncated header') +lines.append(f' {{"{mode_request}", "{mode_reply[:-2]}"}}, // truncated body') +lines.append("};") + +lines.append("inline constexpr RpcVector kWrap[] = {") +for sequence in [0xFFFFFFFF, 1]: + request, reply = pair(3, sequence, [("int32", 2)], True) + lines.append(f' {{"{request}", "{reply}"}},') +lines.append("};") +lines.append("inline constexpr RpcVector kConcurrent[] = {") +for sequence in range(1, 41): + request, reply = pair(3, sequence, [("int32", 2)], True) + lines.append(f' {{"{request}", "{reply}"}},') +lines += ["};", "} // namespace cmvr::device::test", "#endif", ""] +args.output.write_text("\n".join(lines), encoding="utf-8") +print(f"Wrote independent NXP SDK vectors: {args.output}") diff --git a/cmvr-es/devices/biohead/biohead_usb/tests/usb_biohead_test.cpp b/cmvr-es/devices/biohead/biohead_usb/tests/usb_biohead_test.cpp new file mode 100644 index 00000000..4a0dee82 --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_usb/tests/usb_biohead_test.cpp @@ -0,0 +1,544 @@ +#include "../include/usb_biohead.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace { + +using cmvr::device::HeadCommandOutcome; +using cmvr::device::UsbBioHead; + +void append16(std::vector& bytes, uint16_t value) +{ + bytes.push_back(static_cast(value)); + bytes.push_back(static_cast(value >> 8)); +} + +void append32(std::vector& bytes, uint32_t value) +{ + for (unsigned shift = 0; shift < 32; shift += 8) bytes.push_back(value >> shift); +} + +uint32_t read32(const std::vector& bytes, size_t at) +{ + uint32_t value = 0; + for (size_t index = 0; index < 4; ++index) value |= uint32_t(bytes.at(at + index)) << (8 * index); + return value; +} + +uint16_t crc(const std::vector& bytes) +{ + uint16_t value = 0xEF4A; + for (auto byte : bytes) { + value ^= uint16_t(byte) << 8; + for (int bit = 0; bit < 8; ++bit) { + value = static_cast((value & 0x8000) ? (value << 1) ^ 0x1021 : value << 1); + } + } + return value; +} + +// Firmware stand-in for backend behavior tests. Protocol byte correctness is +// independently checked against Python-generated vectors in the protocol tests. +class ReplyTransport final : public cmvr::AbstractSerialTransport { +public: + bool open(const Config&) override { ++open_attempts; opened = !fail_open; return opened; } + bool close() override { opened = false; return true; } + bool isOpen() const override { return opened; } + bool flushInput() override { pending.clear(); return true; } + std::string lastError() const override { return "injected read failure"; } + + bool write(const std::vector& request) override + { + writes.push_back(request); + writes_seen.store(writes.size()); + std::vector body(request.begin() + 6, request.begin() + 14); + body[0] = 2; + const auto method = request.at(7); + if (method == 5 || method == 6) { + const auto result = read32(request, 14) == 0 ? -22 : move_result; + append32(body, static_cast(result)); + } else { + body.push_back(boolean_result ? 1 : 0); + } + const auto length = static_cast(body.size()); + const auto checksum = crc(body); + std::vector length_bytes, checksum_bytes; + append16(length_bytes, length); + append16(checksum_bytes, checksum); + pending.clear(); + append16(pending, static_cast(crc(length_bytes) + crc(checksum_bytes))); + append16(pending, length); + append16(pending, checksum); + pending.insert(pending.end(), body.begin(), body.end()); + if ((method == 5 || method == 6) && read32(request, 14) != 0) { + if (on_move) on_move(); + if (move_delay.count()) std::this_thread::sleep_for(move_delay); + } + return true; + } + + bool read(size_t minimum, std::chrono::milliseconds, std::vector& output) override + { + if (fail_read || pending.empty()) return false; + const auto count = std::min(minimum, pending.size()); + output.assign(pending.begin(), pending.begin() + count); + pending.erase(pending.begin(), pending.begin() + count); + return true; + } + + bool opened{false}; + bool fail_open{false}; + size_t open_attempts{0}; + bool boolean_result{true}; + bool fail_read{false}; + int32_t move_result{0}; + std::function on_move; + std::chrono::milliseconds move_delay{0}; + std::atomic writes_seen{0}; + std::vector> writes; + std::vector pending; +}; + +cmvr::config::BioHeadRobotConfig configuration() +{ + cmvr::config::BioHeadRobotConfig config; + config.set_id("usb_head"); + config.set_serial_port("offline_fake"); + auto* first = config.mutable_usb_erpc()->add_joints(); + first->set_id("eye_l_lower"); + first->set_min_position_rad(-0.35); + first->set_max_position_rad(0.55); + first->set_home_position_rad(0); + auto* second = config.mutable_usb_erpc()->add_joints(); + second->set_id("pwm8_local"); + second->set_min_position_rad(-1.5); + second->set_max_position_rad(0.393); + second->set_home_position_rad(-1); + for (const auto& joint : std::vector{ + {"eye_l_up", -1, 1, 0}, {"eye_l_v", -1.5, 1, 0}, {"eye_l_h", -0.65, 0.70, 0}}) { + auto* next = config.mutable_usb_erpc()->add_joints(); + next->set_id(joint.id); + next->set_min_position_rad(joint.min_position_rad); + next->set_max_position_rad(joint.max_position_rad); + next->set_home_position_rad(joint.home_position_rad); + } + return config; +} + +float firstWirePosition(const std::vector& request) +{ + const auto name_size = read32(request, 18); + const auto bits = read32(request, 22 + name_size); + float value; + std::memcpy(&value, &bits, sizeof(value)); + return value; +} + +std::vector wireTargets(const std::vector& request) +{ + std::vector result; + size_t cursor = 18; + for (size_t index = 0; index < read32(request, 14); ++index) { + const auto size = read32(request, cursor); + cursor += 4; + const std::string id(request.begin() + cursor, request.begin() + cursor + size); + cursor += size; + const auto bits = read32(request, cursor); + cursor += 4; + float position; + std::memcpy(&position, &bits, sizeof(position)); + result.push_back({id, position}); + } + return result; +} + +std::vector movementWrites(const ReplyTransport& wire, size_t first = 0) +{ + std::vector result; + for (size_t index = first; index < wire.writes.size(); ++index) { + if (wire.writes[index][7] == 5 && read32(wire.writes[index], 14) > 0) result.push_back(index); + } + return result; +} + +TEST(UsbBioHead, InitProbesWithoutSendingTargetsOrHome) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(configuration(), std::move(transport)); + EXPECT_TRUE(wire->writes.empty()); + ASSERT_TRUE(head.init()); + ASSERT_EQ(wire->writes.size(), 1); + EXPECT_EQ(wire->writes[0][7], 5); + EXPECT_EQ(read32(wire->writes[0], 14), 0); + auto state = head.jointState(); + EXPECT_TRUE(state.connected); + EXPECT_EQ(state.last_command_outcome, HeadCommandOutcome::None); + EXPECT_FALSE(state.joints[0].target_valid); + EXPECT_FALSE(state.joints[1].target_valid); + EXPECT_FALSE(state.expression_baseline_ready); +} + +TEST(UsbBioHead, RejectsEntireInvalidBatchBeforeAnyWrite) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(configuration(), std::move(transport)); + ASSERT_TRUE(head.init()); + const auto count = wire->writes.size(); + EXPECT_THROW(head.moveJoints({{"eye_l_lower", 0.2}, {"pwm8_local", 0.5}}), std::invalid_argument); + EXPECT_THROW(head.moveJoints({{"eye_l_lower", 0.2}, {"eye_l_lower", 0.3}}), std::invalid_argument); + EXPECT_THROW(head.moveJoints({{"missing", 0.2}}), std::invalid_argument); + EXPECT_THROW(head.moveJoints({{"eye_l_lower", std::numeric_limits::quiet_NaN()}}), std::invalid_argument); + EXPECT_THROW(head.moveJoints({{"eye_l_lower", 1e-100}}), std::invalid_argument); + EXPECT_EQ(wire->writes.size(), count); +} + +TEST(UsbBioHead, QuantizesBoundariesInwardAndCachesOnlyAcknowledgedTargets) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(configuration(), std::move(transport)); + ASSERT_TRUE(head.init()); + head.moveJoints({{"eye_l_lower", 0.55}}); + const float encoded = firstWirePosition(wire->writes.back()); + EXPECT_LE(encoded, 0.55); + EXPECT_GE(encoded, -0.35); + EXPECT_EQ(encoded, std::nextafter(0.55f, -std::numeric_limits::infinity())); + auto state = head.jointState(); + EXPECT_EQ(state.last_command_outcome, HeadCommandOutcome::Acknowledged); + ASSERT_TRUE(state.joints[0].target_valid); + EXPECT_DOUBLE_EQ(state.joints[0].target_position_rad, encoded); + EXPECT_FALSE(state.joints[1].target_valid); + head.home(); + state = head.jointState(); + EXPECT_DOUBLE_EQ(state.joints[0].target_position_rad, 0); + EXPECT_DOUBLE_EQ(state.joints[1].target_position_rad, -1); + EXPECT_TRUE(state.expression_baseline_ready); +} + +TEST(UsbBioHead, FirmwareRejectionMayPartiallyExecuteAndInvalidatesCachedTargets) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(configuration(), std::move(transport)); + ASSERT_TRUE(head.init()); + head.moveJoints({{"eye_l_lower", 0.2}}); + wire->move_result = -88; + EXPECT_THROW(head.moveJoints({{"eye_l_lower", 0.3}}), std::runtime_error); + const auto state = head.jointState(); + EXPECT_EQ(state.last_command_outcome, HeadCommandOutcome::Rejected); + EXPECT_FALSE(state.joints[0].target_valid); + EXPECT_NE(state.last_error.find("partial execution"), std::string::npos); +} + +TEST(UsbBioHead, UnknownReplyDisconnectsWithoutRetryOrTargetSuccess) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(configuration(), std::move(transport)); + ASSERT_TRUE(head.init()); + head.moveJoints({{"eye_l_lower", 0.2}}); + wire->fail_read = true; + const auto count = wire->writes.size(); + EXPECT_THROW(head.moveJoints({{"eye_l_lower", 0.3}}), std::runtime_error); + EXPECT_EQ(wire->writes.size(), count + 1); + const auto state = head.jointState(); + EXPECT_FALSE(state.connected); + EXPECT_EQ(state.last_command_outcome, HeadCommandOutcome::Unknown); + EXPECT_FALSE(state.joints[0].target_valid); +} + +TEST(UsbBioHead, StopDoesNotClaimHardwareStoppedAndLegacyCommandsAreUnsupported) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(configuration(), std::move(transport)); + ASSERT_TRUE(head.init()); + const auto count = wire->writes.size(); + EXPECT_THROW(head.eStop(), std::runtime_error); + EXPECT_THROW(head.speakstart(), std::runtime_error); + EXPECT_FALSE(head.stop()); + EXPECT_FALSE(head.jointState().connected); + EXPECT_EQ(wire->writes.size(), count); +} + +TEST(UsbBioHead, RejectsInvalidSettingsBeforeTransportWrite) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(configuration(), std::move(transport)); + ASSERT_TRUE(head.init()); + const auto count = wire->writes.size(); + EXPECT_THROW(head.setMotionConstraints("eye_l_lower", 0, 2, 3), std::invalid_argument); + EXPECT_THROW(head.setPositionGain("eye_l_lower", -1), std::invalid_argument); + EXPECT_THROW(head.setUpdatePeriodMs(101), std::invalid_argument); + EXPECT_EQ(wire->writes.size(), count); + EXPECT_NO_THROW(head.setPositionGain("eye_l_lower", 0)); +} + +TEST(UsbBioHead, FrozenPresetsPreserveSixIdsNamesAndOriginalDoubleValues) +{ + UsbBioHead head(configuration(), std::make_unique()); + const auto& presets = head.expressions(); + const char* ids[]{"0de8a527543e423abab593484926dd1c", "ad8f669a78d54d30a2356512b0802c1d", + "516bc0f0e76647109411cbf92e5c86fc", "5e68f9b26f4d4f8580dead7777c6501b", + "44821d9fa6df4fc78558666db32656e1", "8f97ed10b5b44012b004183ba61c839c"}; + const char* names[]{u8"中立", u8"微笑", u8"疲倦", u8"惊讶", u8"生气", u8"当前姿态"}; + const char* joints[]{"eye_l_up", "eye_l_lower", "eye_l_v", "eye_l_h", "pwm8_local"}; + const double expected[][5]{ + {0, 0, 0, 0, -1}, + {0.2329999953508377, -0.00041940261144191027, -0.00041940261144191027, + -0.00041940261144191027, -1.121000051498413}, + {-0.991, 0.322, -1.015, 0.004, -0.537}, + {-1, -0.0004194026121000505, 0.999890384765, -0.0004194026121000505, -0.0004194026121000505}, + {-1, 0.5497252979258, 0.999890384765, 0.6999468312800001, -1.400129282005}, + {-0.0004194026121000505, -0.0004194026121000505, -0.0004194026121000505, -0.65, -1} + }; + ASSERT_EQ(presets.size(), 6); + for (size_t pose = 0; pose < 6; ++pose) { + EXPECT_EQ(presets[pose].id, ids[pose]); + EXPECT_EQ(presets[pose].name, names[pose]); + ASSERT_EQ(presets[pose].targets.size(), 5); + for (size_t joint = 0; joint < 5; ++joint) { + EXPECT_EQ(presets[pose].targets[joint].id, joints[joint]); + EXPECT_EQ(presets[pose].targets[joint].position_rad, expected[pose][joint]); + } + } +} + +TEST(UsbBioHead, ExpressionRequiresAllFiveImmediateTargetsInCurrentConnection) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(configuration(), std::move(transport)); + ASSERT_TRUE(head.init()); + const auto before = wire->writes.size(); + EXPECT_THROW(head.playExpression(u8"疲倦", true, .2, {}), std::runtime_error); + EXPECT_EQ(wire->writes.size(), before); + head.home(); + EXPECT_TRUE(head.jointState().expression_baseline_ready); + head.setMotionMode(cmvr::device::HeadMotionMode::SCurve); + EXPECT_FALSE(head.jointState().expression_baseline_ready); + head.setMotionMode(cmvr::device::HeadMotionMode::Immediate); + EXPECT_FALSE(head.jointState().expression_baseline_ready); + const auto current = wire->writes.size(); + EXPECT_THROW(head.playExpression(u8"疲倦", true, .2, {}), std::runtime_error); + EXPECT_EQ(wire->writes.size(), current); +} + +TEST(UsbBioHead, MinimumJerkExpressionUsesCompleteFramesAndAcknowledgedFinalTarget) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(configuration(), std::move(transport)); + ASSERT_TRUE(head.init()); + head.home(); + const auto before = wire->writes.size(); + const auto pose = head.playExpression(u8"疲倦", true, .2, {}); + EXPECT_EQ(pose.id, "516bc0f0e76647109411cbf92e5c86fc"); + ASSERT_GE(wire->writes.size(), before + 3); + EXPECT_EQ(wire->writes[before][7], 3); + EXPECT_EQ(read32(wire->writes[before], 14), 0); + EXPECT_EQ(wire->writes[before + 1][7], 4); + EXPECT_EQ(read32(wire->writes[before + 1], 14), 20); + const auto frames = movementWrites(*wire, before); + ASSERT_FALSE(frames.empty()); + EXPECT_LE(frames.size(), 10); + for (const auto index : frames) { + const auto positions = wireTargets(wire->writes[index]); + ASSERT_EQ(positions.size(), 5); + // Each emitted frame is one of the prevalidated quintic samples; + // host scheduling is allowed to skip samples, never replay them. + const double up = positions[0].position_rad; + bool is_planned = false; + for (int frame = 1; frame <= 10; ++frame) { + const double u = frame / 10.0; + const double blend = u * u * u * (10 + u * (-15 + 6 * u)); + const float target = static_cast(-0.991); + const float expected = frame == 10 ? target : static_cast(target * blend); + if (up == expected) is_planned = true; + } + EXPECT_TRUE(is_planned); + } + const auto final = wireTargets(wire->writes[frames.back()]); + EXPECT_DOUBLE_EQ(final[0].position_rad, static_cast(-0.991)); + EXPECT_DOUBLE_EQ(final[4].position_rad, static_cast(-0.537)); + const auto state = head.jointState(); + EXPECT_TRUE(state.expression_baseline_ready); + EXPECT_EQ(state.last_command_outcome, HeadCommandOutcome::Acknowledged); +} + +TEST(UsbBioHead, InvalidDurationOrIncompleteExpressionDoesNotWrite) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(configuration(), std::move(transport)); + ASSERT_TRUE(head.init()); + head.home(); + const auto before = wire->writes.size(); + EXPECT_THROW(head.setExpression({{"eye_l_up", .1}}, .2, {}), std::invalid_argument); + EXPECT_THROW(head.playExpression(u8"微笑", true, .19, {}), std::invalid_argument); + EXPECT_THROW(head.playExpression(u8"微笑", true, 5.01, {}), std::invalid_argument); + EXPECT_THROW(head.playExpression(u8"微笑", true, std::numeric_limits::quiet_NaN(), {}), std::invalid_argument); + EXPECT_THROW(head.playExpression("missing", false, .2, {}), std::invalid_argument); + EXPECT_EQ(wire->writes.size(), before); + EXPECT_TRUE(head.jointState().expression_baseline_ready); +} + +TEST(UsbBioHead, SlowAcknowledgementsSkipExpiredFramesButStillSendExactFinalFrame) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(configuration(), std::move(transport)); + ASSERT_TRUE(head.init()); + head.home(); + const auto before = wire->writes.size(); + wire->move_delay = std::chrono::milliseconds(60); + head.playExpression(u8"疲倦", true, .2, {}); + const auto frames = movementWrites(*wire, before); + ASSERT_FALSE(frames.empty()); + EXPECT_LT(frames.size(), 10); + const auto final = wireTargets(wire->writes[frames.back()]); + EXPECT_DOUBLE_EQ(final[0].position_rad, static_cast(-0.991)); +} + +TEST(UsbBioHead, CancellationStopsFutureFramesAndConcurrentControlIsBusy) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(configuration(), std::move(transport)); + ASSERT_TRUE(head.init()); + head.home(); + std::mutex mutex; + std::condition_variable condition; + bool entered = false, release = false; + std::atomic calls{0}; + wire->on_move = [&] { + ++calls; + std::unique_lock lock(mutex); + entered = true; + condition.notify_all(); + condition.wait_for(lock, std::chrono::seconds(2), [&] { return release; }); + }; + const auto before = wire->writes.size(); + auto work = std::async(std::launch::async, [&] { head.playExpression(u8"疲倦", true, .5, {}); }); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(condition.wait_for(lock, std::chrono::seconds(2), [&] { return entered; })); + } + const auto writes = wire->writes_seen.load(); + EXPECT_THROW(head.moveJoints({{"eye_l_up", .1}}), std::runtime_error); + EXPECT_EQ(wire->writes_seen.load(), writes); + head.cancelExpression(); + { + std::lock_guard lock(mutex); + release = true; + } + condition.notify_all(); + EXPECT_THROW(work.get(), std::runtime_error); + EXPECT_EQ(calls.load(), 1); + EXPECT_EQ(movementWrites(*wire, before).size(), 1); + EXPECT_FALSE(head.jointState().expression_baseline_ready); +} + +TEST(UsbBioHead, DeadlineCancellationAndReconnectNeverSendHomeAutomatically) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(configuration(), std::move(transport)); + ASSERT_TRUE(head.init()); + head.home(); + auto before = wire->writes.size(); + EXPECT_THROW(head.playExpression(u8"微笑", true, .2, [] { return true; }), std::runtime_error); + EXPECT_EQ(wire->writes.size(), before); + EXPECT_FALSE(head.jointState().expression_baseline_ready); + before = wire->writes.size(); + head.reconnect(); + ASSERT_EQ(wire->writes.size(), before + 1); + EXPECT_EQ(read32(wire->writes.back(), 14), 0); + EXPECT_TRUE(head.jointState().connected); + EXPECT_FALSE(head.jointState().expression_baseline_ready); + EXPECT_THROW(head.playExpression(u8"微笑", true, .2, {}), std::runtime_error); +} + +TEST(UsbBioHead, HomeCancellationAfterSettingsDoesNotSendPositionTargets) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(configuration(), std::move(transport)); + ASSERT_TRUE(head.init()); + const auto before = wire->writes.size(); + // Expire once setMode and setUpdatePeriodMs have both been acknowledged. + EXPECT_THROW(head.home([&] { return wire->writes.size() >= before + 2; }), std::runtime_error); + EXPECT_EQ(wire->writes.size(), before + 2); + EXPECT_TRUE(movementWrites(*wire, before).empty()); + EXPECT_FALSE(head.jointState().expression_baseline_ready); +} + +TEST(UsbBioHead, OfflineInitRemainsRegisteredAndOnlyExplicitReconnectAttemptsRecovery) +{ + auto transport = std::make_unique(); + auto* wire = transport.get(); + wire->fail_open = true; + UsbBioHead head(configuration(), std::move(transport)); + EXPECT_TRUE(head.init()); // Object/configuration initialized; hardware is offline. + EXPECT_EQ(wire->open_attempts, 1); + EXPECT_TRUE(wire->writes.empty()); + auto state = head.jointState(); + EXPECT_FALSE(state.connected); + EXPECT_FALSE(state.expression_baseline_ready); + EXPECT_EQ(state.last_command_outcome, HeadCommandOutcome::Unknown); + EXPECT_FALSE(state.last_error.empty()); + EXPECT_EQ(head.expressions().size(), 6); + EXPECT_THROW(head.moveJoints({{"eye_l_up", .1}}), std::runtime_error); + wire->fail_open = false; + EXPECT_TRUE(head.start()); + EXPECT_EQ(wire->open_attempts, 1); // start() must not silently reconnect. + EXPECT_TRUE(wire->writes.empty()); + head.reconnect(); + EXPECT_EQ(wire->open_attempts, 2); + ASSERT_EQ(wire->writes.size(), 1); + EXPECT_EQ(wire->writes[0][7], 5); + EXPECT_EQ(read32(wire->writes[0], 14), 0); // Only a no-target service probe. + state = head.jointState(); + EXPECT_TRUE(state.connected); + EXPECT_FALSE(state.expression_baseline_ready); + EXPECT_EQ(state.last_command_outcome, HeadCommandOutcome::None); + for (const auto& joint : state.joints) EXPECT_FALSE(joint.target_valid); +} + +TEST(UsbBioHead, HomeSupportsConfiguredSubsetWithoutClaimingFiveJointBaseline) +{ + auto config = configuration(); + config.mutable_usb_erpc()->mutable_joints()->DeleteSubrange(2, 3); + auto transport = std::make_unique(); + auto* wire = transport.get(); + UsbBioHead head(config, std::move(transport)); + ASSERT_TRUE(head.init()); + head.home(); + const auto movements = movementWrites(*wire); + ASSERT_EQ(movements.size(), 1); + const auto targets = wireTargets(wire->writes[movements.front()]); + ASSERT_EQ(targets.size(), 2); + EXPECT_EQ(targets[0].id, "eye_l_lower"); + EXPECT_EQ(targets[1].id, "pwm8_local"); + EXPECT_FALSE(head.jointState().expression_baseline_ready); + const auto writes = wire->writes.size(); + EXPECT_THROW(head.setExpression(targets, 0.2, {}), std::invalid_argument); + EXPECT_EQ(wire->writes.size(), writes); +} + +} // namespace diff --git a/cmvr-es/devices/biohead/biohead_usb/tests/usb_head_erpc_client_test.cpp b/cmvr-es/devices/biohead/biohead_usb/tests/usb_head_erpc_client_test.cpp new file mode 100644 index 00000000..06dc3090 --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_usb/tests/usb_head_erpc_client_test.cpp @@ -0,0 +1,253 @@ +#include "../include/usb_head_erpc_client.h" +#include "usb_head_erpc_vectors.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using cmvr::device::UsbHeadErpcClient; +using cmvr::device::test::RpcVector; +using namespace std::chrono_literals; + +void require(bool condition, const char* message) +{ + if (!condition) throw std::runtime_error(message); +} + +std::vector unhex(const char* text) +{ + std::vector result; + const std::string value(text); + require(value.size() % 2 == 0, "Invalid test vector"); + for (std::size_t index = 0; index < value.size(); index += 2) { + result.push_back(static_cast(std::stoul(value.substr(index, 2), nullptr, 16))); + } + return result; +} + +class ScriptedTransport final : public cmvr::AbstractSerialTransport { +public: + ScriptedTransport(const RpcVector* entries, std::size_t size) + : entries_(entries), size_(size) { } + + bool open(const Config& config) override + { + port_seen = config.port_name; + baud_rate_seen = config.baud_rate; + opened_ = !fail_open; + return opened_; + } + bool close() override { opened_ = false; ++closes; return true; } + bool isOpen() const override { return opened_; } + bool flushInput() override { pending_.clear(); return !fail_flush; } + std::string lastError() const override { return "injected transport fault"; } + + bool write(const std::vector& data) override + { + { + std::lock_guard lock(mutex_); + require(opened_, "Write after close"); + require(pending_.empty(), "Concurrent requests interleaved"); + require(writes < size_, "Unexpected retry or extra request"); + require(data == unhex(entries_[writes].request), "Request disagrees with Python SDK oracle"); + pending_ = unhex(entries_[writes].reply); + ++writes; + if (fail_write) return false; + } + // Forces a scheduling opportunity while a complete RPC is outstanding. + if (schedule_delay) std::this_thread::sleep_for(1ms); + if (write_delay.count()) std::this_thread::sleep_for(write_delay); + return true; + } + + bool read(std::size_t, std::chrono::milliseconds, + std::vector& output) override + { + if (read_delay.count()) std::this_thread::sleep_for(read_delay); + std::lock_guard lock(mutex_); + ++reads; + if (fail_read || pending_.empty()) return false; + const auto count = std::min(chunk_size, pending_.size()); + output.assign(pending_.begin(), pending_.begin() + count); + pending_.erase(pending_.begin(), pending_.begin() + count); + return true; + } + + std::size_t writes{0}; + std::size_t reads{0}; + int closes{0}; + std::size_t chunk_size{2}; + std::chrono::milliseconds read_delay{0}; + std::chrono::milliseconds write_delay{0}; + std::string port_seen; + int baud_rate_seen{0}; + bool fail_open{false}; + bool fail_flush{false}; + bool fail_write{false}; + bool fail_read{false}; + bool schedule_delay{false}; + +private: + const RpcVector* entries_; + std::size_t size_; + std::vector pending_; + std::atomic opened_{false}; + std::mutex mutex_; +}; + +void testGoldenMethodsAndFragmentedReads() +{ + using namespace cmvr::device::test; + auto wire = std::make_unique(kCalls, std::size(kCalls)); + auto* observed = wire.get(); + UsbHeadErpcClient client(std::move(wire), 2000ms, 0); + client.open("fake"); + require(observed->writes == 0, "Opening must not send any target"); + require(observed->port_seen == "fake" && observed->baud_rate_seen == 115200, + "Protocol must use the original serial transport Config"); + require(client.setConstraints("eye_l_h", 2.5f, 20.f, 80.f), "constraints"); + require(client.setPositionGain("eye_l_h", 3.5f), "gain"); + require(client.setMode(2), "mode"); + require(client.setUpdatePeriodMs(17), "period"); + require(client.move({{"eye_l_h", .1f}, {"pwm8_local", -.8f}}) == 0, "move"); + require(client.moveJ({.1f, -.2f, .3f, -.4f, -.8f}) == 0, "moveJ method ID must be 6"); + require(client.move({}) == -22, "signed no-target probe result"); + require(observed->writes == 7, "Expected exactly one frame per operation"); + require(client.isOpen(), "Known firmware result must not be misreported as transport failure"); + client.close(); + require(observed->closes == 1, "close"); +} + +void testCoalescedReplyAndKnownRejection() +{ + using namespace cmvr::device::test; + for (const auto* entry : {&kMode, &kRejected}) { + auto wire = std::make_unique(entry, 1); + wire->chunk_size = 4096; + UsbHeadErpcClient client(std::move(wire), 2000ms, 0); + client.open("fake"); + require(client.setMode(2) == (entry == &kMode), "Preserve boolean ACK result"); + require(client.isOpen(), "Well-formed false ACK has a confirmed result"); + } +} + +void testCorruptionDisconnectsWithoutRetry() +{ + using namespace cmvr::device::test; + for (const auto& entry : kBadReplies) { + auto wire = std::make_unique(&entry, 1); + auto* observed = wire.get(); + UsbHeadErpcClient client(std::move(wire), 2000ms, 0); + client.open("fake"); + bool failed = false; + try { client.setMode(2); } catch (const std::runtime_error&) { failed = true; } + require(failed, "Malformed frame was accepted"); + require(!client.isOpen(), "Malformed or incomplete frame must disconnect"); + require(observed->writes == 1, "Unconfirmed commands must not be retried"); + require(observed->closes == 1, "Failure must close port"); + } +} + +void testTransportFaultsAndWholeReplyDeadline() +{ + using namespace cmvr::device::test; + for (int fault = 0; fault < 4; ++fault) { + auto wire = std::make_unique(&kMode, 1); + auto* observed = wire.get(); + wire->fail_write = fault == 0; + wire->fail_read = fault == 1; + if (fault == 2) { + wire->read_delay = 12ms; + wire->chunk_size = 1; + } + if (fault == 3) wire->write_delay = 25ms; + UsbHeadErpcClient client(std::move(wire), fault >= 2 ? 20ms : 2000ms, 0); + client.open("fake"); + bool failed = false; + try { client.setMode(2); } catch (const std::runtime_error&) { failed = true; } + require(failed && !client.isOpen(), "Transport failure must disconnect"); + require(observed->writes == 1, "No automatic retry after write/read/deadline fault"); + if (fault == 2) require(observed->reads <= 2, "Deadline must not restart for each fragment"); + if (fault == 3) require(observed->reads == 0, "The RPC deadline must start before write"); + } +} + +void testValidationHasNoSideEffects() +{ + using namespace cmvr::device::test; + auto wire = std::make_unique(&kMode, 1); + auto* observed = wire.get(); + UsbHeadErpcClient client(std::move(wire), 2000ms, 0); + client.open("fake"); + auto invalid = [&](auto operation) { + bool failed = false; + try { operation(); } catch (const std::invalid_argument&) { failed = true; } + require(failed, "Invalid input accepted"); + require(observed->writes == 0 && client.isOpen(), "Validation sent an RPC or closed connection"); + }; + invalid([&] { client.setMode(3); }); + invalid([&] { client.setUpdatePeriodMs(0); }); + invalid([&] { client.setConstraints("eye_l_h", 0, 1, 1); }); + invalid([&] { client.setPositionGain("eye_l_h", -1); }); + invalid([&] { client.move({{"eye_l_h", 0}, {"eye_l_h", 1}}); }); + invalid([&] { client.move({{"eye_l_h", std::numeric_limits::quiet_NaN()}}); }); + invalid([&] { client.move({{std::string(65, 'x'), 0}}); }); + invalid([&] { client.moveJ(std::vector(6)); }); + require(client.setMode(2), "Invalid requests must not consume sequence numbers"); +} + +void testSequenceWrapAndConcurrentTransactions() +{ + using namespace cmvr::device::test; + { + auto wire = std::make_unique(kWrap, std::size(kWrap)); + UsbHeadErpcClient client(std::move(wire), 2000ms, 0xFFFFFFFEu); + client.open("fake"); + require(client.setMode(2) && client.setMode(2), "Sequence must wrap and skip zero"); + } + auto wire = std::make_unique(kConcurrent, std::size(kConcurrent)); + auto* observed = wire.get(); + wire->schedule_delay = true; + UsbHeadErpcClient client(std::move(wire), 2000ms, 0); + client.open("fake"); + std::atomic errors{0}; + auto worker = [&] { + try { + for (int count = 0; count < 20; ++count) { + if (!client.setMode(2)) ++errors; + } + } catch (...) { ++errors; } + }; + std::thread first(worker); + std::thread second(worker); + first.join(); + second.join(); + require(errors == 0 && observed->writes == 40, "Request/reply transaction interleaving"); +} + +} // namespace + +int main() +{ + try { + testGoldenMethodsAndFragmentedReads(); + testCoalescedReplyAndKnownRejection(); + testCorruptionDisconnectsWithoutRetry(); + testTransportFaultsAndWholeReplyDeadline(); + testValidationHasNoSideEffects(); + testSequenceWrapAndConcurrentTransactions(); + std::cout << "USB head eRPC offline tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/cmvr-es/devices/biohead/biohead_usb/tests/usb_head_erpc_vectors.h b/cmvr-es/devices/biohead/biohead_usb/tests/usb_head_erpc_vectors.h new file mode 100644 index 00000000..0a7af75e --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_usb/tests/usb_head_erpc_vectors.h @@ -0,0 +1,78 @@ +// Generated by generate_erpc_vectors.py with the NXP eRPC Python SDK. +// Fixed wire vectors, independent of the C++ implementation under test. +#ifndef CMVR_ES_USB_HEAD_ERPC_VECTORS_H +#define CMVR_ES_USB_HEAD_ERPC_VECTORS_H +namespace cmvr::device::test { +struct RpcVector { const char* request; const char* reply; }; +inline constexpr RpcVector kCalls[] = { + {"371e1f0096430001010101000000070000006579655f6c5f68000020400000a0410000a042", "54e609006a7e020101010100000001"}, + {"0582170022b20002010102000000070000006579655f6c5f6800006040", "91a60900cd58020201010200000001"}, + {"1f9d0c00cb95000301010300000002000000", "285709004fb5020301010300000001"}, + {"5ff80c0015fb000401010400000011000000", "f73809008315020401010400000001"}, + {"428d2d00e52d000501010500000002000000070000006579655f6c5f68cdcccc3d0a00000070776d385f6c6f63616ccdcc4cbf", "81660c00760f020501010500000000000000"}, + {"cbe120004449000601010600000005000000cdcccc3dcdcc4cbe9a99993ecdccccbecdcc4cbf", "dec20c00f9bf020601010600000000000000"}, + {"819e0c003a86000501010700000000000000", "f9760c00fdbe0205010107000000eaffffff"}, +}; +inline constexpr RpcVector kMode = {"7ed30c006d1a000301010100000002000000", "9f980900ccf1020301010100000001"}; +inline constexpr RpcVector kRejected = {"7ed30c006d1a000301010100000002000000", "7db60900ede1020301010100000000"}; +inline constexpr RpcVector kBadReplies[] = { + {"7ed30c006d1a000301010100000002000000", "8fae0900ef1a030301010100000001"}, // type + {"7ed30c006d1a000301010100000002000000", "ec9009001fb6020201010100000001"}, // method + {"7ed30c006d1a000301010100000002000000", "67af0900ad49020300010100000001"}, // service + {"7ed30c006d1a000301010100000002000000", "b49309006cb4020301000100000001"}, // version + {"7ed30c006d1a000301010100000002000000", "c5bf09009d5b020301010000000001"}, // sequence + {"7ed30c006d1a000301010100000002000000", "c9800900afc1020301010100000002"}, // boolean + {"7ed30c006d1a000301010100000002000000", "71d00a003e3302030101010000000100"}, // length + {"7ed30c006d1a000301010100000002000000", "9e980900ccf1020301010100000001"}, // header CRC + {"7ed30c006d1a000301010100000002000000", "9f980900ccf1020301010100000000"}, // body CRC + {"7ed30c006d1a000301010100000002000000", "9f9809"}, // truncated header + {"7ed30c006d1a000301010100000002000000", "9f980900ccf10203010101000000"}, // truncated body +}; +inline constexpr RpcVector kWrap[] = { + {"7c690c00906200030101ffffffff02000000", "aac109000d8602030101ffffffff01"}, + {"7ed30c006d1a000301010100000002000000", "9f980900ccf1020301010100000001"}, +}; +inline constexpr RpcVector kConcurrent[] = { + {"7ed30c006d1a000301010100000002000000", "9f980900ccf1020301010100000001"}, + {"56350c0018d2000301010200000002000000", "3a7e09001e1f020301010200000001"}, + {"1f9d0c00cb95000301010300000002000000", "285709004fb5020301010300000001"}, + {"30800c00d352000301010400000002000000", "c61909009bd2020301010400000001"}, + {"05580c000015000301010500000002000000", "9c420900ca78020301010500000001"}, + {"edb00c0075dd000301010600000002000000", "41d409001896020301010600000001"}, + {"98280c00a69a000301010700000002000000", "23fd0900493c020301010700000001"}, + {"ba020c006443000301010800000002000000", "6d900900b059020301010800000001"}, + {"8bda0c00b704000301010900000002000000", "97690900e1f3020301010900000001"}, + {"632e0c00c2cc000301010a00000002000000", "f2cd0900331d020301010a00000001"}, + {"12a60c00118b000301010b00000002000000", "10a7090062b7020301010b00000001"}, + {"41870c00094c000301010c00000002000000", "6eea0900b6d0020301010c00000001"}, + {"f44e0c00da0b000301010d00000002000000", "94130900e77a020301010d00000001"}, + {"dcb90c00afc3000301010e00000002000000", "f92309003594020301010e00000001"}, + {"a9210c007c84000301010f00000002000000", "0b4d0900643e020301010f00000001"}, + {"de160c000a60000301011000000002000000", "75210900c75f020301011000000001"}, + {"a7be0c00d927000301011100000002000000", "8f38090096f5020301011100000001"}, + {"3f6a0c00acef000301011200000002000000", "eade0900441b020301011200000001"}, + {"f6710c007fa8000301011300000002000000", "18f6090015b1020301011300000001"}, + {"65930c00676f000301011400000002000000", "76bb0900c1d6020301011400000001"}, + {"104b0c00b428000301011500000002000000", "8ca20900907c020301011500000001"}, + {"b8dd0c00c1e0000301011600000002000000", "f17409004292020301011600000001"}, + {"8df50c0012a7000301011700000002000000", "135c09001338020301011700000001"}, + {"eb0f0c00d07e000301011800000002000000", "bdf00900ea5d020301011800000001"}, + {"9ac70c000339000301011900000002000000", "a7070900bbf7020301011900000001"}, + {"32610c0076f1000301011a00000002000000", "422f09006919020301011a00000001"}, + {"03790c00a5b6000301011b00000002000000", "2046090038b3020301011b00000001"}, + {"549c0c00bd71000301011c00000002000000", "be8a0900ecd4020301011c00000001"}, + {"21440c006e36000301011d00000002000000", "a4710900bd7e020301011d00000001"}, + {"c9e40c001bfe000301011e00000002000000", "49c509006f90020301011e00000001"}, + {"7cec0c00c8b9000301011f00000002000000", "1bac09003e3a020301011f00000001"}, + {"96be0c00d626000301012000000002000000", "849309002953020301012000000001"}, + {"df160c000561000301012100000002000000", "5e6a090078f9020301012100000001"}, + {"07720c0070a9000301012200000002000000", "fbcc0900aa17020301012200000001"}, + {"3e6a0c00a3ee000301012300000002000000", "e9a30900fbbd020301012300000001"}, + {"2d4b0c00bb29000301012400000002000000", "87e909002fda020301012400000001"}, + {"58930c00686e000301012500000002000000", "5d1009007e70020301012500000001"}, + {"70f50c001da6000301012600000002000000", "00270900ac9e020301012600000001"}, + {"c5dd0c00cee1000301012700000002000000", "e24d0900fd34020301012700000001"}, + {"a3c70c000c38000301012800000002000000", "acc209000451020301012800000001"}, +}; +} // namespace cmvr::device::test +#endif diff --git a/cmvr-es/devices/biohead/biohead_usb/tests/usb_head_serial_transport_test.cpp b/cmvr-es/devices/biohead/biohead_usb/tests/usb_head_serial_transport_test.cpp new file mode 100644 index 00000000..4d320592 --- /dev/null +++ b/cmvr-es/devices/biohead/biohead_usb/tests/usb_head_serial_transport_test.cpp @@ -0,0 +1,259 @@ +#include "../include/usb_head_serial_transport.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using cmvr::device::UsbHeadSerialTransport; +using Clock = std::chrono::steady_clock; +using namespace std::chrono_literals; + +void require(bool condition, const char* message) +{ + if (!condition) throw std::runtime_error(message); +} + +class Pty final { +public: + Pty() + { + master = ::posix_openpt(O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC); + require(master >= 0, "Cannot create test PTY"); + if (::grantpt(master) != 0 || ::unlockpt(master) != 0) { + ::close(master); + master = -1; + throw std::runtime_error("Cannot initialize test PTY"); + } + const auto* name = ::ptsname(master); + if (!name) { + ::close(master); + master = -1; + throw std::runtime_error("Cannot resolve test PTY slave"); + } + slave = name; + require(slave.rfind("/dev/pts/", 0) == 0, "Test may only open its own PTY slave"); + } + + ~Pty() { if (master >= 0) ::close(master); } + Pty(const Pty&) = delete; + Pty& operator=(const Pty&) = delete; + + void disconnect() + { + if (master >= 0) ::close(master); + master = -1; + } + + int master{-1}; + std::string slave; +}; + +volatile std::sig_atomic_t signal_count = 0; + +void interrupted(int) +{ + ++signal_count; +} + +class SignalStorm final { +public: + SignalStorm() + { + signal_count = 0; + struct sigaction handler{}; + handler.sa_handler = interrupted; + ::sigemptyset(&handler.sa_mask); + require(::sigaction(SIGUSR1, &handler, &previous_) == 0, "Cannot install test signal handler"); + const auto target = ::pthread_self(); + worker_ = std::thread([this, target] { + // Bounded even if the transport under test accidentally restarts + // its timeout on every signal, so a regression cannot hang forever. + for (int count = 0; count < 500 && running_; ++count) { + ::pthread_kill(target, SIGUSR1); + std::this_thread::sleep_for(1ms); + } + }); + } + + ~SignalStorm() + { + running_ = false; + worker_.join(); + ::sigaction(SIGUSR1, &previous_, nullptr); + } + +private: + struct sigaction previous_{}; + std::atomic running_{true}; + std::thread worker_; +}; + +void testRawIoExclusiveAndRelease() +{ + Pty pty; + UsbHeadSerialTransport transport(500ms); + require(transport.open({pty.slave, 115200}), "Cannot open test PTY transport"); + require(transport.isOpen(), "Transport should be open"); + + termios2 options{}; + require(::ioctl(pty.master, TCGETS2, &options) == 0, "Cannot query PTY attributes"); + require(options.c_iflag == 0 && options.c_oflag == 0 && options.c_lflag == 0, + "PTY must be raw with no echo, translation or software flow control"); + require((options.c_cflag & CSIZE) == CS8 && !(options.c_cflag & (PARENB | CSTOPB | CRTSCTS)), + "PTY must use 8N1 without hardware flow control"); + require(options.c_ispeed == 115200 && options.c_ospeed == 115200, + "termios2 must retain the configured baud rate"); + const int competing = ::open(pty.slave.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK); + const int competing_error = errno; + int exclusive = 0; + if (competing >= 0) { + const int queried = ::ioctl(competing, TIOCGEXCL, &exclusive); + ::close(competing); + require(queried == 0 && exclusive, "USB head transport must acquire TIOCEXCL"); + } + // CAP_SYS_ADMIN can bypass TIOCEXCL. Run this test as the device user; + // checking TIOCGEXCL still verifies the flag when the test runs as root. + if (::geteuid() != 0) require(competing < 0 && competing_error == EBUSY, "A second open must be refused"); + + const std::vector expected{0, 10, 13, 17, 19, 127, 128, 255}; + require(::write(pty.master, expected.data(), expected.size()) == static_cast(expected.size()), + "Cannot send PTY test bytes"); + std::vector actual; + require(transport.read(expected.size(), 200ms, actual) && actual == expected, + "Raw serial input changed bytes"); + require(transport.write(expected), "Raw serial write failed"); + pollfd readable{pty.master, POLLIN, 0}; + require(::poll(&readable, 1, 500) > 0, "No serial output reached PTY master"); + std::uint8_t bytes[32]{}; + const auto count = ::read(pty.master, bytes, sizeof(bytes)); + require(count == static_cast(expected.size()) && + std::equal(expected.begin(), expected.end(), bytes), "Raw serial output changed bytes"); + + const std::uint8_t stale = 0x55; + require(::write(pty.master, &stale, 1) == 1, "Cannot send stale input"); + std::this_thread::sleep_for(5ms); + require(transport.flushInput(), "flushInput failed"); + require(!transport.read(1, 20ms, actual) && actual.empty(), "flushInput did not remove stale input"); + require(transport.close() && transport.close() && !transport.isOpen(), "Close must be idempotent"); + const int reopened = ::open(pty.slave.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK); + require(reopened >= 0, "Exclusive mode leaked after close"); + exclusive = 1; + const int queried = ::ioctl(reopened, TIOCGEXCL, &exclusive); + ::close(reopened); + require(queried == 0 && !exclusive, + "close must release TIOCNXCL while PTY master remains alive"); +} + +void testFragmentedInputAndReadDeadline() +{ + Pty pty; + UsbHeadSerialTransport transport(80ms); + require(transport.open({pty.slave, 115200}), "Cannot open read-deadline PTY"); + std::thread writer([&] { + const std::uint8_t first[] = {1, 2}; + const std::uint8_t last[] = {3, 4}; + ::write(pty.master, first, sizeof(first)); + std::this_thread::sleep_for(5ms); + ::write(pty.master, last, sizeof(last)); + }); + std::vector result; + const bool read_ok = transport.read(4, 500ms, result); + writer.join(); + require(read_ok && result == std::vector({1, 2, 3, 4}), + "Fragmented input did not complete"); + + const std::uint8_t prefix = 0x55; + require(::write(pty.master, &prefix, 1) == 1, "Cannot send partial reply"); + SignalStorm signals; + const auto started = Clock::now(); + require(!transport.read(16, 500ms, result), "Incomplete reply must time out"); + const auto elapsed = Clock::now() - started; + require(result == std::vector({prefix}), "Partial reply bytes were lost"); + require(signal_count > 0, "Read poll was not exercised under signals"); + require(elapsed >= 30ms && elapsed < 450ms, + "Read must honor the constructor budget without restarting after EINTR"); + require(!transport.lastError().empty(), "Read timeout must report an error"); +} + +void testWriteDeadlineUnderBackpressure() +{ + Pty pty; + UsbHeadSerialTransport transport(80ms); + require(transport.open({pty.slave, 115200}), "Cannot open write-deadline PTY"); + // Deliberately do not read the PTY master. This exceeds the kernel's TTY + // buffer and exercises nonblocking EAGAIN/POLLOUT rather than a fast write. + const std::vector oversized(4 * 1024 * 1024, 0x5a); + SignalStorm signals; + const auto started = Clock::now(); + require(!transport.write(oversized), "Backpressured write must time out"); + const auto elapsed = Clock::now() - started; + require(signal_count > 0, "Write poll was not exercised under signals"); + require(elapsed >= 30ms && elapsed < 450ms, + "Write must retain one deadline across EAGAIN and EINTR"); + require(!transport.lastError().empty(), "Write timeout must report an error"); +} + +void testShortRequestedTimeoutAndHangup() +{ + Pty pty; + UsbHeadSerialTransport transport(500ms); + require(transport.open({pty.slave, 115200}), "Cannot open hangup PTY"); + std::vector result; + const auto started = Clock::now(); + require(!transport.read(1, 25ms, result), "Short requested timeout was ignored"); + require(Clock::now() - started < 250ms, "Read exceeded the caller's shorter timeout"); + pty.disconnect(); + const auto disconnected = Clock::now(); + require(!transport.read(1, 500ms, result), "PTY hangup must fail read"); + require(Clock::now() - disconnected < 250ms, "Hangup must not poll until timeout"); + require(!transport.write({1, 2, 3}), "PTY hangup must fail write"); + require(transport.close(), "Disconnected PTY must still close cleanly"); +} + +void testValidationAndCleanup() +{ + UsbHeadSerialTransport transport(100ms); + require(!transport.open({"", 115200}) && !transport.isOpen(), "Empty port was accepted"); + require(!transport.open({"/dev/this-usb-head-test-does-not-exist", 115200}), "Missing port was accepted"); + Pty pty; + require(!transport.open({pty.slave, 0}) && !transport.isOpen(), "Invalid baud rate was accepted"); + require(transport.open({pty.slave, 115200}), "Validation leaked or locked the PTY"); + std::vector output{1}; + require(!transport.read(1, 0ms, output) && output.empty(), "Invalid read budget was accepted"); + require(!transport.read(65537, 20ms, output), "Unbounded read allocation was accepted"); + require(transport.close(), "Cleanup failed"); + require(!transport.read(1, 10ms, output) && !transport.write({1}), "Closed port accepted I/O"); +} + +} // namespace + +int main() +{ + try { + testRawIoExclusiveAndRelease(); + testFragmentedInputAndReadDeadline(); + testWriteDeadlineUnderBackpressure(); + testShortRequestedTimeoutAndHangup(); + testValidationAndCleanup(); + std::cout << "USB head local serial PTY tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/cmvr-es/manager/device_manager/CMakeLists.txt b/cmvr-es/manager/device_manager/CMakeLists.txt index c43db8d8..5dfc7e35 100644 --- a/cmvr-es/manager/device_manager/CMakeLists.txt +++ b/cmvr-es/manager/device_manager/CMakeLists.txt @@ -13,6 +13,7 @@ target_link_libraries(device_manager PRIVATE cmvr_es::device::microphone cmvr_es::device::dexhand cmvr::device::head_esp32 + cmvr::device::head_usb cmvr_es::device::motor_manager cmvr_es::device::arm cmvr_es::mujoco_viewer diff --git a/cmvr-es/manager/device_manager/src/device_factory.cpp b/cmvr-es/manager/device_manager/src/device_factory.cpp index 91086228..ed83b9d7 100644 --- a/cmvr-es/manager/device_manager/src/device_factory.cpp +++ b/cmvr-es/manager/device_manager/src/device_factory.cpp @@ -4,7 +4,7 @@ #include "manager/device_manager/include/device_factory.h" -#include "devices/biohead/biohead_esp32/include/biohead_esp32.h" +#include "devices/biohead/biohead_factory.h" #include "devices/agv/agv_factory.h" #include "devices/arm/robot_arm_factory.h" #include "devices/camera/camera_factory.h" @@ -283,9 +283,25 @@ DeviceFactory::DeviceFactory() }); registerCreator(config::DeviceConfigEntry::DEVICE_TYPE_BIO_HEAD_ROBOT, - [](const auto& entry) { - return createSingleDeviceRecord( - entry, [](const auto& root) -> decltype(auto) { return (root.bio_head()); }); + [](const auto& entry) -> DeviceRecord { + if (entry.config_file().empty()) { + CMVR_LOG(ERROR) << "[DeviceFactory]: BioHead config_file is required"; + return {}; + } + config::BioHeadRobotRootConfig root; + if (!cmvr::ConfigHelper::loadConfigFileSilent(entry.config_file(), root)) { + CMVR_LOG(ERROR) << "[DeviceFactory]: Read BioHead config failed"; + return {}; + } + const auto& cfg = root.bio_head(); + const auto id = resolveDeviceId(entry, cfg); + if (id.empty() || (!entry.id().empty() && cfg.id() != entry.id())) { + CMVR_LOG(ERROR) << "[DeviceFactory]: BioHead config ID mismatch"; + return {}; + } + auto device = BioHeadFactory::create(cfg); + if (!device) return {}; + return {id, device->kind(), device->typeName(), std::move(device)}; }); } diff --git a/cmvr-es/service/CMakeLists.txt b/cmvr-es/service/CMakeLists.txt index 7ab97be4..e3e446aa 100644 --- a/cmvr-es/service/CMakeLists.txt +++ b/cmvr-es/service/CMakeLists.txt @@ -7,6 +7,7 @@ add_library(service grpc/src/grpc_speaker_service.cpp grpc/src/grpc_microphone_service.cpp grpc/src/grpc_head_service.cpp + grpc/src/grpc_head_joint_service.cpp grpc/src/grpc_dexhand_service.cpp grpc/src/grpc_arm_service.cpp grpc/src/grpc_motor_service.cpp @@ -118,3 +119,14 @@ target_link_libraries(grpc_hlc_client_test fcl cmvr_es::device_manager ) + +if(BUILD_TESTING OR CMVR_HEAD_BUILD_TESTING) + enable_testing() + add_executable(grpc_head_joint_service_test + grpc/tests/grpc_head_joint_service_test.cpp) + target_link_libraries(grpc_head_joint_service_test PRIVATE + cmvr_es::service cmvr_es::device_manager cmvr_es::proto gtest gtest_main pthread) + add_test(NAME grpc_head_joint_service_test COMMAND grpc_head_joint_service_test) + set_tests_properties(grpc_head_joint_service_test PROPERTIES ENVIRONMENT + "LD_LIBRARY_PATH=${CMAKE_BINARY_DIR}:${CMAKE_SOURCE_DIR}/output/lib:${CMAKE_SOURCE_DIR}/dependency/${ARCH}/third_party/grpc/v1.76.0/lib") +endif() diff --git a/cmvr-es/service/grpc/include/grpc_head_service.h b/cmvr-es/service/grpc/include/grpc_head_service.h index 4b8b20c3..52cbfacd 100644 --- a/cmvr-es/service/grpc/include/grpc_head_service.h +++ b/cmvr-es/service/grpc/include/grpc_head_service.h @@ -2,6 +2,7 @@ #define BIO_HEAD_SERVICE_H #include "cmvr/api/biohead_service.grpc.pb.h" +#include "cmvr/api/head_joint_command.pb.h" #include "manager/device_manager/include/device_manager.h" #include "devices/biohead/abstract_biohead.h" @@ -12,6 +13,22 @@ namespace cmvr::service gRPCMBioHeadServiceImpl(); ~gRPCMBioHeadServiceImpl() override = default; + grpc::Status ControlHeadJoints(grpc::ServerContext* context, + const api::HeadJointCommand_Request* request, + api::HeadJointCommand_Feedback* response) override; + + grpc::Status GetHeadJointState(grpc::ServerContext* context, + const api::GetHeadJointStateCommand_Request* request, + api::GetHeadJointStateCommand_Feedback* response) override; + + grpc::Status SetHeadExpression(grpc::ServerContext* context, + const api::SetHeadExpressionCommand_Request* request, + api::SetHeadExpressionCommand_Feedback* response) override; + + grpc::Status PlayHeadExpression(grpc::ServerContext* context, + const api::PlayHeadExpressionCommand_Request* request, + api::PlayHeadExpressionCommand_Feedback* response) override; + grpc::Status SetExpression(grpc::ServerContext* context, const api::SetFacialExpression_Request* request, api::SetFacialExpression_Feedback* response) override; diff --git a/cmvr-es/service/grpc/src/grpc_head_joint_service.cpp b/cmvr-es/service/grpc/src/grpc_head_joint_service.cpp new file mode 100644 index 00000000..340021c0 --- /dev/null +++ b/cmvr-es/service/grpc/src/grpc_head_joint_service.cpp @@ -0,0 +1,402 @@ +#include "service/grpc/include/grpc_head_service.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common/base/grpc_utils.h" +#include "common/base/logging/logger.h" +#include "devices/biohead/abstract_joint_head.h" +#include "service/grpc/action/include/control_command_arbiter.h" +#include "service/grpc/action/include/control_command_guard.h" + +namespace cmvr::service { +namespace { + +template +grpc::Status failJointResponse(Response* response, const std::string& message) +{ + CMVR_LOG(ERROR) << "[gRPCMBioHeadServiceImpl] " << message; + auto* header = response->mutable_header(); + header->set_success(false); + header->set_error_message(message); + setCurrentTimestamp(header->mutable_timestamp()); + return grpc::Status::OK; +} + +template +grpc::Status checkJointContext(grpc::ServerContext* context, Response* response) +{ + if (!context) { + return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, + "Server context is missing"); + } + if (context->deadline() <= std::chrono::system_clock::now()) { + failJointResponse(response, "Head RPC deadline exceeded"); + return grpc::Status(grpc::StatusCode::DEADLINE_EXCEEDED, + "Head RPC deadline exceeded"); + } + if (context->IsCancelled()) { + failJointResponse(response, "Head RPC cancelled"); + return grpc::Status(grpc::StatusCode::CANCELLED, + "Head RPC cancelled"); + } + return grpc::Status::OK; +} + +std::shared_ptr getJointHead( + device::DeviceManager& manager, const std::string& id) +{ + if (id.empty()) { + throw std::invalid_argument("Head device_id is required"); + } + const auto biohead = manager.getDevice(id); + if (!biohead) { + throw std::invalid_argument("Biohead device not found: " + id); + } + auto head = std::dynamic_pointer_cast(biohead); + if (!head) { + throw std::invalid_argument( + "Head device does not support joint commands: " + id); + } + return head; +} + +device::HeadMotionMode toDeviceMode(const api::HeadJointCommand_Mode& mode) +{ + if (!mode.has_mode()) { + throw std::invalid_argument("Head motion mode is required"); + } + switch (mode.mode()) { + case api::HEAD_JOINT_MOTION_IMMEDIATE: + return device::HeadMotionMode::Immediate; + case api::HEAD_JOINT_MOTION_S_CURVE: + return device::HeadMotionMode::SCurve; + case api::HEAD_JOINT_MOTION_FOLLOW: + return device::HeadMotionMode::Follow; + default: + throw std::invalid_argument("Unknown head motion mode"); + } +} + +api::HeadJointCommandOutcome toProtoOutcome(device::HeadCommandOutcome outcome) +{ + switch (outcome) { + case device::HeadCommandOutcome::None: + return api::HEAD_JOINT_COMMAND_NONE; + case device::HeadCommandOutcome::Acknowledged: + return api::HEAD_JOINT_COMMAND_ACKNOWLEDGED; + case device::HeadCommandOutcome::Rejected: + return api::HEAD_JOINT_COMMAND_REJECTED; + case device::HeadCommandOutcome::Unknown: + return api::HEAD_JOINT_COMMAND_UNKNOWN; + } + throw std::logic_error("Invalid head driver command outcome"); +} + +template +void fillJointSuccess(Response* response) +{ + auto* header = response->mutable_header(); + header->set_success(true); + header->clear_error_message(); + setCurrentTimestamp(header->mutable_timestamp()); +} + +std::function expressionCancellation(grpc::ServerContext* context) +{ + return [context] { + return context->IsCancelled() + || context->deadline() <= std::chrono::system_clock::now(); + }; +} + +void checkExpressionDuration(double duration_s) +{ + if (!std::isfinite(duration_s) || duration_s < 0.2 || duration_s > 5.0) { + throw std::invalid_argument("Expression duration must be finite and in [0.2, 5.0] seconds"); + } +} + +template +std::vector decodeTargets( + const Targets& source, const device::AbstractJointHead& head, bool complete) +{ + const auto& configured = head.jointInfo(); + if (source.empty() || static_cast(source.size()) > configured.size() + || (complete && (configured.size() != 5 || source.size() != 5))) { + throw std::invalid_argument(complete + ? "An expression requires all five configured joint targets" + : "Invalid head target count"); + } + std::set configured_ids; + for (const auto& joint : configured) configured_ids.insert(joint.id); + std::set selected_ids; + std::vector targets; + targets.reserve(static_cast(source.size())); + for (const auto& target : source) { + if (target.id().empty() || !configured_ids.count(target.id())) { + throw std::invalid_argument("Unknown head joint: " + target.id()); + } + if (!selected_ids.insert(target.id()).second) { + throw std::invalid_argument("Duplicate head joint: " + target.id()); + } + if (!target.has_position_rad() || !std::isfinite(target.position_rad())) { + throw std::invalid_argument("A finite position_rad is required: " + target.id()); + } + targets.push_back({target.id(), target.position_rad()}); + } + if (complete && selected_ids != configured_ids) { + throw std::invalid_argument("Expression joint IDs must match the configured five joints"); + } + return targets; +} + +void validateExpressionSelector(const device::AbstractJointHead& head, + const std::string& selector, bool by_name) +{ + if (selector.empty()) { + throw std::invalid_argument("An expression ID or exact name is required"); + } + std::size_t matches = 0; + for (const auto& preset : head.expressions()) { + if ((by_name ? preset.name : preset.id) == selector) ++matches; + } + if (matches == 0) throw std::invalid_argument("Unknown expression selector: " + selector); + if (matches != 1) throw std::invalid_argument("Ambiguous expression selector: " + selector); +} + +} // namespace + +grpc::Status gRPCMBioHeadServiceImpl::ControlHeadJoints( + grpc::ServerContext* context, + const api::HeadJointCommand_Request* request, + api::HeadJointCommand_Feedback* response) +{ + if (!request || !response) { + return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, + "Head request and response are required"); + } + response->Clear(); + const auto context_status = checkJointContext(context, response); + if (!context_status.ok()) return context_status; + + if (!request->has_header()) { + return failJointResponse(response, "Head command header is required"); + } + auto control_lease = ControlCommandArbiter::instance().tryAcquireControl(); + if (!control_lease) return rejectControlCommand(response); + + try { + const auto head = getJointHead(dmgr_, request->header().device_id()); + // Check again after device lookup. Once a device transaction has started, + // its configured timeout applies; cancellation cannot undo sent commands. + const auto dispatch_status = checkJointContext(context, response); + if (!dispatch_status.ok()) return dispatch_status; + + switch (request->operation_case()) { + case api::HeadJointCommand_Request::kMove: { + head->moveJoints(decodeTargets(request->move().targets(), *head, false)); + break; + } + case api::HeadJointCommand_Request::kHome: + head->home(expressionCancellation(context)); + break; + case api::HeadJointCommand_Request::kMode: + head->setMotionMode(toDeviceMode(request->mode())); + break; + case api::HeadJointCommand_Request::kConstraints: { + const auto& limits = request->constraints(); + head->setMotionConstraints( + limits.id(), limits.max_velocity_rad_s(), + limits.max_acceleration_rad_s2(), limits.max_jerk_rad_s3()); + break; + } + case api::HeadJointCommand_Request::kPositionGain: + if (!request->position_gain().has_gain()) { + return failJointResponse(response, "Head position gain is required"); + } + head->setPositionGain(request->position_gain().id(), + request->position_gain().gain()); + break; + case api::HeadJointCommand_Request::kUpdatePeriod: + head->setUpdatePeriodMs(request->update_period().period_ms()); + break; + case api::HeadJointCommand_Request::kReconnect: + head->reconnect(); + break; + case api::HeadJointCommand_Request::kCancelExpression: + head->cancelExpression(); + break; + case api::HeadJointCommand_Request::OPERATION_NOT_SET: + default: + return failJointResponse(response, "A typed head operation is required"); + } + + fillJointSuccess(response); + CMVR_LOG(DEBUG) << "[gRPCMBioHeadServiceImpl] (ControlHeadJoints): success, id=" + << request->header().device_id(); + return grpc::Status::OK; + } catch (const std::exception& error) { + const auto context_status = checkJointContext(context, response); + if (!context_status.ok()) return context_status; + return failJointResponse(response, error.what()); + } +} + +grpc::Status gRPCMBioHeadServiceImpl::GetHeadJointState( + grpc::ServerContext* context, + const api::GetHeadJointStateCommand_Request* request, + api::GetHeadJointStateCommand_Feedback* response) +{ + if (!request || !response) { + return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, + "Head request and response are required"); + } + response->Clear(); + const auto context_status = checkJointContext(context, response); + if (!context_status.ok()) return context_status; + if (!request->has_header()) { + return failJointResponse(response, "Head state header is required"); + } + + try { + const auto head = getJointHead(dmgr_, request->header().device_id()); + const auto snapshot = head->jointState(); + response->set_connected(snapshot.connected); + response->set_last_command_outcome(toProtoOutcome(snapshot.last_command_outcome)); + response->set_last_error(snapshot.last_error); + response->set_position_feedback_available(false); + response->set_expression_baseline_ready(snapshot.expression_baseline_ready); + response->set_hardware_emergency_stop_available(false); + + for (const auto& joint : head->jointInfo()) { + auto* info = response->add_joint_info(); + info->set_id(joint.id); + info->set_min_position_rad(joint.min_position_rad); + info->set_max_position_rad(joint.max_position_rad); + info->set_home_position_rad(joint.home_position_rad); + } + for (const auto& joint : snapshot.joints) { + auto* target = response->add_targets(); + target->set_id(joint.id); + target->set_target_position_rad(joint.target_position_rad); + target->set_target_valid(joint.target_valid); + } + for (const auto& preset : head->expressions()) { + auto* info = response->add_expressions(); + info->set_expression_id(preset.id); + info->set_expression_name(preset.name); + for (const auto& joint : preset.targets) { + auto* target = info->add_targets(); + target->set_id(joint.id); + target->set_position_rad(joint.position_rad); + } + } + fillJointSuccess(response); + return grpc::Status::OK; + } catch (const std::exception& error) { + response->Clear(); + const auto context_status = checkJointContext(context, response); + if (!context_status.ok()) return context_status; + return failJointResponse(response, error.what()); + } +} + +grpc::Status gRPCMBioHeadServiceImpl::SetHeadExpression( + grpc::ServerContext* context, + const api::SetHeadExpressionCommand_Request* request, + api::SetHeadExpressionCommand_Feedback* response) +{ + if (!request || !response) { + return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, + "Head request and response are required"); + } + response->Clear(); + const auto context_status = checkJointContext(context, response); + if (!context_status.ok()) return context_status; + if (!request->has_header()) { + return failJointResponse(response, "Head expression header is required"); + } + auto control_lease = ControlCommandArbiter::instance().tryAcquireControl(); + if (!control_lease) return rejectControlCommand(response); + try { + checkExpressionDuration(request->transition_duration_s()); + const auto head = getJointHead(dmgr_, request->header().device_id()); + const auto targets = decodeTargets(request->targets(), *head, true); + const auto dispatch_status = checkJointContext(context, response); + if (!dispatch_status.ok()) return dispatch_status; + head->setExpression(targets, request->transition_duration_s(), + expressionCancellation(context)); + fillJointSuccess(response); + CMVR_LOG(DEBUG) << "[gRPCMBioHeadServiceImpl] (SetHeadExpression): frames acknowledged, id=" + << request->header().device_id(); + return grpc::Status::OK; + } catch (const std::exception& error) { + const auto context_status = checkJointContext(context, response); + if (!context_status.ok()) return context_status; + return failJointResponse(response, error.what()); + } +} + +grpc::Status gRPCMBioHeadServiceImpl::PlayHeadExpression( + grpc::ServerContext* context, + const api::PlayHeadExpressionCommand_Request* request, + api::PlayHeadExpressionCommand_Feedback* response) +{ + if (!request || !response) { + return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, + "Head request and response are required"); + } + response->Clear(); + const auto context_status = checkJointContext(context, response); + if (!context_status.ok()) return context_status; + if (!request->has_header()) { + return failJointResponse(response, "Head expression header is required"); + } + auto control_lease = ControlCommandArbiter::instance().tryAcquireControl(); + if (!control_lease) return rejectControlCommand(response); + try { + checkExpressionDuration(request->transition_duration_s()); + const auto head = getJointHead(dmgr_, request->header().device_id()); + std::string selector; + bool by_name; + switch (request->expression_case()) { + case api::PlayHeadExpressionCommand_Request::kExpressionId: + selector = request->expression_id(); + by_name = false; + break; + case api::PlayHeadExpressionCommand_Request::kExpressionName: + selector = request->expression_name(); + by_name = true; + break; + case api::PlayHeadExpressionCommand_Request::EXPRESSION_NOT_SET: + default: + return failJointResponse(response, "An expression ID or exact name is required"); + } + validateExpressionSelector(*head, selector, by_name); + const auto dispatch_status = checkJointContext(context, response); + if (!dispatch_status.ok()) return dispatch_status; + const auto preset = head->playExpression( + selector, by_name, request->transition_duration_s(), expressionCancellation(context)); + response->set_expression_id(preset.id); + response->set_expression_name(preset.name); + fillJointSuccess(response); + CMVR_LOG(DEBUG) << "[gRPCMBioHeadServiceImpl] (PlayHeadExpression): frames acknowledged, id=" + << request->header().device_id() << ", expression_id=" << preset.id; + return grpc::Status::OK; + } catch (const std::exception& error) { + response->Clear(); + const auto context_status = checkJointContext(context, response); + if (!context_status.ok()) return context_status; + return failJointResponse(response, error.what()); + } +} + +} // namespace cmvr::service diff --git a/cmvr-es/service/grpc/src/grpc_head_service.cpp b/cmvr-es/service/grpc/src/grpc_head_service.cpp index 26be6d69..fc54124a 100644 --- a/cmvr-es/service/grpc/src/grpc_head_service.cpp +++ b/cmvr-es/service/grpc/src/grpc_head_service.cpp @@ -1,5 +1,6 @@ #include "common/base/logging/logger.h" #include "../include/grpc_head_service.h" +#include "devices/biohead/abstract_joint_head.h" #include "cmvr/api/biohead_service.grpc.pb.h" #include "manager/device_manager/include/device_manager.h" @@ -26,6 +27,26 @@ grpc::Status failResponse(ResponseT* response, const std::string& message) { return grpc::Status::OK; } +// Only USB joint shortcuts use this cancellation mapping; legacy ESP32 +// response behavior remains unchanged. +template +grpc::Status checkJointShortcutContext(grpc::ServerContext* context, ResponseT* response) +{ + if (!context) { + failResponse(response, "Server context is missing"); + return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "Server context is missing"); + } + if (context->deadline() <= std::chrono::system_clock::now()) { + failResponse(response, "Head RPC deadline exceeded"); + return grpc::Status(grpc::StatusCode::DEADLINE_EXCEEDED, "Head RPC deadline exceeded"); + } + if (context->IsCancelled()) { + failResponse(response, "Head RPC cancelled"); + return grpc::Status(grpc::StatusCode::CANCELLED, "Head RPC cancelled"); + } + return grpc::Status::OK; +} + void logSuccess(const char* rpc_name, const std::string& device_id) { CMVR_LOG(DEBUG) << "[gRPCMBioHeadServiceImpl] (" << rpc_name << "): success, id=" << device_id; @@ -52,6 +73,9 @@ grpc::Status gRPCMBioHeadServiceImpl::SetExpression( return failResponse(response, "Biohead device not found: " + dev_id); } + if (std::dynamic_pointer_cast(robot)) { + return failResponse(response, "USB joint head requires ControlHeadJoints or SetHeadExpression"); + } FacialExpressionState& expression_state = robot->expression_state_; expression_state.left_eyebrow_outside_y = request->expression().eyebrow().left_outside_y(); @@ -132,6 +156,13 @@ grpc::Status gRPCMBioHeadServiceImpl::StreamExpression( return grpc::Status::OK; } + if (std::dynamic_pointer_cast(robot)) { + failResponse(&feedback_msg, + "USB joint head requires SetHeadExpression or PlayHeadExpression"); + stream->Write(feedback_msg); + return grpc::Status::OK; + } + // ✅ 重置紧急停止标志 robot->emergency_stop_requested = false; @@ -224,6 +255,11 @@ grpc::Status gRPCMBioHeadServiceImpl::GetSystemStatus( return failResponse(response, "Biohead device not found: " + dev_id); } + if (std::dynamic_pointer_cast(robot)) { + return failResponse(response, + "USB service 1 has no measured position feedback; use GetHeadJointState"); + } + response->mutable_header()->set_success(true); setCurrentTimestamp(response->mutable_header()->mutable_timestamp()); logSuccess("GetSystemStatus", dev_id); @@ -338,6 +374,7 @@ grpc::Status gRPCMBioHeadServiceImpl::Happy(grpc::ServerContext* context, const { auto control_lease = ControlCommandArbiter::instance().tryAcquireControl(); if (!control_lease) return rejectControlCommand(response); + bool joint_head_request = false; try { string dev_id = request->header().device_id(); auto robot = dmgr_.getDevice(dev_id); @@ -345,7 +382,18 @@ grpc::Status gRPCMBioHeadServiceImpl::Happy(grpc::ServerContext* context, const return failResponse(response, "Biohead device not found: " + dev_id); } - robot->expressionHappy(); // 停止执行 + if (const auto joint_head = std::dynamic_pointer_cast(robot)) { + joint_head_request = true; + const auto context_status = checkJointShortcutContext(context, response); + if (!context_status.ok()) return context_status; + const auto cancelled = [context] { + return context->IsCancelled() + || context->deadline() <= std::chrono::system_clock::now(); + }; + joint_head->playExpression("微笑", true, 0.6, cancelled); + } else { + robot->expressionHappy(); + } response->mutable_header()->set_success(true); setCurrentTimestamp(response->mutable_header()->mutable_timestamp()); @@ -353,6 +401,10 @@ grpc::Status gRPCMBioHeadServiceImpl::Happy(grpc::ServerContext* context, const return grpc::Status::OK; } catch (const exception& e) { + if (joint_head_request) { + const auto context_status = checkJointShortcutContext(context, response); + if (!context_status.ok()) return context_status; + } response->mutable_header()->set_success(false); response->mutable_header()->set_error_message(e.what()); setCurrentTimestamp(response->mutable_header()->mutable_timestamp()); @@ -364,6 +416,7 @@ grpc::Status gRPCMBioHeadServiceImpl::Surprise(grpc::ServerContext* context, con { auto control_lease = ControlCommandArbiter::instance().tryAcquireControl(); if (!control_lease) return rejectControlCommand(response); + bool joint_head_request = false; try { string dev_id = request->header().device_id(); auto robot = dmgr_.getDevice(dev_id); @@ -371,7 +424,18 @@ grpc::Status gRPCMBioHeadServiceImpl::Surprise(grpc::ServerContext* context, con return failResponse(response, "Biohead device not found: " + dev_id); } - robot->expressionSurprised(); // + if (const auto joint_head = std::dynamic_pointer_cast(robot)) { + joint_head_request = true; + const auto context_status = checkJointShortcutContext(context, response); + if (!context_status.ok()) return context_status; + const auto cancelled = [context] { + return context->IsCancelled() + || context->deadline() <= std::chrono::system_clock::now(); + }; + joint_head->playExpression("惊讶", true, 0.6, cancelled); + } else { + robot->expressionSurprised(); + } response->mutable_header()->set_success(true); setCurrentTimestamp(response->mutable_header()->mutable_timestamp()); @@ -379,6 +443,10 @@ grpc::Status gRPCMBioHeadServiceImpl::Surprise(grpc::ServerContext* context, con return grpc::Status::OK; } catch (const exception& e) { + if (joint_head_request) { + const auto context_status = checkJointShortcutContext(context, response); + if (!context_status.ok()) return context_status; + } response->mutable_header()->set_success(false); response->mutable_header()->set_error_message(e.what()); setCurrentTimestamp(response->mutable_header()->mutable_timestamp()); @@ -391,6 +459,7 @@ grpc::Status gRPCMBioHeadServiceImpl::ExpressionTired(grpc::ServerContext* conte { auto control_lease = ControlCommandArbiter::instance().tryAcquireControl(); if (!control_lease) return rejectControlCommand(response); + bool joint_head_request = false; try { string dev_id = request->header().device_id(); auto robot = dmgr_.getDevice(dev_id); @@ -398,7 +467,18 @@ grpc::Status gRPCMBioHeadServiceImpl::ExpressionTired(grpc::ServerContext* conte return failResponse(response, "Biohead device not found: " + dev_id); } - robot->expressionTired(); // 停止执行 + if (const auto joint_head = std::dynamic_pointer_cast(robot)) { + joint_head_request = true; + const auto context_status = checkJointShortcutContext(context, response); + if (!context_status.ok()) return context_status; + const auto cancelled = [context] { + return context->IsCancelled() + || context->deadline() <= std::chrono::system_clock::now(); + }; + joint_head->playExpression("疲倦", true, 0.6, cancelled); + } else { + robot->expressionTired(); + } response->mutable_header()->set_success(true); setCurrentTimestamp(response->mutable_header()->mutable_timestamp()); @@ -406,6 +486,10 @@ grpc::Status gRPCMBioHeadServiceImpl::ExpressionTired(grpc::ServerContext* conte return grpc::Status::OK; } catch (const exception& e) { + if (joint_head_request) { + const auto context_status = checkJointShortcutContext(context, response); + if (!context_status.ok()) return context_status; + } response->mutable_header()->set_success(false); response->mutable_header()->set_error_message(e.what()); setCurrentTimestamp(response->mutable_header()->mutable_timestamp()); @@ -419,6 +503,7 @@ grpc::Status gRPCMBioHeadServiceImpl::ExpressionAngry(grpc::ServerContext* conte { auto control_lease = ControlCommandArbiter::instance().tryAcquireControl(); if (!control_lease) return rejectControlCommand(response); + bool joint_head_request = false; try { string dev_id = request->header().device_id(); auto robot = dmgr_.getDevice(dev_id); @@ -426,7 +511,18 @@ grpc::Status gRPCMBioHeadServiceImpl::ExpressionAngry(grpc::ServerContext* conte return failResponse(response, "Biohead device not found: " + dev_id); } - robot->expressionAngry(); // 停止执行 + if (const auto joint_head = std::dynamic_pointer_cast(robot)) { + joint_head_request = true; + const auto context_status = checkJointShortcutContext(context, response); + if (!context_status.ok()) return context_status; + const auto cancelled = [context] { + return context->IsCancelled() + || context->deadline() <= std::chrono::system_clock::now(); + }; + joint_head->playExpression("生气", true, 0.6, cancelled); + } else { + robot->expressionAngry(); + } response->mutable_header()->set_success(true); setCurrentTimestamp(response->mutable_header()->mutable_timestamp()); @@ -434,6 +530,10 @@ grpc::Status gRPCMBioHeadServiceImpl::ExpressionAngry(grpc::ServerContext* conte return grpc::Status::OK; } catch (const exception& e) { + if (joint_head_request) { + const auto context_status = checkJointShortcutContext(context, response); + if (!context_status.ok()) return context_status; + } response->mutable_header()->set_success(false); response->mutable_header()->set_error_message(e.what()); setCurrentTimestamp(response->mutable_header()->mutable_timestamp()); diff --git a/cmvr-es/service/grpc/tests/grpc_head_joint_service_test.cpp b/cmvr-es/service/grpc/tests/grpc_head_joint_service_test.cpp new file mode 100644 index 00000000..2d54ff88 --- /dev/null +++ b/cmvr-es/service/grpc/tests/grpc_head_joint_service_test.cpp @@ -0,0 +1,564 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "devices/biohead/abstract_joint_head.h" +#include "manager/device_manager/include/device_manager.h" +#include "service/grpc/action/include/control_command_arbiter.h" +#include "service/grpc/include/grpc_head_service.h" + +namespace { + +using namespace std::chrono_literals; +namespace api = cmvr::api; +namespace device = cmvr::device; + +// This stand-in never opens a port or controls hardware. The tests exercise +// the real gRPC server, generated stub, service handlers and DeviceManager route. +class MockJointHead final : public device::AbstractJointHead { +public: + MockJointHead() + { + id_ = "test_usb_head"; + for (const char* id : {"eye_l_up", "eye_l_lower", "eye_l_v", "eye_l_h", "pwm8_local"}) { + info_.push_back({id, -1.5, 1.5, 0.0}); + state_.joints.push_back({id, 0.0, false}); + } + state_.connected = true; + const std::vector names{"中立", "微笑", "疲倦", "惊讶", "生气", "当前姿态"}; + for (std::size_t i = 0; i < names.size(); ++i) { + device::HeadExpressionPreset preset{"preset-" + std::to_string(i), names[i], {}}; + for (const auto& joint : info_) preset.targets.push_back({joint.id, 0.0}); + presets_.push_back(preset); + } + } + + std::string typeName() const override { return "MockJointHead"; } + const std::vector& jointInfo() const override { return info_; } + const std::vector& expressions() const override { return presets_; } + device::HeadJointSnapshot jointState() const override + { + std::lock_guard lock(mutex_); + return state_; + } + void moveJoints(const std::vector& targets) override + { + std::lock_guard lock(mutex_); + ++move_calls; + last_targets = targets; + } + void home(const std::function& cancelled = {}) override + { + if (cancelled && cancelled()) throw std::runtime_error("Home cancelled before dispatch"); + ++home_calls; + } + void setMotionMode(device::HeadMotionMode) override { ++mode_calls; } + void setMotionConstraints(const std::string&, double, double, double) override {} + void setPositionGain(const std::string&, double) override { ++gain_calls; } + void setUpdatePeriodMs(uint32_t) override {} + void reconnect() override + { + std::lock_guard lock(mutex_); + ++reconnect_calls; + state_.connected = true; + state_.expression_baseline_ready = false; + } + void cancelExpression() noexcept override + { + ++cancel_calls; + cancel_requested = true; + } + void setExpression(const std::vector& targets, + double duration, const std::function& cancelled) override + { + ++set_calls; + { + std::lock_guard lock(mutex_); + last_targets = targets; + last_duration = duration; + } + lease_seen = cmvr::service::ControlCommandArbiter::instance().activeControlCount() != 0; + callback_seen = static_cast(cancelled); + entered = true; + const auto deadline = std::chrono::steady_clock::now() + 1500ms; + while (true) { + const bool context_cancelled = cancelled && cancelled(); + if (context_cancelled || cancel_requested.load()) { + cancellation_seen = true; + throw std::runtime_error("Mock expression cancelled; no more host frames"); + } + if (!wait_for_cancel.load()) break; + if (std::chrono::steady_clock::now() >= deadline) { + throw std::runtime_error("Test cancellation was not observed in time"); + } + std::this_thread::sleep_for(1ms); + } + std::lock_guard lock(mutex_); + state_.expression_baseline_ready = true; + } + device::HeadExpressionPreset playExpression( + const std::string& selector, bool by_name, double duration, + const std::function& cancelled) override + { + ++play_calls; + for (const auto& preset : presets_) { + if ((by_name ? preset.name : preset.id) == selector) { + { + std::lock_guard lock(mutex_); + last_selector = selector; + } + setExpression(preset.targets, duration, cancelled); + return preset; + } + } + throw std::runtime_error("Mock received an unvalidated selector"); + } + void makeNameAmbiguous() { presets_[0].name = "微笑"; } + void setBaseline(bool ready) + { + std::lock_guard lock(mutex_); + state_.expression_baseline_ready = ready; + } + + std::atomic move_calls{0}, home_calls{0}, mode_calls{0}, gain_calls{0}; + std::atomic reconnect_calls{0}, cancel_calls{0}, set_calls{0}, play_calls{0}; + std::atomic wait_for_cancel{false}, cancel_requested{false}, entered{false}; + std::atomic cancellation_seen{false}, callback_seen{false}, lease_seen{false}; + std::vector last_targets; + std::string last_selector; + double last_duration{0}; + +private: + std::vector info_; + std::vector presets_; + mutable std::mutex mutex_; + device::HeadJointSnapshot state_; +}; + +class HeadJointRpcTest : public ::testing::Test { +protected: + void SetUp() override + { + cmvr::config::DeviceManagerConfig config; + auto& manager = device::DeviceManager::getInstance(config); + head_ = std::make_shared(); + manager.registerDevice(head_); + service_ = std::make_unique(); + grpc::ServerBuilder builder; + int port = 0; + builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port); + builder.RegisterService(service_.get()); + server_ = builder.BuildAndStart(); + ASSERT_TRUE(server_); + ASSERT_GT(port, 0); + channel_ = grpc::CreateChannel("127.0.0.1:" + std::to_string(port), + grpc::InsecureChannelCredentials()); + ASSERT_TRUE(channel_->WaitForConnected(std::chrono::system_clock::now() + 2s)); + stub_ = api::BioHeadService::NewStub(channel_); + } + void TearDown() override + { + if (server_) { + server_->Shutdown(std::chrono::system_clock::now() + 2s); + server_->Wait(); + } + stub_.reset(); + service_.reset(); + device::DeviceManager::destroyInstance(); + } + template + void address(Request& request) { request.mutable_header()->set_device_id(head_->id()); } + api::SetHeadExpressionCommand_Request expressionRequest(double duration = 0.2) + { + api::SetHeadExpressionCommand_Request request; + address(request); + request.set_transition_duration_s(duration); + for (const auto& joint : head_->jointInfo()) { + auto* target = request.add_targets(); + target->set_id(joint.id); + target->set_position_rad(0.0); + } + return request; + } + bool waitUntilEntered() + { + const auto until = std::chrono::steady_clock::now() + 1s; + while (!head_->entered.load() && std::chrono::steady_clock::now() < until) { + std::this_thread::sleep_for(1ms); + } + return head_->entered.load(); + } + std::shared_ptr head_; + std::unique_ptr service_; + std::unique_ptr server_; + std::shared_ptr channel_; + std::unique_ptr stub_; +}; + +TEST_F(HeadJointRpcTest, RejectsMissingHeaderOrDeviceIdBeforeDispatch) +{ + auto request = expressionRequest(); + request.clear_header(); + api::SetHeadExpressionCommand_Feedback response; + grpc::ClientContext context; + ASSERT_TRUE(stub_->SetHeadExpression(&context, request, &response).ok()); + EXPECT_FALSE(response.header().success()); + request.mutable_header()->set_device_id(""); + grpc::ClientContext second; + ASSERT_TRUE(stub_->SetHeadExpression(&second, request, &response).ok()); + EXPECT_FALSE(response.header().success()); + EXPECT_EQ(head_->set_calls, 0); +} + +TEST_F(HeadJointRpcTest, RejectsMissingZeroNonfiniteOrOutOfRangeDuration) +{ + for (double duration : {0.0, -1.0, 0.199, 5.001, + std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + auto request = expressionRequest(duration); + api::SetHeadExpressionCommand_Feedback response; + grpc::ClientContext context; + ASSERT_TRUE(stub_->SetHeadExpression(&context, request, &response).ok()); + EXPECT_FALSE(response.header().success()); + } + EXPECT_EQ(head_->set_calls, 0); + for (double duration : {0.2, 5.0}) { + auto request = expressionRequest(duration); + api::SetHeadExpressionCommand_Feedback response; + grpc::ClientContext context; + ASSERT_TRUE(stub_->SetHeadExpression(&context, request, &response).ok()); + EXPECT_TRUE(response.header().success()); + } + EXPECT_EQ(head_->set_calls, 2); +} + +TEST_F(HeadJointRpcTest, RequiresCompleteUniqueKnownTargetsWithExplicitFinitePositions) +{ + std::vector invalid; + auto request = expressionRequest(); + request.mutable_targets()->RemoveLast(); + invalid.push_back(request); + request = expressionRequest(); + request.mutable_targets(4)->set_id(request.targets(0).id()); + invalid.push_back(request); + request = expressionRequest(); + request.mutable_targets(4)->set_id("unknown"); + invalid.push_back(request); + request = expressionRequest(); + request.mutable_targets(4)->clear_position_rad(); + invalid.push_back(request); + request = expressionRequest(); + request.mutable_targets(4)->set_position_rad(std::numeric_limits::quiet_NaN()); + invalid.push_back(request); + for (const auto& input : invalid) { + api::SetHeadExpressionCommand_Feedback response; + grpc::ClientContext context; + ASSERT_TRUE(stub_->SetHeadExpression(&context, input, &response).ok()); + EXPECT_FALSE(response.header().success()); + } + EXPECT_EQ(head_->set_calls, 0); + request = expressionRequest(); + api::SetHeadExpressionCommand_Feedback response; + grpc::ClientContext context; + ASSERT_TRUE(stub_->SetHeadExpression(&context, request, &response).ok()); + EXPECT_TRUE(response.header().success()); + ASSERT_EQ(head_->last_targets.size(), 5); + EXPECT_DOUBLE_EQ(head_->last_targets[0].position_rad, 0.0); + EXPECT_TRUE(head_->callback_seen); + EXPECT_TRUE(head_->lease_seen); +} + +TEST_F(HeadJointRpcTest, SelectsExactChineseNameAndCanonicalIdWithoutFallback) +{ + for (bool by_name : {true, false}) { + api::PlayHeadExpressionCommand_Request request; + address(request); + request.set_transition_duration_s(0.6); + if (by_name) request.set_expression_name("微笑"); + else request.set_expression_id("preset-1"); + api::PlayHeadExpressionCommand_Feedback response; + grpc::ClientContext context; + ASSERT_TRUE(stub_->PlayHeadExpression(&context, request, &response).ok()); + EXPECT_TRUE(response.header().success()); + EXPECT_EQ(response.expression_id(), "preset-1"); + EXPECT_EQ(response.expression_name(), "微笑"); + } + EXPECT_EQ(head_->play_calls, 2); +} + +TEST_F(HeadJointRpcTest, RejectsUnknownMissingEmptyAndAmbiguousPresetSelectors) +{ + for (int variant = 0; variant < 4; ++variant) { + api::PlayHeadExpressionCommand_Request request; + address(request); + request.set_transition_duration_s(0.2); + if (variant == 0) request.set_expression_name("unknown"); + if (variant == 1) request.set_expression_id("unknown-id"); + if (variant == 2) request.set_expression_name(""); + api::PlayHeadExpressionCommand_Feedback response; + grpc::ClientContext context; + ASSERT_TRUE(stub_->PlayHeadExpression(&context, request, &response).ok()); + EXPECT_FALSE(response.header().success()); + EXPECT_TRUE(response.expression_id().empty()); + } + head_->makeNameAmbiguous(); + api::PlayHeadExpressionCommand_Request request; + address(request); + request.set_expression_name("微笑"); + request.set_transition_duration_s(0.2); + api::PlayHeadExpressionCommand_Feedback response; + grpc::ClientContext context; + ASSERT_TRUE(stub_->PlayHeadExpression(&context, request, &response).ok()); + EXPECT_FALSE(response.header().success()); + EXPECT_EQ(head_->play_calls, 0); +} + +TEST_F(HeadJointRpcTest, QueryReturnsSixConfiguredPresetsAndHonestFeedbackFlags) +{ + api::GetHeadJointStateCommand_Request request; + address(request); + api::GetHeadJointStateCommand_Feedback response; + grpc::ClientContext context; + ASSERT_TRUE(stub_->GetHeadJointState(&context, request, &response).ok()); + EXPECT_TRUE(response.header().success()); + EXPECT_TRUE(response.connected()); + EXPECT_EQ(response.joint_info_size(), 5); + ASSERT_EQ(response.expressions_size(), 6); + EXPECT_EQ(response.expressions(1).expression_name(), "微笑"); + ASSERT_EQ(response.expressions(1).targets_size(), 5); + EXPECT_TRUE(response.expressions(1).targets(0).has_position_rad()); + EXPECT_FALSE(response.expression_baseline_ready()); + EXPECT_FALSE(response.position_feedback_available()); + EXPECT_FALSE(response.hardware_emergency_stop_available()); + head_->setBaseline(true); + grpc::ClientContext second; + ASSERT_TRUE(stub_->GetHeadJointState(&second, request, &response).ok()); + EXPECT_TRUE(response.expression_baseline_ready()); +} + +TEST_F(HeadJointRpcTest, ControlDistinguishesMissingZeroValuesAndRejectsUnknownMode) +{ + api::HeadJointCommand_Request request; + address(request); + auto* target = request.mutable_move()->add_targets(); + target->set_id("eye_l_up"); + api::HeadJointCommand_Feedback response; + grpc::ClientContext first; + ASSERT_TRUE(stub_->ControlHeadJoints(&first, request, &response).ok()); + EXPECT_FALSE(response.header().success()); + target->set_position_rad(0.0); + grpc::ClientContext second; + ASSERT_TRUE(stub_->ControlHeadJoints(&second, request, &response).ok()); + EXPECT_TRUE(response.header().success()); + request.mutable_position_gain()->set_id("eye_l_up"); + grpc::ClientContext third; + ASSERT_TRUE(stub_->ControlHeadJoints(&third, request, &response).ok()); + EXPECT_FALSE(response.header().success()); + request.mutable_position_gain()->set_gain(0.0); + grpc::ClientContext fourth; + ASSERT_TRUE(stub_->ControlHeadJoints(&fourth, request, &response).ok()); + EXPECT_TRUE(response.header().success()); + request.mutable_mode()->set_mode(static_cast(999)); + grpc::ClientContext fifth; + ASSERT_TRUE(stub_->ControlHeadJoints(&fifth, request, &response).ok()); + EXPECT_FALSE(response.header().success()); + EXPECT_EQ(head_->move_calls, 1); + EXPECT_EQ(head_->gain_calls, 1); + EXPECT_EQ(head_->mode_calls, 0); +} + +TEST_F(HeadJointRpcTest, ReconnectIsExplicitAndDoesNotSendAMotion) +{ + api::HeadJointCommand_Request request; + address(request); + request.mutable_reconnect(); + api::HeadJointCommand_Feedback response; + grpc::ClientContext context; + ASSERT_TRUE(stub_->ControlHeadJoints(&context, request, &response).ok()); + EXPECT_TRUE(response.header().success()); + EXPECT_EQ(head_->reconnect_calls, 1); + EXPECT_EQ(head_->move_calls, 0); + EXPECT_EQ(head_->home_calls, 0); + EXPECT_EQ(head_->set_calls, 0); +} + +TEST_F(HeadJointRpcTest, CancelCommandCanInterruptAnActiveExpression) +{ + head_->wait_for_cancel = true; + auto request = expressionRequest(); + auto result = std::async(std::launch::async, [&] { + grpc::ClientContext context; + context.set_deadline(std::chrono::system_clock::now() + 2s); + api::SetHeadExpressionCommand_Feedback response; + const auto status = stub_->SetHeadExpression(&context, request, &response); + return status.ok() && !response.header().success(); + }); + ASSERT_TRUE(waitUntilEntered()); + api::HeadJointCommand_Request cancel; + address(cancel); + cancel.mutable_cancel_expression(); + api::HeadJointCommand_Feedback response; + grpc::ClientContext context; + ASSERT_TRUE(stub_->ControlHeadJoints(&context, cancel, &response).ok()); + EXPECT_TRUE(response.header().success()); + EXPECT_TRUE(result.get()); + EXPECT_EQ(head_->cancel_calls, 1); + EXPECT_TRUE(head_->cancellation_seen); + EXPECT_TRUE(head_->lease_seen); +} + +TEST_F(HeadJointRpcTest, DeadlineIsObservedInsideTheExpressionExecutor) +{ + head_->wait_for_cancel = true; + auto request = expressionRequest(); + api::SetHeadExpressionCommand_Feedback response; + grpc::ClientContext context; + context.set_deadline(std::chrono::system_clock::now() + 100ms); + const auto status = stub_->SetHeadExpression(&context, request, &response); + EXPECT_EQ(status.error_code(), grpc::StatusCode::DEADLINE_EXCEEDED); + const auto until = std::chrono::steady_clock::now() + 1s; + while (!head_->cancellation_seen.load() && std::chrono::steady_clock::now() < until) { + std::this_thread::sleep_for(1ms); + } + EXPECT_TRUE(head_->entered); + EXPECT_TRUE(head_->callback_seen); + EXPECT_TRUE(head_->cancellation_seen); + EXPECT_TRUE(head_->lease_seen); +} + +TEST_F(HeadJointRpcTest, LegacyNormalizedCallsRejectUsbBeforeMutatingOldState) +{ + head_->expression_state_.left_nose_y = 0.75f; + api::SetFacialExpression_Request request; + address(request); + request.mutable_expression()->mutable_nose()->set_left_y(0.25f); + api::SetFacialExpression_Feedback response; + grpc::ClientContext first; + ASSERT_TRUE(stub_->SetExpression(&first, request, &response).ok()); + EXPECT_FALSE(response.header().success()); + EXPECT_FLOAT_EQ(head_->expression_state_.left_nose_y, 0.75f); + + api::GetStatus_Request query; + address(query); + api::GetStatus_Feedback query_response; + grpc::ClientContext second; + ASSERT_TRUE(stub_->GetSystemStatus(&second, query, &query_response).ok()); + EXPECT_FALSE(query_response.header().success()); + + head_->emergency_stop_requested = true; + grpc::ClientContext third; + auto stream = stub_->StreamExpression(&third); + api::StreamFacialExpression_Request frame; + address(frame); + ASSERT_TRUE(stream->Write(frame)); + stream->WritesDone(); + api::StreamFacialExpression_Feedback feedback; + ASSERT_TRUE(stream->Read(&feedback)); + EXPECT_FALSE(feedback.header().success()); + EXPECT_FALSE(stream->Read(&feedback)); + EXPECT_TRUE(stream->Finish().ok()); + EXPECT_TRUE(head_->emergency_stop_requested); +} + +TEST_F(HeadJointRpcTest, LegacyUsbShortcutPreservesDeadlineStatus) +{ + head_->wait_for_cancel = true; + api::Happy_Request request; + address(request); + api::Happy_Feedback response; + grpc::ClientContext context; + context.set_deadline(std::chrono::system_clock::now() + 100ms); + const auto status = stub_->Happy(&context, request, &response); + EXPECT_EQ(status.error_code(), grpc::StatusCode::DEADLINE_EXCEEDED); + const auto until = std::chrono::steady_clock::now() + 1s; + while (!head_->cancellation_seen.load() && std::chrono::steady_clock::now() < until) { + std::this_thread::sleep_for(1ms); + } + EXPECT_TRUE(head_->entered); + EXPECT_TRUE(head_->callback_seen); + EXPECT_TRUE(head_->cancellation_seen); +} + +TEST_F(HeadJointRpcTest, LegacyShortcutsUseTheSameCancelablePresetExecutor) +{ + api::Happy_Request happy; address(happy); + api::Happy_Feedback happy_response; + grpc::ClientContext first; + ASSERT_TRUE(stub_->Happy(&first, happy, &happy_response).ok()); + EXPECT_TRUE(happy_response.header().success()); + EXPECT_EQ(head_->last_selector, "微笑"); + + api::Surprise_Request surprise; address(surprise); + api::Surprise_Feedback surprise_response; + grpc::ClientContext second; + ASSERT_TRUE(stub_->Surprise(&second, surprise, &surprise_response).ok()); + EXPECT_TRUE(surprise_response.header().success()); + EXPECT_EQ(head_->last_selector, "惊讶"); + + api::ExpressionTired_Request tired; address(tired); + api::ExpressionTired_Feedback tired_response; + grpc::ClientContext third; + ASSERT_TRUE(stub_->ExpressionTired(&third, tired, &tired_response).ok()); + EXPECT_TRUE(tired_response.header().success()); + EXPECT_EQ(head_->last_selector, "疲倦"); + + api::ExpressionAngry_Request angry; address(angry); + api::ExpressionAngry_Feedback angry_response; + grpc::ClientContext fourth; + ASSERT_TRUE(stub_->ExpressionAngry(&fourth, angry, &angry_response).ok()); + EXPECT_TRUE(angry_response.header().success()); + EXPECT_EQ(head_->last_selector, "生气"); + EXPECT_EQ(head_->play_calls, 4); + EXPECT_DOUBLE_EQ(head_->last_duration, 0.6); + EXPECT_TRUE(head_->callback_seen); + EXPECT_TRUE(head_->lease_seen); + + api::ExpressionSadness_Request sadness; address(sadness); + api::ExpressionSadness_Feedback sadness_response; + grpc::ClientContext fifth; + ASSERT_TRUE(stub_->ExpressionSadness(&fifth, sadness, &sadness_response).ok()); + EXPECT_FALSE(sadness_response.header().success()); + api::ExpressionYawn_Request yawn; address(yawn); + api::ExpressionYawn_Feedback yawn_response; + grpc::ClientContext sixth; + ASSERT_TRUE(stub_->ExpressionYawn(&sixth, yawn, &yawn_response).ok()); + EXPECT_FALSE(yawn_response.header().success()); + EXPECT_EQ(head_->play_calls, 4); +} + +TEST(HeadJointRpcSchema, KeepsAllLegacyRpcNamesAndTypes) +{ + const auto* service = google::protobuf::DescriptorPool::generated_pool() + ->FindServiceByName("cmvr.api.BioHeadService"); + ASSERT_NE(service, nullptr); + const std::vector> legacy{ + {"SetExpression", "SetFacialExpression"}, {"StreamExpression", "StreamFacialExpression"}, + {"GetSystemStatus", "GetStatus"}, {"EmergencyStop", "EmergencyStop"}, + {"SpeakStart", "SpeakStart"}, {"SpeakStop", "SpeakStop"}, {"Happy", "Happy"}, + {"Surprise", "Surprise"}, {"ExpressionTired", "ExpressionTired"}, + {"ExpressionAngry", "ExpressionAngry"}, {"ExpressionSadness", "ExpressionSadness"}, + {"ExpressionYawn", "ExpressionYawn"}}; + for (const auto& item : legacy) { + const auto* method = service->FindMethodByName(item.first); + ASSERT_NE(method, nullptr) << item.first; + EXPECT_EQ(method->input_type()->full_name(), "cmvr.api." + item.second + ".Request"); + EXPECT_EQ(method->output_type()->full_name(), "cmvr.api." + item.second + ".Feedback"); + const bool streaming = item.first == "StreamExpression"; + EXPECT_EQ(method->client_streaming(), streaming); + EXPECT_EQ(method->server_streaming(), streaming); + } +} + +} // namespace diff --git a/dependency/x86/third_party/erpc/v1.14.0/bin/erpcgen b/dependency/x86/third_party/erpc/v1.14.0/bin/erpcgen new file mode 100755 index 00000000..78ec6c6e Binary files /dev/null and b/dependency/x86/third_party/erpc/v1.14.0/bin/erpcgen differ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_arbitrated_client_manager.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_arbitrated_client_manager.hpp new file mode 100755 index 00000000..dc271345 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_arbitrated_client_manager.hpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__ARBITRATED_CLIENT_MANAGER_H_ +#define _EMBEDDED_RPC__ARBITRATED_CLIENT_MANAGER_H_ + +#include "erpc_client_manager.h" + +/*! + * @addtogroup infra_client + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { +class TransportArbitrator; + +/*! + * @brief Client that can share a transport with a server. + * + * This class is a special subclass of ClientManager that works with the TransportArbitrator + * to share a single transport with a Server. This enables, for instance, a single UART to + * be used for bidirectional remote function invocations and replies. + * + * The setTransport() method used on ClientManager is not used with this class. Instead, there + * is a setArbitrator() method. The underlying transport that is shared is set on the arbitrator. + * + * @ingroup infra_client + */ +class ArbitratedClientManager : public ClientManager +{ +public: + /*! + * @brief Constructor. + * + * This function initializes object attributes. + */ + ArbitratedClientManager(void) : ClientManager(), m_arbitrator(NULL) {} + + /*! + * @brief Sets the transport arbitrator instance. + * + * @param[in] arbitrator Transport arbitrator to use. + */ + void setArbitrator(TransportArbitrator *arbitrator); + + /*! + * @brief Gets the transport arbitrator instance. + * + * @return TransportArbitrator * Transport arbitrator instance. + */ + TransportArbitrator *getArbitrator(void) { return m_arbitrator; }; + +protected: + TransportArbitrator *m_arbitrator; //!< Optional transport arbitrator. May be NULL. + + /*! + * @brief This function performs request. + * + * Should be called in non server context (do not call another eRPC function in server + * remote call implementation). + * + * @param[in] request Request context to perform. + */ + virtual void performClientRequest(RequestContext &request) override; + + //! @brief This method is not used with this class. + void setTransport(Transport *transport) { (void)transport; } +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__ARBITRATED_CLIENT_MANAGER_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_arbitrated_client_setup.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_arbitrated_client_setup.h new file mode 100755 index 00000000..d8775d60 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_arbitrated_client_setup.h @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * Copyright 2019 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _ERPC_ARBITRATED_CLIENT_SETUP_H_ +#define _ERPC_ARBITRATED_CLIENT_SETUP_H_ + +#include "erpc_common.h" +#include "erpc_config_internal.h" +#include "erpc_mbf_setup.h" +#if ERPC_PRE_POST_ACTION +#include "erpc_pre_post_action.h" +#endif +#if ERPC_NESTED_CALLS +#include "erpc_server_setup.h" +#endif +#include "erpc_client_manager.h" +#include "erpc_transport_setup.h" + +/*! + * @addtogroup client_setup + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// API +//////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +//! @name Arbitrated client setup +//@{ + +/*! + * @brief Initializes a client that shares its transport with the server. + * + * This function initializes a client with all components necessary for sending client requests + * using the same transport instance as used by a server. Only one instance of the shared + * transport should be created. The transport arbitrator that wraps the shared transport is + * returned. This arbitrator, not the shared transport, should be passed to the server setup + * routine. + * + * Example use: + * @code + * erpc_transport_t arbitrator; + * erpc_transport_t sharedSerial = erpc_transport_serial_init(...); + * erpc_client_t client = erpc_arbitrated_client_init(sharedSerial, message_buffer_factory, &arbitrator); + * erpc_server_init(arbitrator); + * @endcode + * + * @param[in] transport Initiated transport. + * @param[in] message_buffer_factory Initiated message buffer factory. + * @param[out] arbitrator Transport arbitrator reference that should be passed to the server setup API. + * + * @return erpc_client_t Pointer to client structure. + */ +erpc_client_t erpc_arbitrated_client_init(erpc_transport_t transport, erpc_mbf_t message_buffer_factory, + erpc_transport_t *arbitrator); + +/*! + * @brief This function sets error handler function. + * + * Given error_handler function is called when error occur inside eRPC infrastructure. + * + * @param[in] client Pointer to client structure. + * @param[in] error_handler Pointer to function error handler. + */ +void erpc_arbitrated_client_set_error_handler(erpc_client_t client, client_error_handler_t error_handler); + +/*! + * @brief Can be used to set own crcStart number. + * + * For example can be used generated crc from erpcgen + * which is providing when @crc annotation is used. + * Accessed can be through 'extern const uint32_t erpc_generated_crc;' + * + * @param[in] client Pointer to client structure. + * @param[in] crcStart Set start number for crc. + */ +void erpc_arbitrated_client_set_crc(erpc_client_t client, uint32_t crcStart); + +#if ERPC_NESTED_CALLS +/*! + * @brief This function sets server object for handling nested eRPC calls. + * + * @param[in] client Pointer to client structure. + * @param[in] server Initiated server. + */ +void erpc_arbitrated_client_set_server(erpc_client_t client, erpc_server_t server); + +/*! + * @brief This function sets server thread id. + * + * @param[in] client Pointer to client structure. + * @param[in] serverThreadId Id of thread where server run function is executed. + */ +void erpc_arbitrated_client_set_server_thread_id(erpc_client_t client, void *serverThreadId); +#endif + +#if ERPC_MESSAGE_LOGGING +/*! + * @brief This function adds transport object for logging send/receive messages. + * + * @param[in] client Pointer to client structure. + * @param[in] transport Initiated transport. + * + * @retval True When transport was successfully added. + * @retval False When transport wasn't added. + */ +bool erpc_arbitrated_client_add_message_logger(erpc_client_t client, erpc_transport_t transport); +#endif + +#if ERPC_PRE_POST_ACTION +/*! + * @brief This function set callback function executed at the beginning of eRPC call. + * + * @param[in] client Pointer to client structure. + * @param[in] preCB Callback used at the beginning of eRPC call. When NULL and ERPC_PRE_POST_ACTION_DEFAULT + * is enabled then default function will be set. + */ +void erpc_arbitrated_client_add_pre_cb_action(erpc_client_t client, pre_post_action_cb preCB); + +/*! + * @brief This function set callback function executed at the end of eRPC call. + * + * @param[in] client Pointer to client structure. + * @param[in] postCB Callback used at the end of eRPC call. When NULL and ERPC_PRE_POST_ACTION_DEFAULT + * is enabled then default function will be set. + */ +void erpc_arbitrated_client_add_post_cb_action(erpc_client_t client, pre_post_action_cb postCB); +#endif + +/*! + * @brief This function de-initializes client. + * + * This function de-initializes client and all components which it own. + * + * @param[in] client Pointer to client structure. + */ +void erpc_arbitrated_client_deinit(erpc_client_t client); + +//@} + +#ifdef __cplusplus +} +#endif + +/*! @} */ + +#endif // _ERPC_ARBITRATED_CLIENT_SETUP_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_basic_codec.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_basic_codec.hpp new file mode 100755 index 00000000..3dc0faa9 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_basic_codec.hpp @@ -0,0 +1,381 @@ +/* + * Copyright (c) 2014, Freescale Semiconductor, Inc. + * Copyright 2016-2021 NXP + * Copyright 2021 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__BASIC_SERIALIZATION_H_ +#define _EMBEDDED_RPC__BASIC_SERIALIZATION_H_ + +#include "erpc_codec.hpp" + +/*! + * @addtogroup infra_codec + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { +/*! + * @brief Values of the uint8 flag prefixing nullable values. + */ +enum class null_flag_t +{ + kNotNull = 0, + kIsNull +}; + +/*! + * @brief Simple binary serialization format. + * + * @ingroup infra_codec + */ +class BasicCodec : public Codec +{ +public: + static const uint32_t kBasicCodecVersion; /*!< Codec version. */ + + /*! + * @brief Constructor. + */ + BasicCodec(void); + + /*! + * @brief CodecFactory destructor + */ + virtual ~BasicCodec(void); + + //! @name Encoding + //@{ + /*! + * @brief Prototype for write header of message. + * + * @param[in] type Type of message. + * @param[in] service Which interface is requested. + * @param[in] request Which function need be called. + * @param[in] sequence Send sequence number to be sure that + * received message is reply for current request. or write function. + */ + virtual void startWriteMessage(message_type_t type, uint32_t service, uint32_t request, uint32_t sequence) override; + + /*! + * @brief Prototype for write data stream. + * + * @param[in] length Size of data stream in bytes. + * @param[in] value Pointer to data stream. + */ + virtual void writeData(uint32_t length, const void *value); + + /*! + * @brief Prototype for write boolean value. + * + * @param[in] value Boolean typed value to write. + */ + virtual void write(bool value) override; + + /*! + * @brief Prototype for write int8_t value. + * + * @param[in] value int8_t typed value to write. + */ + virtual void write(int8_t value) override; + + /*! + * @brief Prototype for write int16_t value. + * + * @param[in] value int16_t typed value to write. + */ + virtual void write(int16_t value) override; + + /*! + * @brief Prototype for write int32_t value. + * + * @param[in] value int32_t typed value to write. + */ + virtual void write(int32_t value) override; + + /*! + * @brief Prototype for write int64_t value. + * + * @param[in] value int64_t typed value to write. + */ + virtual void write(int64_t value) override; + + /*! + * @brief Prototype for write uint8_t value. + * + * @param[in] value uint8_t typed value to write. + */ + virtual void write(uint8_t value) override; + + /*! + * @brief Prototype for write uint16_t value. + * + * @param[in] value uint16_t typed value to write. + */ + virtual void write(uint16_t value) override; + + /*! + * @brief Prototype for write uint32_t value. + * + * @param[in] value uint32_t typed value to write. + */ + virtual void write(uint32_t value) override; + + /*! + * @brief Prototype for write uint64_t value. + * + * @param[in] value uint64_t typed value to write. + */ + virtual void write(uint64_t value) override; + + /*! + * @brief Prototype for write float value. + * + * @param[in] value float typed value to write. + */ + virtual void write(float value) override; + + /*! + * @brief Prototype for write double value. + * + * @param[in] value double typed value to write. + */ + virtual void write(double value) override; + + /*! + * @brief Prototype for write uintptr value. + * + * @param[in] value uintptr typed value to write. + */ + virtual void writePtr(uintptr_t value) override; + + /*! + * @brief Prototype for write string value. + * + * @param[in] length of string. + * @param[in] value string value to write. + */ + virtual void writeString(uint32_t length, const char *value) override; + + /*! + * @brief Prototype for write binary value. + * + * @param[in] length of binary. + * @param[in] value Binary value to write. + */ + virtual void writeBinary(uint32_t length, const uint8_t *value) override; + + /*! + * @brief Prototype for start write list. + * + * @param[in] length Length of list. + */ + virtual void startWriteList(uint32_t length) override; + + /*! + * @brief Prototype for start write union. + * + * @param[in] discriminator Discriminator of union. + */ + virtual void startWriteUnion(int32_t discriminator) override; + + /*! + * @brief Writes a flag indicating whether the next value is null. + * + * @param[in] isNull Null flag to send. + */ + virtual void writeNullFlag(bool isNull) override; + //@} + + //! @name Decoding + //@{ + /*! + * @brief Prototype for read header of message. + * + * @param[out] type Type of message. + * @param[out] service Which interface was used. + * @param[out] request Which function was called. + * @param[out] sequence Returned sequence number to be sure that + * received message is reply for current request. + */ + virtual void startReadMessage(message_type_t &type, uint32_t &service, uint32_t &request, + uint32_t &sequence) override; + + /*! + * @brief Prototype for read data stream. + * + * @param[in] length Size of data stream in bytes to be read. + * @param[in] value Pointer to data stream to be read. + */ + virtual void readData(uint32_t length, void *value); + + /*! + * @brief Prototype for read boolean value. + * + * @param[out] value Boolean typed value to read. + */ + virtual void read(bool &value) override; + + /*! + * @brief Prototype for read int8_t value. + * + * @param[out] value int8_t typed value to read. + */ + virtual void read(int8_t &value) override; + + /*! + * @brief Prototype for read int16_t value. + * + * @param[out] value int16_t typed value to read. + */ + virtual void read(int16_t &value) override; + + /*! + * @brief Prototype for read int32_t value. + * + * @param[out] value int32_t typed value to read. + */ + virtual void read(int32_t &value) override; + + /*! + * @brief Prototype for read int64_t value. + * + * @param[out] value int64_t typed value to read. + */ + virtual void read(int64_t &value) override; + + /*! + * @brief Prototype for read uint8_t value. + * + * @param[out] value uint8_t typed value to read. + */ + virtual void read(uint8_t &value) override; + + /*! + * @brief Prototype for read uint16_t value. + * + * @param[out] value uint16_t typed value to read. + */ + virtual void read(uint16_t &value) override; + + /*! + * @brief Prototype for read uint32_t value. + * + * @param[out] value uint32_t typed value to read. + */ + virtual void read(uint32_t &value) override; + + /*! + * @brief Prototype for read uint64_t value. + * + * @param[out] value uint64_t typed value to read. + */ + virtual void read(uint64_t &value) override; + + /*! + * @brief Prototype for read float value. + * + * @param[out] value float typed value to read. + */ + virtual void read(float &value) override; + + /*! + * @brief Prototype for read double value. + * + * @param[out] value double typed value to read. + */ + virtual void read(double &value) override; + + /*! + * @brief Prototype for read uintptr value. + * + * @param[out] value uintptr typed value to read. + */ + virtual void readPtr(uintptr_t &value) override; + + /*! + * @brief Prototype for read string value. + * + * @param[out] length of string. + * @param[out] value String value to read. + */ + virtual void readString(uint32_t &length, char **value) override; + + /*! + * @brief Prototype for read binary value. + * + * @param[out] length of binary. 0 can be valid value or in case of error. + * @param[out] value Binary value to read. Null in case of error. + */ + virtual void readBinary(uint32_t &length, uint8_t **value) override; + + /*! + * @brief Prototype for start read list. + * + * @param[out] length Length of list. + */ + virtual void startReadList(uint32_t &length) override; + + /*! + * @brief Prototype for start read union. + * + * @param[in] discriminator Discriminator of union. + */ + virtual void startReadUnion(int32_t &discriminator) override; + + /*! + * @brief Reads a flag indicating whether the next value is null. + * + * @param[in] isNull Null flag to read. + */ + virtual void readNullFlag(bool &isNull) override; + //@} +}; + +/*! + * @brief Basic codec factory implements functions from codec factory. + * + * @ingroup infra_codec + */ +class BasicCodecFactory : public CodecFactory +{ +public: + /*! + * @brief Constructor. + */ + BasicCodecFactory(void); + + /*! + * @brief CodecFactory destructor + */ + virtual ~BasicCodecFactory(void); + + /*! + * @brief Return created codec. + * + * @return Pointer to created codec. + */ + virtual Codec *create(void) override; + + /*! + * @brief Dispose codec. + * + * @param[in] codec Codec to dispose. + */ + virtual void dispose(Codec *codec) override; +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__BASIC_SERIALIZATION_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_client_manager.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_client_manager.h new file mode 100755 index 00000000..63a8bd12 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_client_manager.h @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * Copyright 2020-2021 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__CLIENT_MANAGER_H_ +#define _EMBEDDED_RPC__CLIENT_MANAGER_H_ + +#ifdef __cplusplus +#include "erpc_client_server_common.hpp" +#if ERPC_NESTED_CALLS +#include "erpc_server.hpp" +#include "erpc_threading.h" +#endif + +/*! + * @addtogroup infra_client + * @{ + * @file + */ + +extern "C" { +#else +#include "erpc_common.h" +#endif + +typedef void (*client_error_handler_t)(erpc_status_t err, + uint32_t functionID); /*!< eRPC error handler function type. */ + +//! @brief Opaque client object type. +typedef struct ClientType *erpc_client_t; + +#ifdef __cplusplus +} + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { +class RequestContext; +#if ERPC_NESTED_CALLS +class Server; +#endif + +/*! + * @brief Base client implementation. + * + * @ingroup infra_client + */ +class ClientManager : public ClientServerCommon +{ +public: + /*! + * @brief Constructor. + * + * This function initializes object attributes. + */ + ClientManager(void) : + ClientServerCommon(), m_sequence(0), m_errorHandler(NULL) +#if ERPC_NESTED_CALLS + , + m_server(NULL), m_serverThreadId(NULL) +#endif + { + } + + /*! + * @brief ClientManager destructor + */ + virtual ~ClientManager(void) {} + + /*! + * @brief This function creates request context. + * + * @param[in] isOneway True if need send data only, else false. + */ + virtual RequestContext createRequest(bool isOneway); + + /*! + * @brief This function performs request. + * + * @param[in] request Request context to perform. + */ + virtual void performRequest(RequestContext &request); + + /*! + * @brief This function releases request context. + * + * @param[in] request Request context to release. + */ + virtual void releaseRequest(RequestContext &request); + + /*! + * @brief This function sets error handler function for infrastructure errors. + * + * @param[in] error_handler Pointer to error handler function. + */ + void setErrorHandler(client_error_handler_t error_handler) { m_errorHandler = error_handler; } + + /*! + * @brief This function calls error handler callback function with given status. + * + * Function is called in client shim code at the end of function when error occurred. + * + * @param[in] err Specify function status at the end of eRPC call. + * @param[in] functionID Specify eRPC function call. + */ + void callErrorHandler(erpc_status_t err, uint32_t functionID); + +#if ERPC_NESTED_CALLS + /*! + * @brief This function sets server used for nested calls. + * + * @param[in] server Server used for nested calls. + */ + void setServer(Server *server) { m_server = server; } + + /*! + * @brief This function sets server thread id. + * + * @param[in] serverThreadId Id of thread where server run function is executed. + */ + void setServerThreadId(Thread::thread_id_t serverThreadId) { m_serverThreadId = serverThreadId; } +#endif + +protected: + uint32_t m_sequence; //!< Sequence number. + client_error_handler_t m_errorHandler; //!< Pointer to function error handler. +#if ERPC_NESTED_CALLS + Server *m_server; //!< Server used for nested calls. + Thread::thread_id_t m_serverThreadId; //!< Thread in which server run function is called. +#endif + + /*! + * @brief This function performs request. + * + * Should be called in non server context (do not call another eRPC function in server + * remote call implementation). + * + * @param[in] request Request context to perform. + */ + virtual void performClientRequest(RequestContext &request); + +#if ERPC_NESTED_CALLS + /*! + * @brief This function performs nested request. + * + * Used when from eRPC function server implementation context is called new eRPC function. + * + * @param[in] request Request context to perform. + */ + virtual void performNestedClientRequest(RequestContext &request); +#endif + + //! @brief Validate that an incoming message is a reply. + virtual void verifyReply(RequestContext &request); + + /*! + * @brief Create message buffer and codec. + * + * The new codec is set to use the new message buffer. Both codec and buffer are allocated + * with the relevant factories. + * + * @return Pointer to created codec with message buffer. + */ + Codec *createBufferAndCodec(void); + +private: + ClientManager(const ClientManager &other); //!< Disable copy ctor. + ClientManager &operator=(const ClientManager &other); //!< Disable copy ctor. +}; + +/*! + * @brief Encapsulates all information about a request. + * + * @ingroup infra_client + */ +class RequestContext +{ +public: + /*! + * @brief Constructor. + * + * This function sets request context attributes. + * + * @param[in] sequence Sequence number. + * @param[in] codec Set in inout codec. + * @param[in] isOneway Set information if codec is only oneway or bidirectional. + */ + RequestContext(uint32_t sequence, Codec *codec, bool argIsOneway) : + m_sequence(sequence), m_codec(codec), m_oneway(argIsOneway) + { + } + + /*! + * @brief Get inout codec (for writing). + * + * @return Inout codec. + */ + Codec *getCodec(void) { return m_codec; } + + /*! + * @brief Get sequence number (be sure that reply belong to current request). + * + * @return Sequence number. + */ + uint32_t getSequence(void) const { return m_sequence; } + + /*! + * @brief Returns information if request context is oneway or not. + * + * @retval True when request context is oneway direction, else false. + */ + bool isOneway(void) const { return m_oneway; } + + /*! + * @brief Set request context to be oneway type (only send data). + * + * @return Set request context to be oneway. + */ + void setIsOneway(bool oneway) { m_oneway = oneway; } + +protected: + uint32_t m_sequence; //!< Sequence number. To be sure that reply belong to current request. + Codec *m_codec; //!< Inout codec. Codec for receiving and sending data. + bool m_oneway; //!< When true, request context will be oneway type (only send data). +}; + +} // namespace erpc + +/*! @} */ + +#endif + +#endif // _EMBEDDED_RPC__CLIENT_MANAGER_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_client_server_common.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_client_server_common.hpp new file mode 100755 index 00000000..159d3d8e --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_client_server_common.hpp @@ -0,0 +1,145 @@ +/* + * Copyright 2020 NXP + * Copyright 2020 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__CLIENTSERVERCOMMON_H_ +#define _EMBEDDED_RPC__CLIENTSERVERCOMMON_H_ + +#include "erpc_codec.hpp" +#include "erpc_config_internal.h" +#if ERPC_MESSAGE_LOGGING +#include "erpc_message_loggers.hpp" +#endif +#if ERPC_PRE_POST_ACTION +#include "erpc_pre_post_action.h" +#endif + +/*! + * @addtogroup infra_transport + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { + +/*! + * @brief Common class inherited by client and server class. + * + * @ingroup infra_utility + */ +class ClientServerCommon +#if ERPC_MESSAGE_LOGGING +#ifdef ERPC_OTHER_INHERITANCE + , +#else +#define ERPC_OTHER_INHERITANCE 1 +: +#endif + public MessageLoggers +#endif +#if ERPC_PRE_POST_ACTION +#ifdef ERPC_OTHER_INHERITANCE + , +#else +#define ERPC_OTHER_INHERITANCE 1 +: +#endif + public PrePostAction +#endif +{ +public: + /*! + * @brief ClientServerCommon constructor. + */ + ClientServerCommon(void) +#ifdef ERPC_OTHER_INHERITANCE +#undef ERPC_OTHER_INHERITANCE +#endif +#if ERPC_MESSAGE_LOGGING +#ifdef ERPC_OTHER_INHERITANCE + , +#else +#define ERPC_OTHER_INHERITANCE 1 + : +#endif + MessageLoggers() +#endif +#if ERPC_PRE_POST_ACTION +#ifdef ERPC_OTHER_INHERITANCE + , +#else +#define ERPC_OTHER_INHERITANCE 1 + : +#endif + PrePostAction() +#endif +#ifdef ERPC_OTHER_INHERITANCE + , +#else +#define ERPC_OTHER_INHERITANCE 1 + : +#endif + m_messageFactory(NULL), m_codecFactory(NULL), m_transport(NULL){}; + + /*! + * @brief ClientServerCommon destructor + */ + ~ClientServerCommon(void){}; + + /*! + * @brief This function sets message buffer factory to use. + * + * @param[in] factory Message buffer factory to use. + */ + void setMessageBufferFactory(MessageBufferFactory * factory) { m_messageFactory = factory; } + + /*! + * @brief This function sets codec factory to use. + * + * @param[in] factory Codec factory to use. + */ + void setCodecFactory(CodecFactory * factory) { m_codecFactory = factory; } + + /*! + * @brief This function sets codec factory to use. + * + * @return CodecFactory * Codec factory to use. + */ + CodecFactory *getCodecFactory(void) { return m_codecFactory; } + + /*! + * @brief This function sets transport layer to use. + * + * It also set messageBufferFactory to the same as in transport layer. + * + * @param[in] transport Transport layer to use. + */ + void setTransport(Transport * transport) { m_transport = transport; } + + /*! + * @brief This function gets transport instance. + * + * @return Transport * Pointer to transport instance. + */ + Transport *getTransport(void) { return m_transport; } + +protected: + MessageBufferFactory *m_messageFactory; //!< Message buffer factory to use. + CodecFactory *m_codecFactory; //!< Codec to use. + Transport *m_transport; //!< Transport layer to use. +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__CLIENTSERVERCOMMON_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_client_setup.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_client_setup.h new file mode 100755 index 00000000..825a022c --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_client_setup.h @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * Copyright 2019 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__CLIENT_SETUP_H_ +#define _EMBEDDED_RPC__CLIENT_SETUP_H_ + +#include "erpc_common.h" +#include "erpc_config_internal.h" +#include "erpc_mbf_setup.h" +#if ERPC_PRE_POST_ACTION +#include "erpc_pre_post_action.h" +#endif +#if ERPC_NESTED_CALLS +#include "erpc_server_setup.h" +#endif +#include "erpc_client_manager.h" +#include "erpc_transport_setup.h" + +/*! + * @addtogroup client_setup + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// API +//////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +//! @name Client setup +//@{ + +/*! + * @brief This function initializes client. + * + * This function initializes client with all components necessary for serve client request. + * + * @param[in] transport Initiated transport. + * @param[in] message_buffer_factory Initiated message buffer factory. + * + * @return erpc_client_t Pointer to client structure. + */ +erpc_client_t erpc_client_init(erpc_transport_t transport, erpc_mbf_t message_buffer_factory); + +/*! + * @brief This function sets error handler function. + * + * Given error_handler function is called when error occur inside eRPC infrastructure. + * + * @param[in] client Pointer to client structure. + * @param[in] error_handler Pointer to function error handler. + */ +void erpc_client_set_error_handler(erpc_client_t client, client_error_handler_t error_handler); + +/*! + * @brief Can be used to set own crcStart number. + * + * For example can be used generated crc from erpcgen + * which is providing when @crc annotation is used. + * Accessed can be through 'extern const uint32_t erpc_generated_crc;' + * + * @param[in] client Pointer to client structure. + * @param[in] crcStart Set start number for crc. + */ +void erpc_client_set_crc(erpc_client_t client, uint32_t crcStart); + +#if ERPC_NESTED_CALLS +/*! + * @brief This function sets server object for handling nested eRPC calls. + * + * @param[in] client Pointer to client structure. + * @param[in] server Initiated server. + */ +void erpc_client_set_server(erpc_client_t client, erpc_server_t server); + +/*! + * @brief This function sets server thread id. + * + * @param[in] client Pointer to client structure. + * @param[in] serverThreadId Id of thread where server run function is executed. + */ +void erpc_client_set_server_thread_id(erpc_client_t client, void *serverThreadId); +#endif + +#if ERPC_MESSAGE_LOGGING +/*! + * @brief This function adds transport object for logging send/receive messages. + * + * @param[in] client Pointer to client structure. + * @param[in] transport Initiated transport. + * + * @retval True When transport was successfully added. + * @retval False When transport wasn't added. + */ +bool erpc_client_add_message_logger(erpc_client_t client, erpc_transport_t transport); +#endif + +#if ERPC_PRE_POST_ACTION +/*! + * @brief This function set callback function executed at the beginning of eRPC call. + * + * @param[in] client Pointer to client structure. + * @param[in] preCB Callback used at the beginning of eRPC call. When NULL and ERPC_PRE_POST_ACTION_DEFAULT + * is enabled then default function will be set. + */ +void erpc_client_add_pre_cb_action(erpc_client_t client, pre_post_action_cb preCB); + +/*! + * @brief This function set callback function executed at the end of eRPC call. + * + * @param[in] client Pointer to client structure. + * @param[in] postCB Callback used at the end of eRPC call. When NULL and ERPC_PRE_POST_ACTION_DEFAULT + * is enabled then default function will be set. + */ +void erpc_client_add_post_cb_action(erpc_client_t client, pre_post_action_cb postCB); +#endif + +/*! + * @brief This function de-initializes client. + * + * This function de-initializes client and all components which it own. + * + * @param[in] client Pointer to client structure. + */ +void erpc_client_deinit(erpc_client_t client); + +//@} + +#ifdef __cplusplus +} +#endif + +/*! @} */ + +#endif // _EMBEDDED_RPC__CLIENT_SETUP_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_codec.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_codec.hpp new file mode 100755 index 00000000..763cb377 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_codec.hpp @@ -0,0 +1,440 @@ +/* + * Copyright (c) 2014, Freescale Semiconductor, Inc. + * Copyright 2016-2021 NXP + * Copyright 2021 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__CODEC_H_ +#define _EMBEDDED_RPC__CODEC_H_ + +#include "erpc_common.h" +#include "erpc_message_buffer.hpp" +#include "erpc_transport.hpp" + +#include +#include + +/*! + * @addtogroup infra_codec + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { +/*! + * @brief Types of messages that can be encoded. + */ +enum class message_type_t +{ + kInvocationMessage = 0, + kOnewayMessage, + kReplyMessage, + kNotificationMessage +}; + +typedef void *funPtr; // Pointer to functions +typedef funPtr *arrayOfFunPtr; // Pointer to array of functions + +/*! + * @brief Abstract serialization encoder/decoder interface. + * + * Codecs write to or read from a MessageBuffer. + * + * @ingroup infra_codec + */ +class Codec +{ +public: + /*! + * @brief Constructor. + * + * This function initializes object attributes. + */ + Codec(void) : m_cursor(), m_status(kErpcStatus_Success) {} + + /*! + * @brief Codec destructor + */ + virtual ~Codec(void) {} + + /*! + * @brief Return message buffer used for read and write data. + * + * @return Pointer to used message buffer. + */ + MessageBuffer getBuffer(void) { return m_cursor.getBuffer(); } + + MessageBuffer &getBufferRef(void) { return m_cursor.getBufferRef(); } + + /*! + * @brief Prototype for set message buffer used for read and write data. + * + * @param[in] buf Message buffer to set. + * @param[in] skip How many bytes to skip from reading. + */ + virtual void setBuffer(MessageBuffer &buf, uint8_t skip = 0) + { + m_cursor.setBuffer(buf, skip); + m_status = kErpcStatus_Success; + } + + /*! + * @brief Reset the codec to initial state. + * + * @param[in] skip How many bytes to skip from reading. + */ + virtual void reset(uint8_t skip = 0) + { + MessageBuffer buffer = m_cursor.getBuffer(); + m_cursor.setBuffer(buffer, skip); + m_status = kErpcStatus_Success; + } + + /*! + * @brief Return current status of eRPC message processing. + * + * @return Current status of eRPC message processing. + */ + erpc_status_t getStatus(void) { return m_status; } + + /*! + * @brief Return bool value representing current status. + * + * @retval True Current status value is kErpcStatus_Success. + * @retval False Current status is other than kErpcStatus_Success. + */ + bool isStatusOk(void) { return (m_status == kErpcStatus_Success); } + + /*! + * @brief Set current status of eRPC message processing to given value. + * + * @param[in] status New current value. + */ + void updateStatus(erpc_status_t status) + { + if (isStatusOk()) + { + m_status = status; + } + } + + //! @name Encoding + //@{ + /*! + * @brief Prototype for write header of message. + * + * @param[in] type Type of message. + * @param[in] service Which interface is requested. + * @param[in] request Which function need be called. + * @param[in] sequence Send sequence number to be sure that + * received message is reply for current request. + */ + virtual void startWriteMessage(message_type_t type, uint32_t service, uint32_t request, uint32_t sequence) = 0; + + /*! + * @brief Prototype for write boolean value. + * + * @param[in] value Boolean typed value to write. + */ + virtual void write(bool value) = 0; + + /*! + * @brief Prototype for write int8_t value. + * + * @param[in] value int8_t typed value to write. + */ + virtual void write(int8_t value) = 0; + + /*! + * @brief Prototype for write int16_t value. + * + * @param[in] value int16_t typed value to write. + */ + virtual void write(int16_t value) = 0; + + /*! + * @brief Prototype for write int32_t value. + * + * @param[in] value int32_t typed value to write. + */ + virtual void write(int32_t value) = 0; + + /*! + * @brief Prototype for write int64_t value. + * + * @param[in] value int64_t typed value to write. + */ + virtual void write(int64_t value) = 0; + + /*! + * @brief Prototype for write uint8_t value. + * + * @param[in] value uint8_t typed value to write. + */ + virtual void write(uint8_t value) = 0; + + /*! + * @brief Prototype for write uint16_t value. + * + * @param[in] value uint16_t typed value to write. + */ + virtual void write(uint16_t value) = 0; + + /*! + * @brief Prototype for write uint32_t value. + * + * @param[in] value uint32_t typed value to write. + */ + virtual void write(uint32_t value) = 0; + + /*! + * @brief Prototype for write uint64_t value. + * + * @param[in] value uint64_t typed value to write. + */ + virtual void write(uint64_t value) = 0; + + /*! + * @brief Prototype for write float value. + * + * @param[in] value float typed value to write. + */ + virtual void write(float value) = 0; + + /*! + * @brief Prototype for write double value. + * + * @param[in] value double typed value to write. + */ + virtual void write(double value) = 0; + + /*! + * @brief Prototype for write uintptr value. + * + * @param[in] value uintptr typed value to write. + */ + virtual void writePtr(uintptr_t value) = 0; + + /*! + * @brief Prototype for write string value. + * + * @param[in] length of string. + * @param[in] value string value to write. + */ + virtual void writeString(uint32_t length, const char *value) = 0; + + /*! + * @brief Prototype for write binary value. + * + * @param[in] length of binary. + * @param[in] value Binary value to write. + */ + virtual void writeBinary(uint32_t length, const uint8_t *value) = 0; + + /*! + * @brief Prototype for start write list. + * + * @param[in] length Length of list. + */ + virtual void startWriteList(uint32_t length) = 0; + + /*! + * @brief Prototype for start write union. + * + * @param[in] discriminator Discriminator of union. + */ + virtual void startWriteUnion(int32_t discriminator) = 0; + + /*! + * @brief Writes a flag indicating whether the next value is null. + * + * @param[in] isNull Null flag to send. + */ + virtual void writeNullFlag(bool isNull) = 0; + //@} + + //! @name Decoding + //@{ + /*! + * @brief Prototype for read header of message. + * + * @param[in] type Type of message. + * @param[in] service Which interface was used. + * @param[in] request Which function was called. + * @param[in] sequence Returned sequence number to be sure that + * received message is reply for current request. + */ + virtual void startReadMessage(message_type_t &type, uint32_t &service, uint32_t &request, uint32_t &sequence) = 0; + + /*! + * @brief Prototype for read boolean value. + * + * @param[in] value Boolean typed value to read. + */ + virtual void read(bool &value) = 0; + + /*! + * @brief Prototype for read int8_t value. + * + * @param[in] value int8_t typed value to read. + */ + virtual void read(int8_t &value) = 0; + + /*! + * @brief Prototype for read int16_t value. + * + * @param[in] value int16_t typed value to read. + */ + virtual void read(int16_t &value) = 0; + + /*! + * @brief Prototype for read int32_t value. + * + * @param[in] value int32_t typed value to read. + */ + virtual void read(int32_t &value) = 0; + + /*! + * @brief Prototype for read int64_t value. + * + * @param[in] value int64_t typed value to read. + */ + virtual void read(int64_t &value) = 0; + + /*! + * @brief Prototype for read uint8_t value. + * + * @param[in] value uint8_t typed value to read. + */ + virtual void read(uint8_t &value) = 0; + + /*! + * @brief Prototype for read uint16_t value. + * + * @param[in] value uint16_t typed value to read. + */ + virtual void read(uint16_t &value) = 0; + + /*! + * @brief Prototype for read uint32_t value. + * + * @param[in] value uint32_t typed value to read. + */ + virtual void read(uint32_t &value) = 0; + + /*! + * @brief Prototype for read uint64_t value. + * + * @param[in] value uint64_t typed value to read. + */ + virtual void read(uint64_t &value) = 0; + + /*! + * @brief Prototype for read float value. + * + * @param[in] value float typed value to read. + */ + virtual void read(float &value) = 0; + + /*! + * @brief Prototype for read double value. + * + * @param[in] value double typed value to read. + */ + virtual void read(double &value) = 0; + + /*! + * @brief Prototype for read uintptr value. + * + * @param[in] value uintptr typed value to read. + */ + virtual void readPtr(uintptr_t &value) = 0; + + /*! + * @brief Prototype for read string value. + * + * @param[in] length of string. + * @param[in] value String value to read. + */ + virtual void readString(uint32_t &length, char **value) = 0; + + /*! + * @brief Prototype for read binary value. + * + * @param[out] length of binary. 0 can be valid value or in case of error. + * @param[out] value Binary value to read. Null in case of error. + */ + virtual void readBinary(uint32_t &length, uint8_t **value) = 0; + + /*! + * @brief Prototype for start read list. + * + * @param[in] length Length of list. + */ + virtual void startReadList(uint32_t &length) = 0; + + /*! + * @brief Prototype for start read union. + * + * @param[in] discriminator Discriminator of union. + */ + virtual void startReadUnion(int32_t &discriminator) = 0; + + /*! + * @brief Reads a flag indicating whether the next value is null. + * + * @param[in] isNull Null flag to read. + */ + virtual void readNullFlag(bool &isNull) = 0; + +protected: + Cursor m_cursor; /*!< Copy data to message buffers. */ + erpc_status_t m_status; /*!< Status of serialized data. */ +}; + +/*! + * @brief Abstract interface for codec factory. + * + * @ingroup infra_codec + */ +class CodecFactory +{ +public: + /*! + * @brief Constructor. + */ + CodecFactory(void) {} + + /*! + * @brief CodecFactory destructor + */ + virtual ~CodecFactory(void) {} + + /*! + * @brief Return created codec. + * + * @return Pointer to created codec. + */ + virtual Codec *create(void) = 0; + + /*! + * @brief Dispose codec. + * + * @param[in] codec Codec to dispose. + */ + virtual void dispose(Codec *codec) = 0; +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__CODEC_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_common.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_common.h new file mode 100755 index 00000000..4ae2597f --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_common.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2015-2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * Copyright 2021 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__ERPC_COMMON_H_ +#define _EMBEDDED_RPC__ERPC_COMMON_H_ + +/*! + * @addtogroup infra + * @{ + */ + +//////////////////////////////////////////////////////////////////////////////// +// Definitions +//////////////////////////////////////////////////////////////////////////////// + +/*! @brief eRPC status return codes. */ +enum _erpc_status +{ + //! No error occurred. + kErpcStatus_Success = 0, + + //! Generic failure. + kErpcStatus_Fail = 1, + + //! Argument is an invalid value. + kErpcStatus_InvalidArgument = 4, + + //! Operated timed out. + kErpcStatus_Timeout = 5, + + //! Message header contains an unknown version. + kErpcStatus_InvalidMessageVersion = 6, + + //! Expected a reply message but got another message type. + kErpcStatus_ExpectedReply, + + //! Message is corrupted. + kErpcStatus_CrcCheckFailed, + + //! Attempt to read or write past the end of a buffer. + kErpcStatus_BufferOverrun, + + //! Could not find host with given name. + kErpcStatus_UnknownName, + + //! Failed to connect to host. + kErpcStatus_ConnectionFailure, + + //! Connected closed by peer. + kErpcStatus_ConnectionClosed, + + //! Memory allocation error. + kErpcStatus_MemoryError, + + //! Server is stopped. + kErpcStatus_ServerIsDown, + + //! Transport layer initialization failed. + kErpcStatus_InitFailed, + + //! Failed to receive data. + kErpcStatus_ReceiveFailed, + + //! Failed to send data. + kErpcStatus_SendFailed, + + //! Sending/Receiving callback function which is not defined in IDL. + kErpcStatus_UnknownCallback, + + //! Calling eRPC function from another eRPC function. For more information see erpc_common.h. + kErpcStatus_NestedCallFailure, + + //! When sending address from bigger architecture to smaller. + kErpcStatus_BadAddressScale +}; + +/*! @brief Type used for all status and error return values. */ +typedef enum _erpc_status erpc_status_t; + +/*! @} */ + +#endif /* _EMBEDDED_RPC__ERPC_COMMON_H_ */ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_config.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_config.h new file mode 100755 index 00000000..279665f3 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_config.h @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2020 NXP + * Copyright 2020-2021 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _ERPC_CONFIG_H_ +#define _ERPC_CONFIG_H_ + +/*! + * @addtogroup config + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Declarations +//////////////////////////////////////////////////////////////////////////////// + +//! @name Threading model options +//@{ +#define ERPC_ALLOCATION_POLICY_DYNAMIC (0U) //!< Dynamic allocation policy +#define ERPC_ALLOCATION_POLICY_STATIC (1U) //!< Static allocation policy + +#define ERPC_THREADS_NONE (0U) //!< No threads. +#define ERPC_THREADS_PTHREADS (1U) //!< POSIX pthreads. +#define ERPC_THREADS_FREERTOS (2U) //!< FreeRTOS. +#define ERPC_THREADS_ZEPHYR (3U) //!< ZEPHYR. +#define ERPC_THREADS_MBED (4U) //!< Mbed OS +#define ERPC_THREADS_WIN32 (5U) //!< WIN32 +#define ERPC_THREADS_THREADX (6U) //!< THREADX + +#define ERPC_NOEXCEPT_DISABLED (0U) //!< Disabling noexcept feature. +#define ERPC_NOEXCEPT_ENABLED (1U) //!< Enabling noexcept feature. + +#define ERPC_NESTED_CALLS_DISABLED (0U) //!< No nested calls support. +#define ERPC_NESTED_CALLS_ENABLED (1U) //!< Nested calls support. + +#define ERPC_NESTED_CALLS_DETECTION_DISABLED (0U) //!< Nested calls detection disabled. +#define ERPC_NESTED_CALLS_DETECTION_ENABLED (1U) //!< Nested calls detection enabled. + +#define ERPC_MESSAGE_LOGGING_DISABLED (0U) //!< Trace functions disabled. +#define ERPC_MESSAGE_LOGGING_ENABLED (1U) //!< Trace functions enabled. + +#define ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED (0U) //!< Do not use MCMGR for MU ISR management. +#define ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED (1U) //!< Use MCMGR for MU ISR management. + +#define ERPC_PRE_POST_ACTION_DISABLED (0U) //!< Pre post shim callbacks functions disabled. +#define ERPC_PRE_POST_ACTION_ENABLED (1U) //!< Pre post shim callback functions enabled. + +#define ERPC_PRE_POST_ACTION_DEFAULT_DISABLED (0U) //!< Pre post shim default callbacks functions disabled. +#define ERPC_PRE_POST_ACTION_DEFAULT_ENABLED (1U) //!< Pre post shim default callback functions enabled. +//@} + +#ifdef MCUXPRESSO_SDK +#include "erpc_config_gen.h" +#endif /* MCUXPRESSO_SDK */ + +//! @name Configuration options +//@{ + +//! @def ERPC_ALLOCATION_POLICY +//! +//! @brief Choose which allocation policy should be used. +//! +//! Set ERPC_ALLOCATION_POLICY_DYNAMIC if dynamic allocations should be used. +//! Set ERPC_ALLOCATION_POLICY_STATIC if static allocations should be used. +//! +//! Default value is ERPC_ALLOCATION_POLICY_DYNAMIC or in case of FreeRTOS it can be auto-detected if __has_include() is +//! supported by compiler. Uncomment comment bellow to use static allocation policy. In case of static implementation +//! user need consider another values to set (ERPC_CODEC_COUNT, ERPC_MESSAGE_LOGGERS_COUNT, +//! ERPC_CLIENTS_THREADS_AMOUNT). +// #define ERPC_ALLOCATION_POLICY (ERPC_ALLOCATION_POLICY_STATIC) + +//! @def ERPC_CODEC_COUNT +//! +//! @brief Set amount of codecs objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. For example if client or server is used in one thread then 1. If both are used in one +//! thread per each then 2, ... Default value 2. +// #define ERPC_CODEC_COUNT (2U) + +//! @def ERPC_MESSAGE_LOGGERS_COUNT +//! +//! @brief Set amount of message loggers objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. +//! For example if client or server is used in one thread then 1. If both are used in one thread per each then 2, ... +//! For arbitrated client 1 is enough. +//! Default value 0 (May not be used). +// #define ERPC_MESSAGE_LOGGERS_COUNT (0U) + +//! @def ERPC_CLIENTS_THREADS_AMOUNT +//! +//! @brief Set amount of client threads objects used in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. Default value 1 (Most of current cases). +// #define ERPC_CLIENTS_THREADS_AMOUNT (1U) + +//! @def ERPC_THREADS +//! +//! @brief Select threading model. +//! +//! Set to one of the @c ERPC_THREADS_x macros to specify the threading model used by eRPC. +//! +//! Leave commented out to attempt to auto-detect. Auto-detection works well for pthreads. +//! FreeRTOS can be detected when building with compilers that support __has_include(). +//! Otherwise, the default is no threading. +//#define ERPC_THREADS (ERPC_THREADS_FREERTOS) + +//! @def ERPC_DEFAULT_BUFFER_SIZE +//! +//! Uncomment to change the size of buffers allocated by one of MessageBufferFactory. +//! (@ref client_setup and @ref server_setup). The default size is set to 256. +//! For RPMsg transport layer, ERPC_DEFAULT_BUFFER_SIZE must be 2^n - 16. +//#define ERPC_DEFAULT_BUFFER_SIZE (256U) + +//! @def ERPC_DEFAULT_BUFFERS_COUNT +//! +//! Uncomment to change the count of buffers allocated by one of statically allocated messages. +//! Default value is set to 2. +//#define ERPC_DEFAULT_BUFFERS_COUNT (2U) + +//! @def ERPC_NOEXCEPT +//! +//! @brief Disable/enable noexcept support. +//! +//! Uncomment for using noexcept feature. +//#define ERPC_NOEXCEPT (ERPC_NOEXCEPT_ENABLED) + +//! @def ERPC_NESTED_CALLS +//! +//! Default set to ERPC_NESTED_CALLS_DISABLED. Uncomment when callbacks, or other eRPC +//! functions are called from server implementation of another eRPC call. Nested functions +//! need to be marked as @nested in IDL. +//#define ERPC_NESTED_CALLS (ERPC_NESTED_CALLS_ENABLED) + +//! @def ERPC_NESTED_CALLS_DETECTION +//! +//! Default set to ERPC_NESTED_CALLS_DETECTION_ENABLED when NDEBUG macro is presented. +//! This serve for locating nested calls in code. Nested calls are calls where inside eRPC function +//! on server side is called another eRPC function (like callbacks). Code need be a bit changed +//! to support nested calls. See ERPC_NESTED_CALLS macro. +//#define ERPC_NESTED_CALLS_DETECTION (ERPC_NESTED_CALLS_DETECTION_DISABLED) + +//! @def ERPC_MESSAGE_LOGGING +//! +//! Enable eRPC message logging code through the eRPC. Take look into "erpc_message_loggers.h". Can be used for base +//! printing messages, or sending data to another system for data analysis. Default set to +//! ERPC_MESSAGE_LOGGING_DISABLED. +//! +//! Uncomment for using logging feature. +//#define ERPC_MESSAGE_LOGGING (ERPC_MESSAGE_LOGGING_ENABLED) + +//! @def ERPC_TRANSPORT_MU_USE_MCMGR +//! +//! @brief MU transport layer configuration. +//! +//! Set to one of the @c ERPC_TRANSPORT_MU_USE_MCMGR_x macros to configure the MCMGR usage in MU transport layer. +//! +//! MU transport layer could leverage the Multicore Manager (MCMGR) component for Inter-Core +//! interrupts / MU interrupts management or the Inter-Core interrupts can be managed by itself (MUX_IRQHandler +//! overloading). By default, ERPC_TRANSPORT_MU_USE_MCMGR is set to ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED when mcmgr.h +//! is part of the project, otherwise the ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED option is used. This settings can be +//! overwritten from the erpc_config.h by uncommenting the ERPC_TRANSPORT_MU_USE_MCMGR macro definition. Do not forget +//! to add the MCMGR library into your project when ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED option is used! See the +//! erpc_mu_transport.h for additional MU settings. +//#define ERPC_TRANSPORT_MU_USE_MCMGR ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED +//@} + +//! @def ERPC_PRE_POST_ACTION +//! +//! Enable eRPC pre and post callback functions shim code. Take look into "erpc_pre_post_action.h". Can be used for +//! detection of eRPC call freeze, ... Default set to ERPC_PRE_POST_ACTION_DISABLED. +//! +//! Uncomment for using pre post callback feature. +//#define ERPC_PRE_POST_ACTION (ERPC_PRE_POST_ACTION_ENABLED) + +//! @def ERPC_PRE_POST_ACTION_DEFAULT +//! +//! Enable eRPC pre and post default callback functions. Take look into "erpc_setup_extensions.h". Can be used for +//! detection of eRPC call freeze, ... Default set to ERPC_PRE_POST_ACTION_DEFAULT_DISABLED. +//! +//! Uncomment for using pre post default callback feature. +//#define ERPC_PRE_POST_ACTION_DEFAULT (ERPC_PRE_POST_ACTION_DEFAULT_ENABLED) + +//! @name Assert function definition +//@{ +//! User custom asser defition. Include header file if needed before bellow line. If assert is not enabled, default will +//! be used. +// #define erpc_assert(condition) +//@} + +//! @def ENDIANES_HEADER +//! +//! Include header file that controls the communication endianness +//! +//! Uncomment for example behaviour for endianness agnostic with: +//! 1. communication in little endian. +//! 2. current processor is big endian. +//! 3. pointer size is 32 bit. +//! 4. float+double scheme not defined, so throws assert if passes. +//! #define ERPC_PROCESSOR_ENDIANNESS_LITTLE 0 +//! #define ERPC_COMMUNICATION_LITTLE 1 +//! #define ERPC_POINTER_SIZE_16 0 +//! #define ERPC_POINTER_SIZE_32 1 +//! #define ERPC_POINTER_SIZE_64 0 +//! #define ENDIANNESS_HEADER "erpc_endianness_agnostic_example.h" + +/*! @} */ +#endif // _ERPC_CONFIG_H_ +//////////////////////////////////////////////////////////////////////////////// +// EOF +//////////////////////////////////////////////////////////////////////////////// diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_config_internal.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_config_internal.h new file mode 100755 index 00000000..f5209c65 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_config_internal.h @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * Copyright 2020 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _ERPC_DETECT_H_ +#define _ERPC_DETECT_H_ + +#include "erpc_config.h" + +//////////////////////////////////////////////////////////////////////////////// +// Declarations +//////////////////////////////////////////////////////////////////////////////// +/* clang-format off */ + +// Determine if this is a POSIX system. +#if !defined(ERPC_HAS_POSIX) + // Detect Linux, BSD, Cygwin, and Mac OS X. + #if defined(__linux__) || defined(__GNU__) || defined(__FreeBSD__) || defined(__NetBSD__) || \ + defined(__OpenBSD__) || defined(__DragonFly__) || defined(__CYGWIN__) || defined(__MACH__) || \ + defined(__MINGW32__) + #define ERPC_HAS_POSIX (1) + #else + #define ERPC_HAS_POSIX (0) + #endif +#endif + +// Determine if we are targeting WIN32 environment +#if !defined(ERPC_HAS_WIN32) + #if defined(_WIN32) + #define ERPC_HAS_WIN32 (1) + #else + #define ERPC_HAS_WIN32 (0) + #endif +#endif + +// Safely detect FreeRTOSConfig.h. +#define ERPC_HAS_FREERTOSCONFIG_H (0) +#if defined(__has_include) + #if __has_include("FreeRTOSConfig.h") + #undef ERPC_HAS_FREERTOSCONFIG_H + #define ERPC_HAS_FREERTOSCONFIG_H (1) + #endif +#endif + +// Detect allocation policy if not already set. +#if !defined(ERPC_ALLOCATION_POLICY) + #if ERPC_HAS_FREERTOSCONFIG_H + #ifdef __cplusplus + extern "C" { + #endif + #include "FreeRTOSConfig.h" + #ifdef __cplusplus + } + #endif + #if defined(configSUPPORT_STATIC_ALLOCATION) && configSUPPORT_STATIC_ALLOCATION + #define ERPC_ALLOCATION_POLICY (ERPC_ALLOCATION_POLICY_STATIC) + #else + #define ERPC_ALLOCATION_POLICY (ERPC_ALLOCATION_POLICY_DYNAMIC) + #endif + #else + #define ERPC_ALLOCATION_POLICY (ERPC_ALLOCATION_POLICY_DYNAMIC) + #endif +#endif + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + #if !defined(ERPC_CODEC_COUNT) + #define ERPC_CODEC_COUNT (2U) + #endif + #if !defined(ERPC_MESSAGE_LOGGERS_COUNT) + #define ERPC_MESSAGE_LOGGERS_COUNT (0U) + #endif + #if !defined(ERPC_CLIENTS_THREADS_AMOUNT) + #define ERPC_CLIENTS_THREADS_AMOUNT (1U) + #endif +#endif + +// Safely detect tx_api.h. +#define ERPC_HAS_THREADX_API_H (0) +#if defined(__has_include) + #if __has_include("tx_api.h") + #undef ERPC_HAS_THREADX_API_H + #define ERPC_HAS_THREADX_API_H (1) + #endif +#endif + +// Detect threading model if not already set. +#if !defined(ERPC_THREADS) + #if ERPC_HAS_POSIX + // Default to pthreads for POSIX systems. + #define ERPC_THREADS (ERPC_THREADS_PTHREADS) + #elif ERPC_HAS_FREERTOSCONFIG_H + // Use FreeRTOS if we can auto detect it. + #define ERPC_THREADS (ERPC_THREADS_FREERTOS) + #elif ERPC_HAS_WIN32 + #define ERPC_THREADS (ERPC_THREADS_WIN32) + #elif ERPC_HAS_THREADX_API_H + #define ERPC_THREADS (ERPC_THREADS_THREADX) + #else + // Otherwise default to no threads. + #define ERPC_THREADS (ERPC_THREADS_NONE) + #endif +#endif + +// Handy macro to test threading model. You can also ERPC_THREADS directly to test for threading +// support, i.e. "#if ERPC_THREADS", because ERPC_THREADS_NONE has a value of 0. +#define ERPC_THREADS_IS(_n_) (ERPC_THREADS == (ERPC_THREADS_##_n_)) + +// Set default buffer size. +#if !defined(ERPC_DEFAULT_BUFFER_SIZE) + //! @brief Size of buffers allocated by BasicMessageBufferFactory in setup functions. + #define ERPC_DEFAULT_BUFFER_SIZE (256U) +#endif + +// Set default buffers count. +#if !defined(ERPC_DEFAULT_BUFFERS_COUNT) + //! @brief Count of buffers allocated by StaticMessageBufferFactory. + #define ERPC_DEFAULT_BUFFERS_COUNT (2U) +#endif + +// Disable/enable noexcept. +#if !defined(ERPC_NOEXCEPT) + #if ERPC_HAS_POSIX + #define ERPC_NOEXCEPT (ERPC_NOEXCEPT_ENABLED) + #else + #define ERPC_NOEXCEPT (ERPC_NOEXCEPT_DISABLED) + #endif +#endif + +//NOEXCEPT support +#if defined(__cplusplus) && __cplusplus >= 201103 && ERPC_NOEXCEPT + #define NOEXCEPT noexcept +#else + #define NOEXCEPT +#endif // NOEXCEPT + +// Disabling nesting calls support as default. +#if !defined(ERPC_NESTED_CALLS) + #define ERPC_NESTED_CALLS (ERPC_NESTED_CALLS_DISABLED) +#endif + +#if ERPC_NESTED_CALLS && !ERPC_THREADS + #error "Nested calls currently working only with Threads." +#endif + +// Enabling nesting calls detection as default for debug. +#if !defined(ERPC_NESTED_CALLS_DETECTION) + #if defined(NDEBUG) || (ERPC_NESTED_CALLS == ERPC_NESTED_CALLS_ENABLED) + #define ERPC_NESTED_CALLS_DETECTION (ERPC_NESTED_CALLS_DETECTION_DISABLED) + #else + #define ERPC_NESTED_CALLS_DETECTION (ERPC_NESTED_CALLS_DETECTION_ENABLED) + #endif +#endif + +// Disabling tracing the eRPC. +#if !defined(ERPC_MESSAGE_LOGGING) + #define ERPC_MESSAGE_LOGGING (ERPC_MESSAGE_LOGGING_DISABLED) +#endif + +#if defined(__CC_ARM) || defined(__ARMCC_VERSION) /* Keil MDK */ + #define THROW_BADALLOC throw(std::bad_alloc) + #define THROW throw() +#else + #define THROW_BADALLOC + #define THROW +#endif + +#ifndef ERPC_TRANSPORT_MU_USE_MCMGR + #if defined(__has_include) + #if (__has_include("mcmgr.h")) + #define ERPC_TRANSPORT_MU_USE_MCMGR (ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED) + #else + #define ERPC_TRANSPORT_MU_USE_MCMGR (ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED) + #endif + #endif +#else + #if defined(__has_include) + #if ((!(__has_include("mcmgr.h"))) && (ERPC_TRANSPORT_MU_USE_MCMGR == ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED)) + #error "Do not forget to add the MCMGR library into your project!" + #endif + #endif +#endif + +// Disabling pre and post callback function related code. +#if !defined(ERPC_PRE_POST_ACTION) + #define ERPC_PRE_POST_ACTION (ERPC_PRE_POST_ACTION_DISABLED) +#endif + +// Disabling pre and post default callback function code. +#if !defined(ERPC_PRE_POST_ACTION_DEFAULT) + #define ERPC_PRE_POST_ACTION_DEFAULT (ERPC_PRE_POST_ACTION_DEFAULT_DISABLED) +#endif + +#if !defined(erpc_assert) + #if ERPC_HAS_FREERTOSCONFIG_H + #ifdef __cplusplus + extern "C" { + #endif + #include "FreeRTOS.h" + #include "task.h" + #ifdef __cplusplus + } + #endif + #define erpc_assert(condition) configASSERT(condition) + #elif defined(ERPC_THREADS) && (ERPC_THREADS == ERPC_THREADS_MBED) + #include "platform/mbed_assert.h" + #define erpc_assert(condition) MBED_ASSERT(condition) + #else + #ifdef __cplusplus + #include + #else + #include "assert.h" + #endif + #define erpc_assert(condition) assert(condition) + #endif +#endif + +// Disabling endianness agnostic feature. +#ifndef ENDIANNESS_HEADER + #define ENDIANNESS_HEADER "erpc_endianness_undefined.h" +#endif + +/* clang-format on */ +#endif // _ERPC_DETECT_H_ +//////////////////////////////////////////////////////////////////////////////// +// EOF +//////////////////////////////////////////////////////////////////////////////// diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_crc16.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_crc16.hpp new file mode 100755 index 00000000..682cd7ab --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_crc16.hpp @@ -0,0 +1,74 @@ +/* + * Copyright 2017 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__CRC16_H_ +#define _EMBEDDED_RPC__CRC16_H_ + +#include + +/*! + * @addtogroup infra_transport + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { + +/*! + * @brief Class for compute crc16. + */ +class Crc16 +{ +public: + /*! + * @brief Constructor. + * + * @param[in] crcStart Start value for crc function. + */ + explicit Crc16(uint32_t crcStart); + + /*! + * @brief Constructor. + */ + Crc16(void); + + /*! + * @brief Crc16 destructor + */ + ~Crc16(void); + + /*! + * @brief Compute a ITU-CCITT CRC-16 over the provided data. + * + * This implementation is slow but small in size. + * + * @param[in] data Pointer to data used for crc16. + * @param[in] lengthInBytes Data length. + */ + uint16_t computeCRC16(const uint8_t *data, uint32_t lengthInBytes); + + /*! + * @brief Set crc start number. + * + * @param[in] crcStart Crc start number. + */ + void setCrcStart(uint32_t crcStart); + +protected: + uint32_t m_crcStart; /*!< CRC start number. */ +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__CRC16_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_framed_transport.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_framed_transport.hpp new file mode 100755 index 00000000..443f1cf4 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_framed_transport.hpp @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016-2020 NXP + * Copyright 2021 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__FRAMED_TRANSPORT_H_ +#define _EMBEDDED_RPC__FRAMED_TRANSPORT_H_ + +#include "erpc_config_internal.h" +#include "erpc_message_buffer.hpp" +#include "erpc_transport.hpp" + +#include + +#if !ERPC_THREADS_IS(NONE) +#include "erpc_threading.h" +#endif + +/*! + * @addtogroup infra_transport + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { + +/*! + * @brief Base class for framed transport layers. + * + * This class adds simple framing to the data transmitted and received on the + * communications channel. This allows the transport to perform reads and writes + * of a size known in advance. Subclasses must implement the underlyingSend() and + * underlyingReceive() methods to actually transmit and receive data. + * + * Frames have a maximum size of 64kB, as a 16-bit frame size is used. + * + * @note This implementation currently assumes both sides of the communications channel + * are the same endianness. + * + * The frame header includes a CRC-16 over the data for integrity checking. This class + * includes a default CRC-16 implementation that is optimized for code size, but is + * relatively slow. If a faster implementation is desired, you can pass the new CRC + * function to setCRCFunction(). + * + * @ingroup infra_transport + */ +class FramedTransport : public Transport +{ +public: + /*! @brief Contents of the header that prefixes each message. */ + struct Header + { + uint16_t m_crcHeader; //!< CRC-16 over this header structure data + uint16_t m_messageSize; //!< Size in bytes of the message, excluding the header. + uint16_t m_crcBody; //!< CRC-16 over the message data. + }; + + /*! + * @brief Constructor. + */ + FramedTransport(void); + + /*! + * @brief FramedTransport destructor + */ + virtual ~FramedTransport(void); + + /** + * @brief Size of data placed in MessageBuffer before serializing eRPC data. + * + * @return uint8_t Amount of bytes, reserved before serialized data. + */ + virtual uint8_t reserveHeaderSize(void) override; + + /*! + * @brief Receives an entire message. + * + * The frame header and message data are received. The CRC-16 in the frame header is + * compared with the computed CRC. If the received CRC is invalid, #kErpcStatus_Fail + * will be returned. + * + * The @a message is only filled with the message data, not the frame header. + * + * This function is blocking. + * + * @param[in] message Message buffer, to which will be stored incoming message. + * + * @retval kErpcStatus_Success When receiving was successful. + * @retval kErpcStatus_CrcCheckFailed When receiving failed. + * @retval other Subclass may return other errors from the underlyingReceive() method. + */ + virtual erpc_status_t receive(MessageBuffer *message) override; + + /*! + * @brief Function to send prepared message. + * + * @param[in] message Pass message buffer to send. + * + * @retval kErpcStatus_Success When sending was successful. + * @retval other Subclass may return other errors from the underlyingSend() method. + */ + virtual erpc_status_t send(MessageBuffer *message) override; + + /*! + * @brief This functions sets the CRC-16 implementation. + * + * @param[in] crcImpl Object containing crc-16 compute function. + */ + virtual void setCrc16(Crc16 *crcImpl) override; + + /*! + * @brief This functions gets the CRC-16 object. + * + * @return Crc16* Pointer to CRC-16 object containing crc-16 compute function. + */ + virtual Crc16 *getCrc16(void) override; + +protected: + Crc16 *m_crcImpl; /*!< CRC object. */ + +#if !ERPC_THREADS_IS(NONE) + Mutex m_sendLock; //!< Mutex protecting send. + Mutex m_receiveLock; //!< Mutex protecting receive. +#endif + + /*! + * @brief Adds ability to framed transport to overwrite MessageBuffer when sending data. + * + * Usually we don't want to do that. + * + * @param message MessageBuffer to send. + * @param size size of message to send. + * @param offset data start address offset + * + * @return erpc_status_t kErpcStatus_Success when it finished successful otherwise error. + */ + virtual erpc_status_t underlyingSend(MessageBuffer *message, uint32_t size, uint32_t offset); + + /*! + * @brief Adds ability to framed transport to overwrite MessageBuffer when receiving data. + * + * Usually we don't want to do that. + * + * @param message MessageBuffer to send. + * @param size size of message to send. + * @param offset data start address offset + * + * @return erpc_status_t kErpcStatus_Success when it finished successful otherwise error. + */ + virtual erpc_status_t underlyingReceive(MessageBuffer *message, uint32_t size, uint32_t offset); + + /*! + * @brief Subclasses must implement this function to send data. + * + * @param[in] data Buffer to send. + * @param[in] size Size of data to send. + * + * @retval kErpcStatus_Success When data was written successfully. + * @retval kErpcStatus_Fail When writing data ends with error. + */ + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) = 0; + + /*! + * @brief Subclasses must implement this function to receive data. + * + * @param[inout] data Preallocated buffer for receiving data. + * @param[in] size Size of data to read. + * + * @retval kErpcStatus_Success When data was read successfully. + * @retval kErpcStatus_Fail When reading data ends with error. + */ + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) = 0; +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__FRAMED_TRANSPORT_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_inter_thread_buffer_transport.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_inter_thread_buffer_transport.hpp new file mode 100755 index 00000000..dabba2bb --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_inter_thread_buffer_transport.hpp @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2014, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__INTER_THREAD_BUFFER_TRANSPORT_H_ +#define _EMBEDDED_RPC__INTER_THREAD_BUFFER_TRANSPORT_H_ + +#include "erpc_message_buffer.hpp" +#include "erpc_threading.h" +#include "erpc_transport.hpp" + +/*! + * @addtogroup itbp_transport + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { +/*! + * @brief Very basic transport to send/receive messages between threads. + * + * Can send and receive message buffers to/from another instance of the same class + * associated with another thread. Only one other thread may be communicated with. To set + * things up first create two instances. Then call the linkWithPeer() method on the + * first one, passing the second. The two instances of this class do not have to be + * created on their respective threads, but the send() and receive() calls must be + * invoked on the appropriate thread. + * + * Only a single message may be pending for each of the two threads. If a message is + * pending for a thread and another is sent, then the sender will block until the + * currently pending message is received. + * + * @ingroup itbp_transport + */ +class InterThreadBufferTransport : public Transport +{ +public: + InterThreadBufferTransport(void) : + Transport(), m_state(NULL), m_peer(NULL), m_inSem(), m_outSem(1), m_inBuffer(NULL) + { + } + virtual ~InterThreadBufferTransport(void); + + void linkWithPeer(InterThreadBufferTransport *peer); + + virtual erpc_status_t receive(MessageBuffer *message) override; + virtual erpc_status_t send(MessageBuffer *message) override; + + virtual int32_t getAvailable(void) const { return 0; } + +protected: + struct SharedState + { + Mutex m_mutex; + }; + + SharedState *m_state; /*!< */ + InterThreadBufferTransport *m_peer; /*!< */ + Semaphore m_inSem; /*!< */ + Semaphore m_outSem; /*!< */ + MessageBuffer *m_inBuffer; /*!< */ +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__INTER_THREAD_BUFFER_TRANSPORT_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_manually_constructed.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_manually_constructed.hpp new file mode 100755 index 00000000..de4f9f7e --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_manually_constructed.hpp @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2014, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * Copyright 2021 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__MANUALLY_CONSTRUCTED_H_ +#define _EMBEDDED_RPC__MANUALLY_CONSTRUCTED_H_ + +#include "erpc_config_internal.h" + +#include +#include + +/*! + * @addtogroup infra_utility + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { +/*! + * @brief Allocates static storage for an object. + * + * This template class defines storage of the template class' size. Then it + * gives the user explicit control over construction and destruction of the + * object residing in that storage. This is useful for placing objects in + * unions, or other situations where you need static storage but want to delay + * the actual construction of the object. + * + * Objects of this class will act as a pointer to the template argument class + * type. Of course, if the object has not yet been constructed then the + * behavior is undefined if the pointer to it is used. + * + * Note that there is not a constructor or deconstructor. This is because + * members of unions cannot have constructors or deconstructors. + * + * Instances of this template class are aligned to 8 bytes. + * + * @ingroup infra_utility + */ +template +class ManuallyConstructed +{ +public: + //! @name Object access + //@{ + T *get(void) { return (m_isConstructed) ? reinterpret_cast(&m_storage) : nullptr; } + const T *get(void) const { return (m_isConstructed) ? reinterpret_cast(&m_storage) : nullptr; } + T *operator->(void) { return get(); } + const T *operator->(void) const { return get(); } + T &operator*(void) + { + if (m_isConstructed) + { + return *get(); + } + else + { + memset(&m_storage, 0, sizeof(m_storage) * 8); + return reinterpret_cast(m_storage); + }; + } + const T &operator*(void) const + { + if (m_isConstructed) + { + return *get(); + } + else + { + memset(&m_storage, 0, sizeof(m_storage) * 8); + return reinterpret_cast(m_storage); + }; + } + operator T *(void) { return get(); } + operator const T *(void) const { return get(); } + //@} + + //! @name Explicit construction methods + //@{ + void construct(void) + { + destroy(); + new (m_storage) T; + m_isConstructed = true; + } + + template + void construct(const A1 &a1) + { + destroy(); + new (m_storage) T(a1); + m_isConstructed = true; + } + + template + void construct(const A1 &a1, const A2 &a2) + { + destroy(); + new (m_storage) T(a1, a2); + m_isConstructed = true; + } + + template + void construct(const A1 &a1, const A2 &a2, const A3 &a3) + { + destroy(); + new (m_storage) T(a1, a2, a3); + m_isConstructed = true; + } + + template + void construct(const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4) + { + destroy(); + new (m_storage) T(a1, a2, a3, a4); + m_isConstructed = true; + } + + template + void construct(const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5) + { + destroy(); + new (m_storage) T(a1, a2, a3, a4, a5); + m_isConstructed = true; + } + + template + void construct(const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5, const A6 &a6) + { + destroy(); + new (m_storage) T(a1, a2, a3, a4, a5, a6); + m_isConstructed = true; + } + //@} + + /*! + * @brief Invoke the object's destructor. + * + * Behavior is undefined if the objected was not previously initialized. + */ + void destroy(void) + { + if (m_isConstructed) + { + get()->~T(); + m_isConstructed = false; + } + } + + /*! + * @brief Returns information if object is free or is used. + * + * @return true Object is constructed and used. + * @return false Object wasn't constructed or it was destructed already. + */ + bool isUsed(void) { return m_isConstructed; } + +protected: + /*! + * @brief Storage for the object. + * + * An array of uint64 is used to get 8-byte alignment. + */ + uint64_t m_storage[(sizeof(T) + sizeof(uint64_t) - 1) / sizeof(uint64_t)]; + + /*! + * @brief Track construct/destruct calls. + * + * Based on this variable we can allow or forbid construct/destruct calls. + */ + bool m_isConstructed = false; +}; + +#define ERPC_MANUALLY_CONSTRUCTED(class, variableName) static ManuallyConstructed variableName +#define ERPC_MANUALLY_CONSTRUCTED_ARRAY(class, variableName, dimension) \ + ERPC_MANUALLY_CONSTRUCTED(class, variableName)[dimension] + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC +#define ERPC_MANUALLY_CONSTRUCTED_STATIC(class, variableName) ERPC_MANUALLY_CONSTRUCTED(class, variableName) +#else +#define ERPC_MANUALLY_CONSTRUCTED_STATIC(class, variableName) +#endif + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC +#define ERPC_MANUALLY_CONSTRUCTED_ARRAY_STATIC(class, variableName, dimension) \ + ERPC_MANUALLY_CONSTRUCTED_ARRAY(class, variableName, dimension) +#else +#define ERPC_MANUALLY_CONSTRUCTED_ARRAY_STATIC(class, variableName, dimension) +#endif + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC +#define ERPC_CREATE_NEW_OBJECT(class, arrayOfObjects, numberOfObjects, ...) \ + return new (std::nothrow) class(__VA_ARGS__); + +#define ERPC_DESTROY_OBJECT(object, ...) delete object; + +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC +#define ERPC_CREATE_NEW_OBJECT(class, arrayOfObjects, numberOfObjects, ...) \ + uint8_t objectsIterator; \ + class *ret = NULL; \ + for (objectsIterator = 0; objectsIterator < numberOfObjects; objectsIterator++) \ + { \ + if (!arrayOfObjects[objectsIterator].isUsed()) \ + { \ + arrayOfObjects[objectsIterator].construct(__VA_ARGS__); \ + ret = arrayOfObjects[objectsIterator].get(); \ + break; \ + } \ + } \ + return ret; + +#define ERPC_DESTROY_OBJECT(object, arrayOfObjects, numberOfObjects) \ + uint8_t objectsIterator; \ + for (objectsIterator = 0; objectsIterator < numberOfObjects; objectsIterator++) \ + { \ + if (object == arrayOfObjects[objectsIterator].get()) \ + { \ + arrayOfObjects[objectsIterator].destroy(); \ + break; \ + } \ + } +#endif + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__MANUALLY_CONSTRUCTED_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_mbf_setup.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_mbf_setup.h new file mode 100755 index 00000000..87ba45d3 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_mbf_setup.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _ERPC_MBF_SETUP_H_ +#define _ERPC_MBF_SETUP_H_ + +#include "erpc_transport_setup.h" + +/*! + * @addtogroup message_buffer_factory_setup + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Types +//////////////////////////////////////////////////////////////////////////////// + +//! @brief Opaque MessageBufferFactory object type. +typedef struct ErpcMessageBufferFactory *erpc_mbf_t; + +//////////////////////////////////////////////////////////////////////////////// +// API +//////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif + +//! @name MessageBufferFactory setup +//@{ + +/*! + * @brief Create MessageBuffer factory which is using dynamic allocated buffers. + */ +erpc_mbf_t erpc_mbf_dynamic_init(void); + +/*! + * @brief Deinit MessageBuffer factory. + * + * @param[in] mbf MessageBuffer factory which was initialized in init function. + */ +void erpc_mbf_dynamic_deinit(erpc_mbf_t mbf); + +/*! + * @brief Create MessageBuffer factory which is using RPMSG LITE zero copy buffers. + * + * Has to be used with RPMSG lite zero copy transport. + */ +erpc_mbf_t erpc_mbf_rpmsg_init(erpc_transport_t transport); + +/*! + * @brief Deinit MessageBuffer factory. + * + * @param[in] mbf MessageBuffer factory which was initialized in init function. + */ +void erpc_mbf_rpmsg_deinit(erpc_mbf_t mbf); + +/*! + * @brief Create MessageBuffer factory which is using static allocated buffers. + */ +erpc_mbf_t erpc_mbf_static_init(void); + +/*! + * @brief Deinit MessageBuffer factory. + * + * @param[in] mbf MessageBuffer factory which was initialized in init function. + */ +void erpc_mbf_static_deinit(erpc_mbf_t mbf); + +//@} + +#ifdef __cplusplus +} +#endif + +/*! @} */ + +#endif // _ERPC_MBF_SETUP_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_message_buffer.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_message_buffer.hpp new file mode 100755 index 00000000..f70bafa9 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_message_buffer.hpp @@ -0,0 +1,407 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__MESSAGE_BUFFER_H_ +#define _EMBEDDED_RPC__MESSAGE_BUFFER_H_ + +#include "erpc_common.h" + +#include +#include + +/*! + * @addtogroup infra_codec + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { +/*! + * @brief Represents a memory buffer containing a message. + * + * The MessageBuffer object does not own the buffer memory. It simply provides an interface + * to accessing that memory in a convenient manner. + * + * @ingroup infra_codec + */ +class MessageBuffer +{ +public: + /*! + * @brief Constructor. + * + * This function initializes object attributes. + */ + MessageBuffer(void) : m_buf(NULL), m_len(0), m_used(0) {} + + /*! + * @brief Constructor. + * + * This function initializes object attributes. + * + * @param[in] buffer Pointer to buffer. + * @param[in] length Length of buffer. + */ + MessageBuffer(uint8_t *buffer, uint16_t length) : m_buf(buffer), m_len(length), m_used(0) {} + + MessageBuffer(const MessageBuffer &buffer); + + /*! + * @brief This function set new buffer and his length. + * + * This function set buffer to read/write data. + * + * @param[in] buffer Pointer to another buffer to read/write data. + * @param[in] length Length of buffer. + */ + void set(uint8_t *buffer, uint16_t length) + { + m_buf = buffer; + m_len = length; + m_used = 0; + } + + /*! + * @brief This function returns pointer to buffer to read/write. + * + * @return Pointer to buffer to read/write. + */ + uint8_t *get(void) { return m_buf; } + + /*! + * @brief This function returns pointer to buffer to read/write. + * + * @return Pointer to buffer to read/write. + */ + const uint8_t *get(void) const { return m_buf; } + + /*! + * @brief This function returns length of buffer. + * + * @return Length of buffer. + */ + uint16_t getLength(void) const { return m_len; } + + /*! + * @brief This function returns length of used space of buffer. + * + * @return Length of used space of buffer. + */ + uint16_t getUsed(void) const { return m_used; } + + /*! + * @brief This function returns length of free space of buffer. + * + * @return Length of free space of buffer. + */ + uint16_t getFree(void) const { return m_len - m_used; } + + /*! + * @brief This function sets length of used space of buffer. + * + * @param[in] used Length of used space of buffer. + */ + void setUsed(uint16_t used); + + /*! + * @brief This function read data from local buffer. + * + * @param[in] offset Offset in local buffer. + * @param[inout] data Given buffer to save read data. + * @param[in] length Length of data to read. + * + * @return Status from reading data. + */ + erpc_status_t read(uint16_t offset, void *data, uint32_t length); + + /*! + * @brief This function write data to local buffer. + * + * @param[in] offset Offset in local buffer. + * @param[inout] data Given buffer from which are copied data. + * @param[in] length Length of data to write. + * + * @return Status from reading data. + */ + erpc_status_t write(uint16_t offset, const void *data, uint32_t length); + + /*! + * @brief This function copy given message buffer to local instance. + * + * @param[in] other MesageBuffer to copy. + * + * @return Status from reading data. + */ + erpc_status_t copy(const MessageBuffer *other); + + /*! + * @brief This function swap message buffer attributes between given instance and local instance. + * + * @param[in] other MesageBuffer to swap. + */ + void swap(MessageBuffer *other); + + /*! + * @brief Casting operator return local buffer. + */ + operator uint8_t *(void) { return m_buf; } + + /*! + * @brief Casting operator return local buffer. + */ + operator const uint8_t *(void) const { return m_buf; } + + /*! + * @brief Array operator return value of buffer at given index. + * + * @param[in] index Index in buffer. + */ + uint8_t &operator[](int index) { return m_buf[index]; } + + /*! + * @brief Array operator return value of buffer at given index. + * + * @param[in] index Index in buffer. + */ + const uint8_t &operator[](int index) const { return m_buf[index]; } + +private: + uint8_t *volatile m_buf; /*!< Buffer used to read write data. */ + uint16_t volatile m_len; /*!< Length of buffer. */ + uint16_t volatile m_used; /*!< Used buffer bytes. */ +}; + +/*! + * @brief Cursor within a MessageBuffer. + */ +class Cursor +{ +public: + /*! + * @brief Constructor. + * + * This function initializes object attributes. + */ + Cursor(void) : m_buffer(), m_pos(NULL) {} + + /*! + * @brief Constructor. + * + * This function initializes object attributes. + * + * @param[in] buffer MessageBuffer for sending/receiving. + */ + explicit Cursor(MessageBuffer &buffer) : m_buffer(buffer), m_pos(buffer.get()) {} + + /*! + * @brief Set message buffer. + * + * @param[in] buffer Message buffer to set. + * @param[in] reserved Moved cursor position outside of reserved memory. + */ + void setBuffer(MessageBuffer &buffer, uint8_t reserved = 0); + + /*! + * @brief Get message buffer. + */ + MessageBuffer getBuffer(void); + + /*! + * @brief Get message buffer. + */ + MessageBuffer &getBufferRef(void); + + /*! + * @brief Return position in buffer. + * + * Return position, where it last write/read. + * + * @return Return position in buffer. + */ + uint8_t *get(void) { return m_pos; } + + /*! + * @brief Return position in buffer. + * + * Return position, where it last write/read. + * + * @return Return position in buffer. + */ + const uint8_t *get(void) const { return m_pos; } + + /*! + * @brief Return remaining free space in current buffer. + * + * @return Remaining free space in current buffer. + */ + uint16_t getRemaining(void) const { return m_buffer.getLength() - (uint16_t)(m_pos - m_buffer.get()); } + + /*! + * @brief Return remaining space from used of current buffer. + * + * @return Remaining space from used of current buffer. + */ + uint16_t getRemainingUsed(void) const { return m_buffer.getUsed() - (uint16_t)(m_pos - m_buffer.get()); } + + /*! + * @brief Read data from current buffer. + * + * @param[out] data Pointer to value, where copy read data. + * @param[in] length How much bytes need be read. + * + * @retval kErpcStatus_Success + * @retval kErpcStatus_BufferOverrun + */ + erpc_status_t read(void *data, uint32_t length); + + /*! + * @brief Read data from current buffer. + * + * @param[out] data Pointer to value to be sent. + * @param[in] length How much bytes need be wrote. + * + * @retval kErpcStatus_Success + * @retval kErpcStatus_BufferOverrun + */ + erpc_status_t write(const void *data, uint32_t length); + + /*! + * @brief Casting operator return local buffer. + */ + operator uint8_t *(void) { return m_pos; } + + /*! + * @brief Casting operator return local buffer. + */ + operator const uint8_t *(void) const { return m_pos; } + + /*! + * @brief Array operator return value of buffer at given index. + * + * @param[in] index Index in buffer. + */ + uint8_t &operator[](int index); + + /*! + * @brief Array operator return value of buffer at given index. + * + * @param[in] index Index in buffer. + */ + const uint8_t &operator[](int index) const; + + /*! + * @brief Sum operator return local buffer. + * + * @param[in] n Summing with n. + * + * @return Current cursor instance. + */ + Cursor &operator+=(uint16_t n); + + /*! + * @brief Subtract operator return local buffer. + * + * @param[in] n Subtracting with n. + * + * @return Current cursor instance. + */ + Cursor &operator-=(uint16_t n); + + /*! + * @brief Sum +1 operator. + * + * @return Current cursor instance. + */ + Cursor &operator++(void); + + /*! + * @brief Subtract -1 operator. + * + * @return Current cursor instance. + */ + Cursor &operator--(void); + +private: + MessageBuffer m_buffer; /*!< Buffer for reading or writing data. */ + uint8_t *m_pos; /*!< Position in buffer, where it last write/read */ +}; + +/*! + * @brief Abstract interface for message buffer factory. + * + * @ingroup infra_codec + */ +class MessageBufferFactory +{ +public: + /*! + * @brief Constructor. + * + * This function initializes object attributes. + */ + MessageBufferFactory(void); + + /*! + * @brief MessageBufferFactory destructor + */ + virtual ~MessageBufferFactory(void); + + /*! + * @brief This function creates new message buffer. + * + * @return New created MessageBuffer. + */ + virtual MessageBuffer create(void) = 0; + + /*! + * @brief This function creates new message buffer with reserved bytes at the beginning + * + * Reserved bytes can be used by transport to write transport related header file data. + * + * @param[in] reserveHeaderSize Reserved amount of bytes at the beginning of message buffer. + * + * @return New created MessageBuffer. + */ + MessageBuffer create(uint8_t reserveHeaderSize); + + /*! + * @brief This function informs server if it has to create buffer for received message. + * + * @return Has to return TRUE when server need create buffer for receiving message. + */ + virtual bool createServerBuffer(void); + + /*! + * @brief This function is preparing output buffer on server side. + * + * This function do decision if this function want reuse buffer, or use new buffer. + * In case of using new buffer function has to free given buffer. + * + * @param[in] message MessageBuffer which can be reused. + * @param[in] reserveHeaderSize Reserved amount of bytes at the beginning of message buffer. + */ + virtual erpc_status_t prepareServerBufferForSend(MessageBuffer &message, uint8_t reserveHeaderSize = 0); + + /*! + * @brief This function disposes message buffer. + * + * @param[in] buf MessageBuffer to dispose. + */ + virtual void dispose(MessageBuffer *buf) = 0; +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__MESSAGE_BUFFER_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_message_loggers.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_message_loggers.hpp new file mode 100755 index 00000000..7d259abe --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_message_loggers.hpp @@ -0,0 +1,125 @@ +/* + * Copyright 2017 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__LOGEVENTLISTENERS_H_ +#define _EMBEDDED_RPC__LOGEVENTLISTENERS_H_ + +#include "erpc_transport.hpp" + +/*! + * @addtogroup infra_transport + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { + +/*! + * @brief Logging messages objects used for logging sent/received messages. + * + * @ingroup infra_utility + */ +class MessageLogger +{ +public: + /*! + * @brief MessageLogger constructor. + */ + explicit MessageLogger(Transport *transport) : m_next(NULL), m_transport(transport){}; + + /*! + * @brief MessageLogger destructor + */ + ~MessageLogger(void){}; + + /*! + * @brief Return next logger. + * + * @return Pointer to next logger. + */ + MessageLogger *getNext(void) { return m_next; } + + /*! + * @brief Set next logger. + * + * @param[in] next Pointer to next logger. + */ + void setNext(MessageLogger *next) { m_next = next; } + + /*! + * @brief Returns next transport object used for logging messages. + * + * @return Transport object used for logging messages. + */ + Transport *getLogger(void) { return m_transport; } + +protected: + MessageLogger *m_next; /*!< Pointer to next logger. */ + Transport *m_transport; /*!< Pointer to transport object used for logging messages. */ +}; + +/*! + * @brief Logging messages functionality. + * + * @ingroup infra_utility + */ +class MessageLoggers +{ +public: + /*! + * @brief Constructor. + */ + MessageLoggers(void) : m_logger(NULL){}; + + /*! + * @brief Transport destructor + */ + ~MessageLoggers(void); + + /*! + * @brief This function add given transport to newly created MessageLogger object. + * + * @param[in] transport Transport used for logging messages + * + * @retval True When transport was successfully added. + * @retval False When transport wasn't added. + */ + bool addMessageLogger(Transport *transport); + +protected: + MessageLogger *m_logger; /*!< Pointer to first logger. */ + + /*! + * @brief This function add given transport to newly created MessageLogger object. + * + * @param[in] msg Buffer which will be logged. + * + * @return The eRPC status based on transport type. + */ + erpc_status_t logMessage(MessageBuffer *msg); + +private: + /** + * @brief This function create new MessageLogger object + * + * @param[in] transport Transport used by MessageLogger. + * + * @return MessageLogger* Returns new MessageLogger object. + */ + MessageLogger *create(Transport *transport); +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__LOGEVENTLISTENERS_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_port.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_port.h new file mode 100755 index 00000000..18b4e8b0 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_port.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__PORT_H_ +#define _EMBEDDED_RPC__PORT_H_ + +#include "erpc_config_internal.h" + +/*! + * @addtogroup port_mem + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Declarations +//////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/*! + * @brief This function is used for allocating space. + * + * @param[in] size Size of memory block which should be allocated. + * + * @return Pointer to allocated space or NULL. + */ +void *erpc_malloc(size_t size); + +/*! + * @brief This function free given memory block. + * + * @param[in] ptr Pointer to memory which should be freed, or NULL. + */ +void erpc_free(void *ptr); + +#ifdef __cplusplus +} +#endif + +/*! @} */ + +#endif // _EMBEDDED_RPC__PORT_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_pre_post_action.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_pre_post_action.h new file mode 100755 index 00000000..3f8574e1 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_pre_post_action.h @@ -0,0 +1,93 @@ +/* + * Copyright 2020 NXP + * Copyright 2020 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__PREPOSTACTION_H_ +#define _EMBEDDED_RPC__PREPOSTACTION_H_ + +#ifdef __cplusplus +#include +/*! + * @addtogroup infra_transport + * @{ + * @file + */ +extern "C" { +#endif + +typedef void (*pre_post_action_cb)(void); + +#ifdef __cplusplus +} + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { + +/*! + * @brief Client and server may used cb functions before and after rpc call. + * + * @ingroup infra_utility + */ +class PrePostAction +{ +public: + /*! + * @brief PrePostAction constructor. + */ + PrePostAction(void) : m_preCB(NULL), m_postCB(NULL){}; + + /*! + * @brief This function sets "before eRPC call start" callback function. + * + * @param[in] preCB Pointer for callback function. When NULL and ERPC_PRE_POST_ACTION_DEFAULT + * is enabled then default function will be set. + */ + void addPreCB(pre_post_action_cb preCB); + + /*! + * @brief This function sets "after eRPC call finish" callback function. + * + * @param[in] postCB Pointer for callback function. When NULL and ERPC_PRE_POST_ACTION_DEFAULT + * is enabled then default function will be set. + */ + void addPostCB(pre_post_action_cb postCB); + + /*! + * @brief This function returns "before eRPC call start" callback function. + * + * @return preCB Pointer for callback function. + */ + pre_post_action_cb getPreCB(void) { return m_preCB; } + + /*! + * @brief This function returns "after eRPC call finish" callback function. + * + * @return postCB Pointer for callback function. + */ + pre_post_action_cb getPostCB(void) { return m_postCB; } + + /*! + * @brief PrePostAction destructor + */ + ~PrePostAction(void){}; + +protected: + pre_post_action_cb m_preCB; /*!< Pointer to "before eRPC call start" callback function. */ + pre_post_action_cb m_postCB; /*!< Pointer to after eRPC call finish" callback function. */ +}; + +} // namespace erpc + +/*! @} */ + +#endif + +#endif // _EMBEDDED_RPC__PREPOSTACTION_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_serial.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_serial.h new file mode 100755 index 00000000..148ace3f --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_serial.h @@ -0,0 +1,78 @@ +/* + * This file is part of the Bus Pirate project (http://code.google.com/p/the-bus-pirate/). + * + * Written and maintained by the Bus Pirate project and http://dangerousprototypes.com + * + * To the extent possible under law, the project has + * waived all copyright and related or neighboring rights to Bus Pirate. This + * work is published from United States. + * + * For details see: http://creativecommons.org/publicdomain/zero/1.0/. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + */ +/* + * OS independent serial interface + * + * Heavily based on Pirate-Loader: + * http://the-bus-pirate.googlecode.com/svn/trunk/bootloader-v4/pirate-loader/source/pirate-loader.c + * + */ +#ifndef MYSERIAL_H_ +#define MYSERIAL_H_ + +#ifdef __APPLE__ +#include +#include + +#define B1500000 1500000 +#define B1000000 1000000 +#define B921600 921600 +#endif + +#include + +#ifdef _WIN32 +#include +#include + +#define B115200 115200 +#define B921600 921600 + +typedef long speed_t; +#else + +#include +#include +#include +#include +#include + +#endif + +/*! + * @addtogroup port_serial + * @{ + * @file + */ + +#if __cplusplus +extern "C" { +#endif + +int serial_setup(int fd, speed_t speed); +int serial_set_read_timeout(int fd, uint8_t vtime, uint8_t vmin); +int serial_write(int fd, const char *buf, int size); +int serial_read(int fd, char *buf, int size); +int serial_open(const char *port); +int serial_close(int fd); + +#if __cplusplus +} +#endif + +/*! @} */ + +#endif diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_serial_transport.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_serial_transport.hpp new file mode 100755 index 00000000..6b41ae11 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_serial_transport.hpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2014, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__SERIAL_TRANSPORT_H_ +#define _EMBEDDED_RPC__SERIAL_TRANSPORT_H_ + +#include "erpc_framed_transport.hpp" + +#include + +extern "C" { +#ifdef _WIN32 +typedef long speed_t; +#else +#include +#endif +} + +/*! + * @addtogroup serial_transport + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { +/*! + * @brief Serial transport layer for host PC + * + * @ingroup serial_transport + */ +class SerialTransport : public FramedTransport +{ +public: + /*! + * @brief Constructor. + * + * @param[in] portName Port name. + * @param[in] baudRate Baudrate. + */ + SerialTransport(const char *portName, speed_t baudRate); + + /*! + * @brief Destructor. + */ + virtual ~SerialTransport(void); + + /*! + * @brief Initialize Serial peripheral. + * + * @param[in] vtime Read timeout. + * @param[in] vmin Read timeout min. + * + * @return Status of init function. + */ + erpc_status_t init(uint8_t vtime, uint8_t vmin); + +private: + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + + /*! + * @brief Receive data from Serial peripheral. + * + * @param[inout] data Preallocated buffer for receiving data. + * @param[in] size Size of data to read. + * + * @retval kErpcStatus_ReceiveFailed Serial failed to receive data. + * @retval kErpcStatus_Success Successfully received all data. + */ + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; + + /*! + * @brief Write data to Serial peripheral. + * + * @param[in] data Buffer to send. + * @param[in] size Size of data to send. + * + * @retval kErpcStatus_ReceiveFailed Serial failed to receive data. + * @retval kErpcStatus_Success Successfully received all data. + */ + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; + +private: + int m_serialHandle; /*!< Serial handle id. */ + const char *m_portName; /*!< Port name. */ + speed_t m_baudRate; /*!< Bauderate. */ +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__SERIAL_TRANSPORT_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_server.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_server.hpp new file mode 100755 index 00000000..b7ec3f24 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_server.hpp @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2014, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * Copyright 2020 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__SERVER_H_ +#define _EMBEDDED_RPC__SERVER_H_ + +#include "erpc_client_server_common.hpp" +#include "erpc_config_internal.h" +#if ERPC_NESTED_CALLS +#include "erpc_client_manager.h" +#endif + +/*! + * @addtogroup infra_server + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { +#if ERPC_NESTED_CALLS +class RequestContext; +#endif +/*! + * @brief Abstract interface for service, which can be executed on server side. + * + * @ingroup infra_server + */ +class Service +{ +public: + /*! + * @brief Constructor. + * + * This function initializes object attributes. + */ + Service(uint32_t serviceId) : m_serviceId(serviceId), m_next(NULL) {} + + /*! + * @brief Service destructor + */ + virtual ~Service(void) {} + + /*! + * @brief Return service id number. + * + * @return Service id number. + */ + uint32_t getServiceId(void) const { return m_serviceId; } + + /*! + * @brief Return next service. + * + * @return Pointer to next service. + */ + Service *getNext(void) { return m_next; } + + /*! + * @brief Set next service. + * + * @param[in] next Pointer to next service. + */ + void setNext(Service *next) { m_next = next; } + + /*! + * @brief This function call function implementation of current service. + * + * @param[in] methodId Id number of function, which is requested. + * @param[in] sequence Sequence number. To be sure that reply from server belongs to client request. + * @param[in] codec For reading and writing data. + * @param[in] messageFactory Used for setting output buffer. + * + * @return Based on handleInvocation implementation. + */ + virtual erpc_status_t handleInvocation(uint32_t methodId, uint32_t sequence, Codec *codec, + MessageBufferFactory *messageFactory, Transport *transport) = 0; + +protected: + uint32_t m_serviceId; /*!< Service unique id. */ + Service *m_next; /*!< Pointer to next service. */ +}; + +/*! + * @brief Based server functionality. + * + * @ingroup infra_server + */ +class Server : public ClientServerCommon +{ +public: + /*! + * @brief Constructor. + * + * This function initializes object attributes. + */ + Server(void) : ClientServerCommon(), m_firstService(NULL) {} + + /*! + * @brief Server destructor + */ + virtual ~Server(void) {} + + /*! + * @brief Add service. + * + * @param[in] service Service to use. + */ + void addService(Service *service); + + /*! + * @brief Remove service. + * + * @param[in] service Service to remove. + */ + void removeService(Service *service); + + /*! + * @brief This function runs the server. + */ + virtual erpc_status_t run(void) = 0; + + /*! + * @brief This function stop the server. + */ + virtual void stop(void) = 0; + +protected: + Service *m_firstService; /*!< Contains pointer to first service. */ + + /*! + * @brief Process message. + * + * @param[in] codec Inout codec to use. + * @param[in] msgType Type of received message. Based on message type will be (will be not) sent respond. + * @param[in] serviceId To identify interface. + * @param[in] methodId To identify function in interface. + * @param[in] sequence To connect correct answer with correct request. + * + * @returns #kErpcStatus_Success or based on codec startReadMessage. + */ + virtual erpc_status_t processMessage(Codec *codec, message_type_t msgType, uint32_t serviceId, uint32_t methodId, + uint32_t sequence); + + /*! + * @brief Read head of message to identify type of message. + * + * @param[in] codec Inout codec to use. + * @param[out] msgType Type of received message. Based on message type will be (will be not) sent respond. + * @param[out] serviceId To identify interface. + * @param[out] methodId To identify function in interface. + * @param[out] sequence To connect correct answer with correct request. + * + * @returns #kErpcStatus_Success or based on service handleInvocation. + */ + virtual erpc_status_t readHeadOfMessage(Codec *codec, message_type_t &msgType, uint32_t &serviceId, + uint32_t &methodId, uint32_t &sequence); + + /*! + * @brief This function finds service base on service ID. + * + * @param[in] serviceId Service id number. + * + * @return Pointer to service or NULL. + */ + virtual Service *findServiceWithId(uint32_t serviceId); + +#if ERPC_NESTED_CALLS + friend class ClientManager; + friend class ArbitratedClientManager; + + /*! + * @brief This function runs the server. + * + * @param[in] Request context to check that answer was for nested call. + */ + virtual erpc_status_t run(RequestContext &request) = 0; +#endif + +private: + // Disable copy ctor. + Server(const Server &other); /*!< Disable copy ctor. */ + Server &operator=(const Server &other); /*!< Disable copy ctor. */ +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__SERVER_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_server_setup.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_server_setup.h new file mode 100755 index 00000000..c9216c0d --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_server_setup.h @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * Copyright 2020 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__SERVER_SETUP_H_ +#define _EMBEDDED_RPC__SERVER_SETUP_H_ + +#include "erpc_common.h" +#include "erpc_config_internal.h" +#include "erpc_mbf_setup.h" +#include "erpc_transport_setup.h" +#if ERPC_PRE_POST_ACTION +#include "erpc_pre_post_action.h" +#endif + +/*! + * @addtogroup server_setup + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// API +//////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +//! @brief Opaque server object type. +typedef struct ServerType *erpc_server_t; + +//! @name Server setup +//@{ + +/*! + * @brief This function initializes server. + * + * This function initializes server with all components necessary for running server. + * + * @param[in] transport Initiated transport. + * @param[in] message_buffer_factory Initiated message buffer factory. + * + * @return erpc_server_t Pointer to server structure. + */ +erpc_server_t erpc_server_init(erpc_transport_t transport, erpc_mbf_t message_buffer_factory); + +/*! + * @brief This function de-initializes server. + * + * This function de-initializes server and all components which it own. + * + * @param[in] server Pointer to server structure. + */ +void erpc_server_deinit(erpc_server_t server); + +/*! + * @brief This function adds service to server. + * + * Services contain implementations of functions called from client to server. + * + * @param[in] server Pointer to server structure. + * @param[in] service Service which contains implementations of functions called from client to server. + */ +void erpc_add_service_to_server(erpc_server_t server, void *service); + +/*! + * @brief This function removes service from server. + * + * @param[in] server Pointer to server structure. + * @param[in] service Service which contains implementations of functions called from client to server. + */ +void erpc_remove_service_from_server(erpc_server_t server, void *service); + +/*! + * @brief Can be used to set own crcStart number. + * + * For example can be used generated crc from erpcgen + * which is providing when @crc annotation is used. + * Accessed can be through 'extern const uint32_t erpc_generated_crc;' + * + * @param[in] server Pointer to server structure. + * @param[in] crcStart Set start number for crc. + */ +void erpc_server_set_crc(erpc_server_t server, uint32_t crcStart); +//@} + +//! @name Server control +//@{ + +/*! + * @brief This function calls server implementation until it is stopped. + * + * This is blocking method, where server is trying read (and if it is requested also send) message + * until it is stopped. + * + * @param[in] server Pointer to server structure. + * + * @return Return one of status from erpc_common.h + */ +erpc_status_t erpc_server_run(erpc_server_t server); + +/*! + * @brief This function calls server implementation only once. + * + * This is non-blocking method, where server is trying read (and if it is requested also send) message only once. + * + * @param[in] server Pointer to server structure. + * + * @return Return one of status from erpc_common.h + */ +erpc_status_t erpc_server_poll(erpc_server_t server); + +/*! + * @brief This functions should be used when client is calling quit server. + * + * This method sets server from On to OFF. When the server returns from its implementation, + * erpc_server_deinit() function should be called. + * + * @param[in] server Pointer to server structure. + */ +void erpc_server_stop(erpc_server_t server); + +#if ERPC_MESSAGE_LOGGING +/*! + * @brief This function adds transport object for logging send/receive messages. + * + * @param[in] server Pointer to server structure. + * @param[in] transport Initiated transport. + * + * @retval True When transport was successfully added. + * @retval False When transport wasn't added. + */ +bool erpc_server_add_message_logger(erpc_server_t server, erpc_transport_t transport); +#endif + +#if ERPC_PRE_POST_ACTION +/*! + * @brief This function set callback function executed at the beginning of eRPC call. + * + * @param[in] server Pointer to server structure. + * @param[in] preCB Callback used at the beginning of eRPC call. When NULL and ERPC_PRE_POST_ACTION_DEFAULT + * is enabled then default function will be set. + */ +void erpc_server_add_pre_cb_action(erpc_server_t server, pre_post_action_cb preCB); + +/*! + * @brief This function set callback function executed at the end of eRPC call. + * + * @param[in] server Pointer to server structure. + * @param[in] postCB Callback used at the end of eRPC call. When NULL and ERPC_PRE_POST_ACTION_DEFAULT + * is enabled then default function will be set. + */ +void erpc_server_add_post_cb_action(erpc_server_t server, pre_post_action_cb postCB); +#endif + +//@} + +#ifdef __cplusplus +} +#endif + +/*! @} */ + +#endif // _EMBEDDED_RPC__SERVER_SETUP_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_setup_extensions.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_setup_extensions.h new file mode 100755 index 00000000..d49dbe8b --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_setup_extensions.h @@ -0,0 +1,94 @@ +/* + * Copyright 2020 NXP + * Copyright 2020 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__SETUP_EXTENSIONS_H_ +#define _EMBEDDED_RPC__SETUP_EXTENSIONS_H_ + +#include "erpc_config_internal.h" + +#include + +#if !ERPC_THREADS_IS(NONE) + +#if ERPC_THREADS_IS(FREERTOS) +#include "FreeRTOS.h" +#include "task.h" +#include "timers.h" +#endif + +#endif // ERPC_THREADS + +/*! + * @addtogroup port_setup_extensions + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Declarations +//////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus + +namespace erpc { +/*! + * @brief This function is used for default pre erpc call action. + */ +void erpc_pre_cb_default(void); + +/*! + * @brief This function is used for default post erpc call action. + */ +void erpc_post_cb_default(void); +} // namespace erpc + +extern "C" { +#endif + +#if ERPC_THREADS_IS(FREERTOS) +typedef TimerCallbackFunction_t erpc_call_timer_cb_default_t; +#else +typedef void *erpc_call_timer_cb_default_t; +#endif + +/*! + * @brief This function is used for initializing variables for task freeze detection. + * + * @param[in] erpc_call_timer_cb Callback function called when eRPC call freeze. + * When NULL default callback will be used. + * @param[in] waitTimeMs Platform specific time to throw error cb in case of eRPC call freeze in [ms]. + */ +void erpc_init_call_progress_detection_default(erpc_call_timer_cb_default_t erpc_call_timer_cb, uint32_t waitTimeMs); + +/*! + * @brief This function is used for deinitialization variables for task freeze detection. + */ +void erpc_deinit_call_progress_detection_default(void); + +/*! + * @brief This function returns default eRPC call progress status. + * + * @return True if eRPC call is in progress, otherwise False. + */ +bool erpc_is_call_in_progress_default(void); + +/*! + * @brief This function resets eRPC state. + * + * Can be used when user reinitialize communication between client and server. + */ +void erpc_reset_in_progress_state_default(void); + +#ifdef __cplusplus +} +#endif + +/*! @} */ + +#endif // _EMBEDDED_RPC__SETUP_EXTENSIONS_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_simple_server.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_simple_server.hpp new file mode 100755 index 00000000..efe0ebc0 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_simple_server.hpp @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2014, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * Copyright 2021 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__SIMPLE_SERVER_H_ +#define _EMBEDDED_RPC__SIMPLE_SERVER_H_ + +#include "erpc_server.hpp" + +/*! + * @addtogroup infra_server + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { +/*! + * @brief Based server implementation. + * + * @ingroup infra_server + */ +class SimpleServer : public Server +{ +public: + /*! + * @brief Constructor. + * + * This function initializes object attributes. + */ + SimpleServer(void); + + virtual ~SimpleServer(void); + + /*! + * @brief Run server in infinite loop. + * + * Will never jump out from this function. + */ + virtual erpc_status_t run(void) override; + + /*! + * @brief Run server implementation only if exist message to process. + * + * If is message to process, server process it and jumps out from this function, + * useful for bare-metal because doesn't block main loop, when are not messages + * to process. + * + * @return Return true when server is ON, else false. + */ + virtual erpc_status_t poll(void); + + /*! + * @brief This function sets server from ON to OFF + */ + virtual void stop(void) override; + +protected: + bool m_isServerOn; /*!< Information if server is ON or OFF. */ + + /*! + * @brief Run server implementation. + * + * This function call functions for receiving data, process this data and + * if reply exist, send it back. + */ + erpc_status_t runInternal(void); + + /*! + * @brief This function handle receiving request message and reading base info about message. + * + * @param[in] codec Inout codec to use. + * @param[in] buff Inout codec to use. + * @param[out] msgType Type of received message. Based on message type will be (will be not) sent respond. + * @param[out] serviceId To identify interface. + * @param[out] methodId To identify function in interface. + * @param[out] sequence To connect correct answer with correct request. + * + * @returns #kErpcStatus_Success or based on service handleInvocation. + */ + erpc_status_t runInternalBegin(Codec **codec, MessageBuffer &buff, message_type_t &msgType, uint32_t &serviceId, + uint32_t &methodId, uint32_t &sequence); + + /*! + * @brief This function process message and handle sending respond. + * + * @param[in] codec Inout codec to use. + * @param[in] msgType Type of received message. Based on message type will be (will be not) sent respond. + * @param[in] serviceId To identify interface. + * @param[in] methodId To identify function in interface. + * @param[in] sequence To connect correct answer with correct request. + * + * @returns #kErpcStatus_Success or based on service handleInvocation. + */ + erpc_status_t runInternalEnd(Codec *codec, message_type_t msgType, uint32_t serviceId, uint32_t methodId, + uint32_t sequence); + +#if ERPC_NESTED_CALLS + /*! + * @brief This function runs the server. + * + * @param[in] Request context to check that answer was for nested call. + */ + virtual erpc_status_t run(RequestContext &request) override; +#endif + + /*! + * @brief Disposing message buffers and codecs. + * + * @param[in] codec Pointer to codec to dispose. It contains also message buffer to dispose. + */ + void disposeBufferAndCodec(Codec *codec); +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__SIMPLE_SERVER_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_static_queue.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_static_queue.hpp new file mode 100755 index 00000000..d1996fbb --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_static_queue.hpp @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2015-2016, Freescale Semiconductor, Inc. + * Copyright 2021 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef __embedded_rpc__static_queue__ +#define __embedded_rpc__static_queue__ + +#include +#include + +/*! + * @addtogroup infra_utility + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { +/*! + * @brief Template class which implements static queue as ring buffer + * + * @ingroup infra_utility + */ +template +class StaticQueue +{ +public: + /*! + * @brief Constructor of StaticQueue class. + * + * This function sets capacity of queue, m_head and m_tail indexes to zero. + */ + StaticQueue(void) + { + m_capacity = elementCount; + m_head = 0; + m_tail = 0; + (void)memset(m_storage, 0, sizeof(m_storage)); + } + + /*! + * @brief Destructor of StaticQueue class. + * + * This function free allocated buffer for m_data. + */ + ~StaticQueue(void) {} + /*! + * @brief This function adds element to queue. + * + * @param[in] element Element for adding. + * + * @retval true Element was added. + * @retval false Element was not added, queue is full. + */ + bool add(T element) + { + if ((m_head + 1U) % m_capacity != m_tail) + { + (void)std::memcpy(m_storage[m_head], &element, sizeof(T)); + m_head = (m_head + 1U) % m_capacity; + return true; + } + return false; + } + + /*! + * @brief This function returns element from queue. + * + * @param[out] element Pointer to element to which will be copied element from queue. + * + * @retval true Element was copied from queue. + * @retval false Element was not copied, queue is empty. + */ + bool get(T *element) + { + if (m_tail != m_head) + { + (void)std::memcpy(element, m_storage[m_tail], sizeof(T)); + m_tail = (m_tail + 1U) % m_capacity; + return true; + } + return false; + } + + /*! + * @brief This function returns number of elements in queue. + * + * @return Number of elements in queue. + */ + uint32_t size(void) + { + if (m_head >= m_tail) + { + return m_head - m_tail; + } + return (m_capacity - m_tail + m_head); + } + +protected: + uint64_t m_storage[elementCount] + [(sizeof(T) + sizeof(uint64_t) - 1U) / sizeof(uint64_t)]; /*!< Preallocated space based on data + type size and elements count. */ + uint32_t m_capacity; /*!< Capacity of queue */ + uint32_t volatile m_head; /*!< Index to free slot */ + uint32_t volatile m_tail; /*!< Index to slot with m_data */ +}; + +} // namespace erpc + +/*! @} */ + +#endif // defined(__embedded_rpc__static_queue__) diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_tcp_transport.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_tcp_transport.hpp new file mode 100755 index 00000000..7e1f4da9 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_tcp_transport.hpp @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ +#ifndef _EMBEDDED_RPC__TCP_TRANSPORT_H_ +#define _EMBEDDED_RPC__TCP_TRANSPORT_H_ + +#if defined(__MINGW32__) +#include +#endif + +#include "erpc_framed_transport.hpp" +#include "erpc_threading.h" + +/*! + * @addtogroup tcp_transport + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { +/*! + * @brief Client side of TCP/IP transport. + * + * @ingroup tcp_transport + */ +class TCPTransport : public FramedTransport +{ +public: + /*! + * @brief Constructor. + * + * This function initializes object attributes. + * + * @param[in] isServer True when this transport is used for server side application. + */ + explicit TCPTransport(bool isServer); + + /*! + * @brief Constructor. + * + * This function initializes object attributes. + * + * @param[in] host Specify the host name or IP address of the computer. + * @param[in] port Specify the listening port number. + * @param[in] isServer True when this transport is used for server side application. + */ + TCPTransport(const char *host, uint16_t port, bool isServer); + + /*! + * @brief TCPTransport destructor + */ + virtual ~TCPTransport(void); + + /*! + * @brief This function set host and port of this transport layer. + * + * @param[in] host Specify the host name or IP address of the computer. + * @param[in] port Specify the listening port number. + */ + void configure(const char *host, uint16_t port); + + /*! + * @brief This function will create host on server side, or connect client to the server. + * + * @retval #kErpcStatus_Success When creating host was successful or client connected successfully. + * @retval #kErpcStatus_UnknownName Host name resolution failed. + * @retval #kErpcStatus_ConnectionFailure Connecting to the specified host failed. + */ + virtual erpc_status_t open(void); + + /*! + * @brief This function disconnects client or stop server host. + * + * @param[in] stopServer Specify is server shall be closed as well (stop listen()) + * @retval #kErpcStatus_Success Always return this. + */ + virtual erpc_status_t close(bool stopServer = true); + +protected: + bool m_isServer; /*!< If true then server is using transport, else client. */ + const char *m_host; /*!< Specify the host name or IP address of the computer. */ + uint16_t m_port; /*!< Specify the listening port number. */ +#if defined(__MINGW32__) + SOCKET m_socket; /*!< Socket number. */ +#else + int m_socket; /*!< Socket number. */ +#endif + Thread m_serverThread; /*!< Pointer to server thread. */ + bool m_runServer; /*!< Thread is executed while this is true. */ + + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + + /*! + * @brief This function connect client to the server. + * + * @retval kErpcStatus_Success When client connected successfully. + * @retval kErpcStatus_Fail When client doesn't connected successfully. + */ + virtual erpc_status_t connectClient(void); + + /*! + * @brief This function read data. + * + * @param[inout] data Preallocated buffer for receiving data. + * @param[in] size Size of data to read. + * + * @retval #kErpcStatus_Success When data was read successfully. + * @retval #kErpcStatus_ReceiveFailed When reading data ends with error. + * @retval #kErpcStatus_ConnectionClosed Peer closed the connection. + */ + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; + + /*! + * @brief This function writes data. + * + * @param[in] data Buffer to send. + * @param[in] size Size of data to send. + * + * @retval #kErpcStatus_Success When data was written successfully. + * @retval #kErpcStatus_SendFailed When writing data ends with error. + * @retval #kErpcStatus_ConnectionClosed Peer closed the connection. + */ + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; + + /*! + * @brief Server thread function. + */ + void serverThread(void); + + /*! + * @brief Thread entry point. + * + * Control is passed to the serverThread() method of the TCPTransport instance pointed to + * by the @c arg parameter. + * + * @param arg Thread argument. The pointer to the TCPTransport instance is passed through + * this argument. + */ + static void serverThreadStub(void *arg); +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__TCP_TRANSPORT_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_threading.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_threading.h new file mode 100755 index 00000000..f2825714 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_threading.h @@ -0,0 +1,540 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016-2023 NXP + * Copyright 2021 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef __embedded_rpc__thread__ +#define __embedded_rpc__thread__ + +#include "erpc_config_internal.h" + +#include + +// Exclude the rest of the file if threading is disabled. +#if !ERPC_THREADS_IS(NONE) + +#if ERPC_THREADS_IS(PTHREADS) +#include +#elif ERPC_THREADS_IS(FREERTOS) +#include "FreeRTOS.h" +#include "semphr.h" +#include "task.h" +#elif ERPC_THREADS_IS(ZEPHYR) +#include +#elif ERPC_THREADS_IS(MBED) +#if MBED_CONF_RTOS_PRESENT +#include "rtos.h" +#else +#warning mbed-rpc: Threading is enabled but Mbed RTOS is not present! +#endif +#elif ERPC_THREADS_IS(WIN32) +#include "windows.h" +#elif ERPC_THREADS_IS(THREADX) +#include "tx_api.h" + +#endif // ERPC_THREADS + +/*! + * @addtogroup port_threads + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Types +//////////////////////////////////////////////////////////////////////////////// + +//! @brief Thread function type. +//! +//! @param arg User provided argument that was passed into the start() method. +typedef void (*thread_entry_t)(void *arg); + +//////////////////////////////////////////////////////////////////////////////// +// Declarations +//////////////////////////////////////////////////////////////////////////////// + +#if defined(__cplusplus) + +namespace erpc { +/*! + * @brief Simple thread class. + * + * @ingroup port_threads + */ +class Thread +{ +public: + //! @brief Unique identifier for a thread. + typedef void *thread_id_t; +#if ERPC_THREADS_IS(FREERTOS) + typedef StackType_t *thread_stack_pointer; +#else + typedef void *thread_stack_pointer; +#endif + + /*! + * @brief Default constructor for use with the init() method. + * + * If this constructor is used, the init() method must be called before the thread can be + * started. + * + * @param[in] name Optional name for the thread. + */ + Thread(const char *name = 0); + + /*! + * @brief Constructor. + * + * This constructor fully initializes the thread object. + * + * @param[in] entry + * @param[in] priority + * @param[in] stackSize + * @param[in] name Optional name for the thread. + * @param[in] stackPtr Mandatory task stack pointer for static api usage. + */ + Thread(thread_entry_t entry, uint32_t priority = 0, uint32_t stackSize = 0, const char *name = 0, + thread_stack_pointer stackPtr = NULL); + + /*! + * @brief Destructor. + */ + virtual ~Thread(void); + + /*! + * @brief This function sets name for thread. + * + * @param[in] name Name for thread. + */ + void setName(const char *name) { m_name = name; } + + /*! + * @brief This function returns name of thread. + * + * @return Name of thread. + */ + const char *getName(void) const { return m_name; } + + /*! + * @brief This function initializes thread. + * + * @param[in] entry Entry function. + * @param[in] priority Task priority. + * @param[in] stackSize Stack size. + * @param[in] stackPtr Mandatory task stack pointer for static api usage. + */ + void init(thread_entry_t entry, uint32_t priority = 0, uint32_t stackSize = 0, + thread_stack_pointer stackPtr = NULL); + + /*! + * @brief This function starts thread execution. + * + * @param[in] arg Function argument. + */ + void start(void *arg = 0); + + /*! + * @brief This function puts thread to sleep. + * + * @param[in] usecs Time for sleeping in [us]. + */ + static void sleep(uint32_t usecs); + + /*! + * @brief This function returns current thread id. + * + * @return Thread id. + */ + thread_id_t getThreadId(void) const + { +#if ERPC_THREADS_IS(PTHREADS) + return reinterpret_cast(m_thread); +#elif ERPC_THREADS_IS(FREERTOS) + return reinterpret_cast(m_task); +#elif ERPC_THREADS_IS(ZEPHYR) + return reinterpret_cast(m_thread_id); +#elif ERPC_THREADS_IS(MBED) + return reinterpret_cast(m_thread->get_id()); +#elif ERPC_THREADS_IS(WIN32) + return reinterpret_cast(m_thread); +#elif ERPC_THREADS_IS(THREADX) + return reinterpret_cast(m_thread.tx_thread_id); +#endif + } + + /*! + * @brief This function returns thread id where function is called. + * + * @return Thread id. + */ + static thread_id_t getCurrentThreadId(void) + { +#if ERPC_THREADS_IS(PTHREADS) + return reinterpret_cast(pthread_self()); +#elif ERPC_THREADS_IS(FREERTOS) + return reinterpret_cast(xTaskGetCurrentTaskHandle()); +#elif ERPC_THREADS_IS(ZEPHYR) + return reinterpret_cast(k_current_get()); +#elif ERPC_THREADS_IS(MBED) + return reinterpret_cast(rtos::ThisThread::get_id()); +#elif ERPC_THREADS_IS(WIN32) + return reinterpret_cast(GetCurrentThread()); +#elif ERPC_THREADS_IS(THREADX) + return reinterpret_cast(tx_thread_identify()); +#endif + } + +#if ERPC_THREADS_IS(ZEPHYR) + /*! + * @brief This function sets stack pointer for Zephyr task. + * + * @param[in] stack Stack pointer. + */ + void setStackPointer(k_thread_stack_t *stack) { m_stack = stack; } +#endif + + /*! + * @brief This function returns Thread instance where functions is called. + * + * @return Thread instance. + */ + static Thread *getCurrentThread(void); + + /*! + * @brief Compare operator compares two threads. + * + * @param[in] o Thread instance. + * + * @retval true When threads are same. + * @retval false When threads aren't same. + */ + bool operator==(Thread &o); + +protected: + /*! + * @brief This function execute entry function. + */ + virtual void threadEntryPoint(void); + +private: + const char *m_name; /*!< Thread name. */ + thread_entry_t m_entry; /*!< Thread entry function. */ + void *m_arg; /*!< Entry parameter. */ + uint32_t m_stackSize; /*!< Stack size. */ + uint32_t m_priority; /*!< Task priority. */ + thread_stack_pointer m_stackPtr; /*!< Task pointer. */ +#if ERPC_THREADS_IS(PTHREADS) + static pthread_key_t s_threadObjectKey; /*!< Thread key. */ + pthread_t m_thread; /*!< Current thread. */ +#elif ERPC_THREADS_IS(FREERTOS) + TaskHandle_t m_task; /*!< Current task. */ + Thread *m_next; /*!< Pointer to next Thread. */ + static Thread *s_first; /*!< Pointer to first Thread. */ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + StaticTask_t m_staticTask; /*!< Hold static task data. */ +#endif +#elif ERPC_THREADS_IS(ZEPHYR) + struct k_thread m_thread; /*!< Current thread. */ + k_tid_t m_thread_id; + k_thread_stack_t *m_stack; /*!< Pointer to stack. */ +#elif ERPC_THREADS_IS(MBED) + rtos::Thread *m_thread; /*!< Underlying Thread instance */ + Thread *m_next; /*!< Pointer to next Thread. */ + static Thread *s_first; /*!< Pointer to first Thread. */ +#elif ERPC_THREADS_IS(WIN32) + HANDLE m_thread; + unsigned int m_thrdaddr; + Thread *m_next; /*!< Pointer to next Thread. */ + static Thread *s_first; /*!< Pointer to first Thread. */ + static CRITICAL_SECTION m_critical_section; + static BOOL m_critical_section_inited; +#elif ERPC_THREADS_IS(THREADX) + TX_THREAD m_thread; /*!< Underlying Thread instance */ + Thread *m_next; /*!< Pointer to next Thread. */ + static Thread *s_first; /*!< Pointer to first Thread. */ +#endif + +#if ERPC_THREADS_IS(PTHREADS) + + /*! + * @brief This function execute threadEntryPoint function. + * + * @param[in] arg Thread to execute. + */ + static void *threadEntryPointStub(void *arg); +#elif ERPC_THREADS_IS(FREERTOS) + + /*! + * @brief This function execute threadEntryPoint function. + * + * @param[in] arg Thread to execute. + */ + static void threadEntryPointStub(void *arg); +#elif ERPC_THREADS_IS(ZEPHYR) + + /*! + * @brief This function execute threadEntryPoint function. + * + * @param[in] arg1 Thread to execute. + * @param[in] arg2 + * @param[in] arg3 + */ + static void threadEntryPointStub(void *arg1, void *arg2, void *arg3); + +#elif ERPC_THREADS_IS(MBED) + + /*! + * @brief This function execute threadEntryPoint function. + * + * @param[in] arg Thread to execute. + */ + static void threadEntryPointStub(void *arg); + +#elif ERPC_THREADS_IS(WIN32) + + /*! + * @brief This function execute threadEntryPoint function. + * + * @param[in] arg Thread to execute. + */ + static unsigned WINAPI threadEntryPointStub(void *arg); + +#elif ERPC_THREADS_IS(THREADX) + + /*! + * @brief This function execute threadEntryPoint function. + * + * @param[in] arg Thread to execute. + */ + static void threadEntryPointStub(ULONG arg); +#endif + +private: + /*! + * @brief Copy constructor. + * + * @param[in] o Thread to copy. + */ + Thread(const Thread &o); + + /*! + * @brief Assign operator. + * + * @param[in] o Thread to assign. + */ + Thread &operator=(const Thread &o); +}; + +/*! + * @brief Mutex. + * + * If the OS supports it, the mutex will be recursive. + * + * @ingroup port_threads + */ +class Mutex +{ +public: + /*! + * @brief + */ + class Guard + { + public: + /*! + * @brief Constructor. + * + * @param[in] mutex to lock. + */ + Guard(Mutex &mutex) : m_mutex(mutex) { (void)m_mutex.lock(); } + /*! + * @brief Destructor. + */ + ~Guard(void) { (void)m_mutex.unlock(); } + + private: + Mutex &m_mutex; /*!< Mutex to lock. */ + }; + + /*! + * @brief Constructor. + */ + Mutex(void); + + /*! + * @brief Destructor. + */ + ~Mutex(void); + + /*! + * @brief This function try lock mutex. + * + * @retval true When mutex locked successfully. + * @retval false When mutex didn't locked. + */ + bool tryLock(void); + + /*! + * @brief This function lock mutex. + * + * @retval true When mutex locked successfully. + * @retval false When mutex didn't locked. + */ + bool lock(void); + + /*! + * @brief This function unlock mutex. + * + * @retval true When mutex unlocked successfully. + * @retval false When mutex didn't unlocked. + */ + bool unlock(void); + +#if ERPC_THREADS_IS(PTHREADS) + /*! + * @brief This function returns pointer to mutex. + * + * @return Pointer to mutex. + */ + pthread_mutex_t *getPtr(void) { return &m_mutex; } +#endif + +private: +#if ERPC_THREADS_IS(PTHREADS) + pthread_mutex_t m_mutex; /*!< Mutex.*/ +#elif ERPC_THREADS_IS(FREERTOS) + SemaphoreHandle_t m_mutex; /*!< Mutex.*/ + StaticSemaphore_t m_staticQueue; /*!< Static queue. */ +#elif ERPC_THREADS_IS(ZEPHYR) + struct k_mutex m_mutex; /*!< Mutex.*/ +#elif ERPC_THREADS_IS(MBED) + rtos::Mutex *m_mutex; /*!< Mutex. */ +#elif ERPC_THREADS_IS(WIN32) + HANDLE m_mutex; +#elif ERPC_THREADS_IS(THREADX) + TX_MUTEX m_mutex; +#endif + +private: + /*! + * @brief Copy constructor. + * + * @param[in] o Mutex to copy. + */ + Mutex(const Mutex &o); + /*! + * @brief Copy constructor. + * + * @param[in] o Mutex to copy. + */ + Mutex &operator=(const Mutex &o); +}; + +/*! + * @brief Simple semaphore class. + * + * @ingroup port_threads + */ +class Semaphore +{ +public: + /*! + * @brief Variable for semaphore to wait forever. + */ + static const uint32_t kWaitForever = 0xffffffffu; + + /*! + * @brief Constructor. + * + * @param[in] count Semaphore number. + */ + Semaphore(int count = 0); + + /*! + * @brief Destructor. + */ + ~Semaphore(void); + + /*! + * @brief This function puts semaphore. + */ + void put(void); + +#if ERPC_THREADS_IS(FREERTOS) + /*! + * @brief This function puts semaphore from interrupt. + */ + void putFromISR(void); +#endif // ERPC_HAS_FREERTOS + + /*! + * @brief This function get semaphore. + * + * @param[in] timeoutUsecs Time how long can wait for getting semaphore in [us]. + * + * @retval true When semaphore got successfully. + * @retval false When failed getting semaphore or if timeout expired. + */ + bool get(uint32_t timeoutUsecs = kWaitForever); + + /*! + * @brief This function returns semaphore count number. + * + * @return Semaphore count number. + */ + int getCount(void) const; + +private: +#if ERPC_THREADS_IS(PTHREADS) + int m_count; /*!< Semaphore count number. */ + pthread_cond_t m_cond; /*!< Condition variable. Allows threads to suspend execution and relinquish the processors + until some predicate on shared data is satisfied. */ + Mutex m_mutex; /*!< Mutext. */ +#elif ERPC_THREADS_IS(FREERTOS) + SemaphoreHandle_t m_sem; /*!< Semaphore. */ + StaticSemaphore_t m_staticQueue; /*!< Static queue. */ +#elif ERPC_THREADS_IS(ZEPHYR) + struct k_sem m_sem; /*!< Semaphore. */ +#elif ERPC_THREADS_IS(MBED) + rtos::Semaphore *m_sem; /*!< Semaphore. */ + int m_count; /*!< Semaphore count number. */ +#elif ERPC_THREADS_IS(WIN32) + Mutex m_mutex; /*!< Mutext. */ + int m_count; + HANDLE m_sem; +#elif ERPC_THREADS_IS(THREADX) + TX_SEMAPHORE m_sem; /*!< Semaphore. */ +#endif + +private: + /*! + * @brief Copy constructor. + * + * @param[in] o Semaphore to copy. + */ + Semaphore(const Semaphore &o); + /*! + * @brief Copy constructor. + * + * @param[in] o Semaphore to copy. + */ + Semaphore &operator=(const Semaphore &o); +}; + +} // namespace erpc + +#endif // defined(__cplusplus) + +/*! @} */ + +#endif // ERPC_THREADS + +#endif // defined(__embedded_rpc__thread__) +//////////////////////////////////////////////////////////////////////////////// +// EOF +//////////////////////////////////////////////////////////////////////////////// diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_transport.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_transport.hpp new file mode 100755 index 00000000..88fde0e3 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_transport.hpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2014, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__TRANSPORT_H_ +#define _EMBEDDED_RPC__TRANSPORT_H_ + +#include "erpc_common.h" +#include "erpc_crc16.hpp" +#include "erpc_message_buffer.hpp" + +#include + +/*! + * @addtogroup infra_transport + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { + +/*! + * @brief Abstract interface for transport layer. + * + * @ingroup infra_transport + */ +class Transport +{ +public: + /*! + * @brief Constructor. + */ + Transport(void) {} + + /*! + * @brief Transport destructor + */ + virtual ~Transport(void) {} + + /** + * @brief Size of data placed in MessageBuffer before serializing eRPC data. + * + * @return uint8_t Amount of bytes, reserved before serialized data. + */ + virtual uint8_t reserveHeaderSize(void) { return 0; } + + /*! + * @brief Prototype for receiving message. + * + * Each transport layer need define this function. + * + * @param[out] message Will return pointer to received message buffer. + * + * @return based on receive implementation. + */ + virtual erpc_status_t receive(MessageBuffer *message) = 0; + + /*! + * @brief Prototype for send message. + * + * Each transport layer need define this function. + * + * @param[in] message Pass message buffer to send. + * + * @return based on send implementation. + */ + virtual erpc_status_t send(MessageBuffer *message) = 0; + + /*! + * @brief Poll for an incoming message. + * + * This function should return true if are some messages to process by server, + * the return value should be tested before calling receive function to avoid + * waiting for a new message (receive can be implemented as blocking function). + * + * @retval True when a message is available to process, else false. + */ + virtual bool hasMessage(void) { return true; } + + /*! + * @brief This functions sets the CRC-16 implementation. + * + * @param[in] crcImpl Object containing crc-16 compute function. + */ + virtual void setCrc16(Crc16 *crcImpl) { (void)crcImpl; } + + /*! + * @brief This functions gets the CRC-16 object. + * + * @return Crc16* Pointer to CRC-16 object containing crc-16 compute function. + */ + virtual Crc16 *getCrc16(void) { return NULL; } +}; + +/*! + * @brief Abstract interface for transport factory. + * + * @ingroup infra_transport + */ +class TransportFactory +{ +public: + /*! + * @brief Constructor. + */ + TransportFactory(void) {} + + /*! + * @brief TransportFactory destructor + */ + virtual ~TransportFactory(void) {} + + /*! + * @brief Return created transport object. + * + * @return Pointer to created transport object. + */ + virtual Transport *create(void) = 0; +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC__TRANSPORT_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_transport_arbitrator.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_transport_arbitrator.hpp new file mode 100755 index 00000000..6a55efb0 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_transport_arbitrator.hpp @@ -0,0 +1,230 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ +#if !defined(__embedded_rpc__transport_arbitrator__) +#define __embedded_rpc__transport_arbitrator__ + +#include "erpc_client_manager.h" +#include "erpc_codec.hpp" +#include "erpc_threading.h" +#include "erpc_transport.hpp" + +/*! + * @addtogroup infra_transport + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { +class Codec; + +/*! + * @brief Interposer to share transport between client and server. + * + * Allocates memory for client receive request info. This memory is never freed. It is put on a + * free list and is reused for future client receives. The class will allocate as many client + * receive info structs as the maximum number of simultaneous client receive requests from different + * threads. + * + * @ingroup infra_transport + */ +class TransportArbitrator : public Transport +{ +public: + //! @brief Represents a single client's receive request. + typedef uintptr_t client_token_t; + + /*! + * @brief Constructor. + */ + TransportArbitrator(void); + + /*! + * @brief Destructor. + */ + virtual ~TransportArbitrator(void); + + /** + * @brief Size of data placed in MessageBuffer before serializing eRPC data. + * + * @return uint8_t Amount of bytes, reserved before serialized data. + */ + virtual uint8_t reserveHeaderSize(void) override; + + /*! + * @brief Prototype for receiving message. + * + * Each transport layer need define this function. + * + * @param[out] message Will return pointer to received message buffer. + * + * @return based on receive implementation. + */ + virtual erpc_status_t receive(MessageBuffer *message) override; + + /*! + * @brief Prototype for send message. + * + * Each transport layer need define this function. + * + * @param[in] message Pass message buffer to send. + * + * @return based on send implementation. + */ + virtual erpc_status_t send(MessageBuffer *message) override; + + /*! + * @brief Check if the underlying shared transport has a message + * + * @retval The underlying transport is expected to return true when a message is available to + * process and false otherwise. + */ + virtual bool hasMessage(void) override; + + /*! + * @brief This functions sets the CRC-16 implementation. + * + * @param[in] crcImpl Object containing crc-16 compute function. + */ + virtual void setCrc16(Crc16 *crcImpl) override; + + /*! + * @brief This functions gets the CRC-16 object. + * + * @return Crc16* Pointer to CRC-16 object containing crc-16 compute function. + */ + virtual Crc16 *getCrc16(void) override; + + /*! + * @brief This function set shared client/server transport. + * + * @param[in] shared Shared client/server transport. + */ + void setSharedTransport(Transport *shared); + + /*! + * @brief This function returns shared client/server transport. + * + * @return Transport * Returns shared client/server transport. + */ + Transport *getSharedTransport(void); + + /*! + * @brief This function set codec. + * + * @param[in] codec Codec. + */ + void setCodec(Codec *codec); + + /*! + * @brief This function get codec. + * + * @return Codec * Pointer to codec used within transport. + */ + Codec *getCodec(void); + + /*! + * @brief Add a client request to the client list. + * + * This call is made by the client thread prior to sending the invocation to the server. It + * ensures that the transport arbitrator has the client's response message buffer ready in + * case it sees the response before the client even has a chance to call clientReceive(). + * + * @param[in] request Reuquest context for receive action. + * + * @return A token is returned to the client + */ + client_token_t prepareClientReceive(RequestContext &request); + + /*! + * @brief Receive method for the client. + * + * Blocks until the a reply message is received with the expected sequence number that is + * associated with @a token. The client must have called prepareClientReceive() previously. + * + * @param[in] token The token previously returned by prepareClientReceive(). + * + * @return erpc_status_t Return erpc status of client receive function. + */ + erpc_status_t clientReceive(client_token_t token); + + /*! + * @brief This function free client token. + * + * @param[in] token the client token to remove. + */ + void removePendingClient(client_token_t token); + + /*! + * @brief Request info for a client trying to receive a response. + */ + struct PendingClientInfo + { + RequestContext *m_request; /*!< Client request context. */ + Semaphore m_sem; /*!< Client semaphore. */ + bool m_isValid; /*!< This struct validation. */ + PendingClientInfo *m_next; /*!< Next client pending information. */ + + /*! + * @brief Constructor. + */ + PendingClientInfo(void); + + /*! + * @brief Destructor. + */ + ~PendingClientInfo(void); + }; + +protected: + Transport *m_sharedTransport; //!< Transport being shared through this arbitrator. + Codec *m_codec; //!< Codec used to read incoming message headers. + + PendingClientInfo *m_clientList; //!< Active client receive requests. + PendingClientInfo *m_clientFreeList; //!< Unused client receive info structs. + Mutex m_clientListMutex; //!< Mutex guarding the client active and free lists. + + /*! + * @brief Create a Pending Client object. + * + * @return PendingClientInfo* Return created object. + */ + PendingClientInfo *createPendingClient(void); + + /*! + * @brief This function adds pending client. + * + * @return Pending client information. + */ + PendingClientInfo *addPendingClient(void); + + /*! + * @brief This function removes pending client list. + * + * @param[in] list Pending client list to remove. + */ + void freeClientList(PendingClientInfo *list); + +private: + // Disable copy ctor. + TransportArbitrator(const TransportArbitrator &other); /*!< Disable copy ctor. */ + TransportArbitrator &operator=(const TransportArbitrator &other); /*!< Disable copy ctor. */ +}; + +} // namespace erpc + +/*! @} */ + +#endif // defined(__embedded_rpc__transport_arbitrator__) +//////////////////////////////////////////////////////////////////////////////// +// EOF +//////////////////////////////////////////////////////////////////////////////// diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_transport_setup.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_transport_setup.h new file mode 100755 index 00000000..65c3d4be --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_transport_setup.h @@ -0,0 +1,598 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016-2024 NXP + * Copyright 2019 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _ERPC_TRANSPORT_SETUP_H_ +#define _ERPC_TRANSPORT_SETUP_H_ + +/*! + * @addtogroup transport_setup + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Types +//////////////////////////////////////////////////////////////////////////////// + +//! @brief Opaque transport object type. +typedef struct ErpcTransport *erpc_transport_t; +//! @brief Ready callback object type for RPMsg-Lite transport. +typedef void (*rpmsg_ready_cb)(void); + +//////////////////////////////////////////////////////////////////////////////// +// API +//////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +//! @name Transport setup +//@{ + +//! @name DSPI transport setup +//@{ + +/*! + * @brief Create a DSPI master transport. + * + * Create DSPI master transport instance, to be used at master core. + * + * @param[in] baseAddr Base address of DSPI peripheral used in this transport layer. + * @param[in] baudRate DSPI baud rate. + * @param[in] srcClock_Hz DSPI source clock in Hz. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_dspi_master_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); + +/*! + * @brief Deinitialize DSPI master transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_dspi_master_deinit(erpc_transport_t transport); + +/*! + * @brief Create a DSPI slave transport. + * + * Create DSPI slave transport instance, to be used at slave core. + * + * @param[in] baseAddr Base address of DSPI peripheral used in this transport layer. + * @param[in] baudRate DSPI baud rate. + * @param[in] srcClock_Hz DSPI source clock in Hz. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_dspi_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); + +/*! + * @brief Deinitialize DSPI slave transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_dspi_slave_deinit(erpc_transport_t transport); + +//@} + +//! @name I2C transport setup +//@{ + +/*! + * @brief Create an I2C slave transport. + * + * Create I2C slave transport instance, to be used at slave core. + * + * @param[in] baseAddr Base address of I2C peripheral used in this transport layer. + * @param[in] baudRate SPI baud rate. + * @param[in] srcClock_Hz I2C source clock in Hz. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_i2c_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); + +/*! + * @brief Deinitialize I2C slave transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_i2c_slave_deinit(erpc_transport_t transport); + +//@} + +//! @name LPI2C transport setup +//@{ + +/*! + * @brief Create an LPI2C slave transport. + * + * Create LPI2C slave transport instance, to be used at slave core. + * + * @param[in] baseAddr Base address of LPI2C peripheral used in this transport layer. + * @param[in] baudRate SPI baud rate. + * @param[in] srcClock_Hz LPI2C source clock in Hz. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_lpi2c_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); + +/*! + * @brief Deinitialize LPI2C slave transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_lpi2c_slave_deinit(erpc_transport_t transport); + +//@} + +//! @name LPSPI transport setup +//@{ + +/*! + * @brief Create a LPSPI slave transport. + * + * Create LPSPI slave transport instance, to be used at slave core. + * + * @param[in] baseAddr Base address of LPSPI peripheral used in this transport layer. + * @param[in] baudRate LPSPI baud rate. + * @param[in] srcClock_Hz LPSPI source clock in Hz. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_lpspi_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); + +/*! + * @brief Deinitialize LPSPI slave transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_lpspi_slave_deinit(erpc_transport_t transport); + +//@} + +//! @name MU transport setup +//@{ + +/*! + * @brief Create an MU transport. + * + * Create Messaging Unit (MU) transport instance, to be used on both the server + * and the client side. Base address of the MU peripheral needs to be passed. + * + * @param[in] baseAddr Base address of MU peripheral. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_mu_init(void *baseAddr); + +/*! + * @brief Deinitialize MU transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_mu_deinit(erpc_transport_t transport); + +//@} + +//! @name Linux RPMSG endpoint setup +//@{ + +/*! + * @brief Create an Linux RPMSG endpoint transport. + * + * This function is using RPMSG endpoints based on this implementation: + * github.com/nxp-mcuxpresso/rpmsg-sysfs/tree/0aa1817545a765c200b1b2f9b6680a420dcf9171 . + * + * When local/remote address is set to '-1', then default addresses will be used. + * When type is set to '0', then Datagram model will be used, else Stream. + * + * @param[in] local_addr Local endpoint address. + * @param[in] type Datagram (0) or Stream (1). + * @param[in] remote_addr Remote endpoint address. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_rpmsg_linux_init(int16_t local_addr, int8_t type, int16_t remote_addr); + +/*! + * @brief Deinitialize an Linux RPMSG endpoint transport. + * + * This function deinitialize the Linux RPMSG endpoint transport. + * + * @param[in] transport Transport which was returned from init function. + */ +void erpc_transport_rpmsg_linux_deinit(erpc_transport_t transport); + +//@} + +//! @name RPMsg-Lite transport setup +//@{ + +/*! + * @brief Create an RPMsg-Lite transport. + * + * Create RPMsg-Lite baremetal transport instance, to be used at master core. + * + * @param[in] src_addr Address of local RPMsg endpoint used for communication. + * @param[in] dst_addr Address of remote RPMsg endpoint used for communication. + * @param[in] rpmsg_link_id Link ID used to define the rpmsg-lite instance, see + * rpmsg_platform.h + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_rpmsg_lite_master_init(uint32_t src_addr, uint32_t dst_addr, uint32_t rpmsg_link_id); + +/*! + * @brief Deinitialize RPMsg-Lite transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_rpmsg_lite_master_deinit(erpc_transport_t transport); + +/*! + * @brief Create an RPMsg-Lite transport. + * + * Create RPMsg-Lite baremetal transport instance, to be used at slave/remote + * core. + * + * @param[in] src_addr Address of local RPMsg endpoint used for communication. + * @param[in] dst_addr Address of remote RPMsg endpoint used for communication. + * @param[in] start_address Shared memory base address used for this instance of + * RPMsg-Lite. + * @param[in] rpmsg_link_id Link ID used to define the rpmsg-lite instance, see + * rpmsg_platform.h. + * @param[in] ready Callback function, which gets called, when RPMsg is + * initialized and master core can be notified. + * @param[in] nameservice_name Name of the nameservice channel to be announced + * to the other core. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_rpmsg_lite_remote_init(uint32_t src_addr, uint32_t dst_addr, void *start_address, + uint32_t rpmsg_link_id, rpmsg_ready_cb ready, + char *nameservice_name); + +/*! + * @brief Deinitialize RPMsg-Lite transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_rpmsg_lite_remote_deinit(erpc_transport_t transport); + +/*! + * @brief Create an RPMsg-Lite RTOS transport. + * + * Create RPMsg-Lite RTOS transport instance, to be used at master core. + * + * @param[in] src_addr Address of local RPMsg endpoint used for communication. + * @param[in] dst_addr Address of remote RPMsg endpoint used for communication. + * @param[in] rpmsg_link_id Link ID used to define the rpmsg-lite instance, see + * rpmsg_platform.h + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_rpmsg_lite_rtos_master_init(uint32_t src_addr, uint32_t dst_addr, + uint32_t rpmsg_link_id); + +/*! + * @brief Deinitialize RPMsg-Lite RTOS transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_rpmsg_lite_rtos_master_deinit(erpc_transport_t transport); + +/*! + * @brief Create an RPMsg-Lite RTOS transport. + * + * Create RPMsg-Lite RTOS transport instance, to be used at slave/remote core. + * + * @param[in] src_addr Address of local RPMsg endpoint used for communication. + * @param[in] dst_addr Address of remote RPMsg endpoint used for communication. + * @param[in] start_address Shared memory base address used for this instance of + * RPMsg-Lite. + * @param[in] rpmsg_link_id Link ID used to define the rpmsg-lite instance, see + * rpmsg_platform.h. + * @param[in] ready Callback function, which gets called, when RPMsg is + * initialized and master core can be notified. + * @param[in] nameservice_name Name of the nameservice channel to be announced + * to the other core. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_rpmsg_lite_rtos_remote_init(uint32_t src_addr, uint32_t dst_addr, void *start_address, + uint32_t rpmsg_link_id, rpmsg_ready_cb ready, + char *nameservice_name); + +/*! + * @brief Deinitialize RPMsg-Lite RTOS transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_rpmsg_lite_rtos_remote_deinit(erpc_transport_t transport); + +/*! + * @brief Create an RPMsg-Lite TTY transport. + * + * Create RPMsg-Lite TTY transport instance, to be used at slave/remote core. + * This function is mainly used with Linux running on the master core. + * + * @param[in] src_addr Address of local RPMsg endpoint used for communication. + * @param[in] dst_addr Address of remote RPMsg endpoint used for communication. + * @param[in] start_address Shared memory base address used for this instance of + * RPMsg-Lite. + * @param[in] rpmsg_link_id Link ID used to define the rpmsg-lite instance, see + * rpmsg_platform.h. + * @param[in] ready Callback function, which gets called, when RPMsg is + * initialized and master core can be notified. + * @param[in] nameservice_name Name of the nameservice channel to be announced + * to the other core. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_rpmsg_lite_tty_rtos_remote_init(uint32_t src_addr, uint32_t dst_addr, + void *start_address, uint32_t rpmsg_link_id, + rpmsg_ready_cb ready, char *nameservice_name); + +/*! + * @brief Deinitialize an RPMSG lite tty rtos transport. + * + * This function deinitialize the RPMSG lite tty rtos transport. + * + * @param[in] transport Transport which was returned from init function. + */ +void erpc_transport_rpmsg_lite_tty_rtos_remote_deinit(erpc_transport_t transport); +//@} + +//! @name Host PC serial port transport setup +//@{ + +/*! + * @brief Create a host PC serial port transport. + * + * Create a host PC serial port transport instance. + * + * @param[in] portName Port name. + * @param[in] baudRate Baud rate. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_serial_init(const char *portName, long baudRate); + +/*! + * @brief Deinitialize a host PC serial port transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_serial_deinit(erpc_transport_t transport); + +//@} + +//! @name SPI transport setup +//@{ + +/*! + * @brief Create a SPI master transport. + * + * Create SPI master transport instance, to be used at master core. + * + * @param[in] baseAddr Base address of SPI peripheral used in this transport layer. + * @param[in] baudRate SPI baud rate. + * @param[in] srcClock_Hz SPI source clock in Hz. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_spi_master_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); + +/*! + * @brief Deinitialize SPI master transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_spi_master_deinit(erpc_transport_t transport); + +/*! + * @brief Create a SPI slave transport. + * + * Create SPI slave transport instance, to be used at slave core. + * + * @param[in] baseAddr Base address of SPI peripheral used in this transport layer. + * @param[in] baudRate SPI baud rate. + * @param[in] srcClock_Hz SPI source clock in Hz. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_spi_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); + +/*! + * @brief Deinitialize SPI slave transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_spi_slave_deinit(erpc_transport_t transport); + +//@} + +//! @name SPIdev transport setup +//@{ + +/*! + * @brief Create a SPIdev transport. + * + * Create SPIdev master transport instance, to be used at master core. + * + * @param[in] spidev SPI device name. + * @param[in] speed_Hz SPI clock speed in Hz. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_spidev_master_init(const char *spidev, uint32_t speed_Hz); + +/*! + * @brief Deinitialize SPIdev transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_spidev_master_deinit(erpc_transport_t transport); + +//@} + +//! @name TCP transport setup +//@{ + +/*! + * @brief Create and open TCP transport + * + * For server, create a TCP listen socket and wait for connections + * For client, connect to server + * + * @param[in] host hostname/IP address to listen on or server to connect to + * @param[in] port port to listen on or server to connect to + * @param[in] isServer true if we are a server + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_tcp_init(const char *host, uint16_t port, bool isServer); + +/*! + * @brief Close TCP connection + * + * For server, stop listening and close all sockets. Note that the server mode + * uses and accept() which is a not-recommended blocking method so we can't exit + * until a connection attempts is made. This is a deadlock but assuming that TCP + * code is supposed to be for test, I assume it's acceptable. Otherwise a non-blocking + * socket or select() shoudl be used + * For client, close server connection + * + * @param[in] transport Transport which was returned from init function. + */ +void erpc_transport_tcp_close(erpc_transport_t transport); + +/*! + * @brief Deinitialize TCP transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_tcp_deinit(erpc_transport_t transport); + +//@} + +//! @name CMSIS UART transport setup +//@{ + +/*! + * @brief Create a CMSIS UART transport. + * + * Create a CMSIS UART transport instance, to be used on both the server + * and the client side. + * + * @param[in] uartDrv CMSIS USART driver structure address (Driver Control Block). + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_cmsis_uart_init(void *uartDrv); + +/*! + * @brief Deinitialize CMSIS UART transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_cmsis_uart_deinit(erpc_transport_t transport); + +//@} + +//! @name Zephyr transports setup +//@{ + +/*! + * @brief Create a Zephyr UART transport. + * + * Create a Zephyr UART transport instance, to be used on both the server + * and the client side. + * + * @param[in] dev Zephyr UART device address. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_zephyr_uart_init(void *dev); + +/*! + * @brief Deinitialize Zephyr UART transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_zephyr_uart_deinit(erpc_transport_t transport); + +/*! + * @brief Create a Zephyr MBOX transport. + * + * Create a Zephyr MBOX transport instance, to be used on both the server + * and the client side. + * + * @param[in] dev Zephyr MBOX device address. + * @param[in] tx_channel Zephyr MBOX transmit channel. + * @param[in] rx_channel Zephyr MBOX receive channel. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_zephyr_mbox_init(void *dev, void *tx_channel, void *rx_channel); + +/*! + * @brief Deinitialize Zephyr MBOX transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_zephyr_mbox_deinit(erpc_transport_t transport); + +//@} + +//! @name USB CDC transport setup +//@{ + +/*! + * @brief Create an USB CDC transport. + * + * Create an USB CDC transport instance. + * + * @param[in] serialHandle Pointer to point to a memory space of size #SERIAL_MANAGER_HANDLE_SIZE allocated by the + * caller, see serial manager header file. + * @param[in] serialConfig Pointer to user-defined configuration structure allocated by the caller, see serial manager + * header file. + * @param[in] usbCdcConfig Pointer to serial port usb config structure allocated by the caller, see serial manager + * header file. + * @param[in] usbRingBuffer Pointer to point serial manager ring buffer allocated by the caller, see serial manager + * header file. + * @param[in] usbRingBufferLength Serial manager ring buffer size. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_usb_cdc_init(void *serialHandle, void *serialConfig, void *usbCdcConfig, + uint8_t *usbRingBuffer, uint32_t usbRingBufferLength); + +/*! + * @brief Deinitialize USB CDC transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_usb_cdc_deinit(erpc_transport_t transport); + +//@} + +//@} + +#ifdef __cplusplus +} +#endif + +/*! @} */ + +#endif // _ERPC_TRANSPORT_SETUP_H_ diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_utils.hpp b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_utils.hpp new file mode 100755 index 00000000..060aec3a --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_utils.hpp @@ -0,0 +1,17 @@ +/* + * Copyright 2023 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +namespace erpc { +typedef void *functionPtr_t; +typedef functionPtr_t *arrayOfFunctionPtr_t; + +bool findIndexOfFunction(const arrayOfFunctionPtr_t sourceArrayOfFunctionPtr, uint16_t sourceArrayLength, + const functionPtr_t functionPtr, uint16_t &retVal); +} // namespace erpc diff --git a/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_version.h b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_version.h new file mode 100755 index 00000000..3cbad2f4 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/include/erpc/erpc_version.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2025 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _ERPC_VERSION_H_ +#define _ERPC_VERSION_H_ + +/*! + * @addtogroup infra + * @{ + */ + +//////////////////////////////////////////////////////////////////////////////// +// Definitions +//////////////////////////////////////////////////////////////////////////////// + +//! @brief String version of eRPC. +#define ERPC_VERSION "1.14.0" +//! @brief Integer version of eRPC. +#define ERPC_VERSION_NUMBER 11400 + +/*! @} */ + +#endif /* _ERPC_VERSION_H_ */ diff --git a/dependency/x86/third_party/erpc/v1.14.0/lib/liberpc.a b/dependency/x86/third_party/erpc/v1.14.0/lib/liberpc.a new file mode 100755 index 00000000..be5861a9 Binary files /dev/null and b/dependency/x86/third_party/erpc/v1.14.0/lib/liberpc.a differ diff --git a/dependency/x86/third_party/erpc/v1.14.0/share/erpc/BUILD.txt b/dependency/x86/third_party/erpc/v1.14.0/share/erpc/BUILD.txt new file mode 100644 index 00000000..682125d9 --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/share/erpc/BUILD.txt @@ -0,0 +1,6 @@ +Official eRPC 1.14.0 SDK for Linux x86_64. +Built from the upstream 1.14.0 tag with GCC on this server. +Release static library, PIC enabled; Linux pthread and serial transports. +Headers and runtime library come from erpc_c; erpcgen is a host build tool. +Link applications using -I/include/erpc -L/lib -lerpc -pthread. +The cmvr_es head implementation, request.txt and project CMake were not changed. diff --git a/dependency/x86/third_party/erpc/v1.14.0/share/erpc/build-info.json b/dependency/x86/third_party/erpc/v1.14.0/share/erpc/build-info.json new file mode 100644 index 00000000..65a7170b --- /dev/null +++ b/dependency/x86/third_party/erpc/v1.14.0/share/erpc/build-info.json @@ -0,0 +1,35 @@ +{ + "project": "EmbeddedRPC/erpc", + "tag": "1.14.0", + "source_url": "https://github.com/EmbeddedRPC/erpc/tree/1.14.0", + "source_archive_sha256": "119db152e961f1b3bec9dae8ce719517181b7ef58f18d976649cd9e627952a21", + "architecture": "x86_64-linux-gnu", + "compiler": "g++ (Ubuntu 11.4.0-1ubuntu1~22.04.3) 11.4.0", + "build_type": "Release", + "position_independent_code": true, + "threading": "POSIX pthreads (Linux autodetection)", + "generator_version": "erpcgen 1.14.0\nCopyright 2016-2021 NXP. All rights reserved.", + "build_session": "/tmp/cmvr-erpc-sdk-1.14.0-19_qlrpl", + "build_command": [ + "make", + "erpc", + "erpcgen", + "MAKETHREADS=4", + "build=release", + "FLEX=/tmp/cmvr-erpc-sdk-1.14.0-19_qlrpl/build-tools/usr/bin/flex", + "BISON=/tmp/cmvr-erpc-sdk-1.14.0-19_qlrpl/build-tools/usr/bin/bison" + ], + "extra_environment": { + "CXXFLAGS": "-fPIC", + "CFLAGS": "-fPIC" + }, + "tests": { + "generator_version": true, + "whole_archive_shared_link": true, + "installed_codec_crc_and_pthread_smoke": true, + "original_head_idl_generation": true, + "generated_sources_compiled": 5, + "generated_head_client_shared_link": true + }, + "original_head_idl_sha256": "b61e0c1d12f5619942c5ce14bfc0650ea03fe6b8756264196e2fd3d2a2892a94" +} \ No newline at end of file diff --git a/protos/cmvr/api/biohead_service.proto b/protos/cmvr/api/biohead_service.proto index f2dda323..bac6e667 100644 --- a/protos/cmvr/api/biohead_service.proto +++ b/protos/cmvr/api/biohead_service.proto @@ -2,9 +2,29 @@ syntax = "proto3"; package cmvr.api; import "cmvr/api/biohead_command.proto"; +import "cmvr/api/head_joint_command.proto"; // 生物头部机器人服务接口 service BioHeadService { + + // USB 头部关节控制。 + rpc ControlHeadJoints(HeadJointCommand.Request) + returns (HeadJointCommand.Feedback); + + // 查询 USB 头部的配置、连接和命令目标缓存。 + rpc GetHeadJointState(GetHeadJointStateCommand.Request) + returns (GetHeadJointStateCommand.Feedback); + + + + // Complete five-joint expression transition, with per-frame cancellation. + rpc SetHeadExpression(SetHeadExpressionCommand.Request) + returns (SetHeadExpressionCommand.Feedback); + + // Play one configured preset by exact ID or exact name. + rpc PlayHeadExpression(PlayHeadExpressionCommand.Request) + returns (PlayHeadExpressionCommand.Feedback); + // 设置面部表情 rpc SetExpression(SetFacialExpression.Request) returns (SetFacialExpression.Feedback){}; @@ -37,11 +57,4 @@ service BioHeadService { rpc ExpressionYawn(ExpressionYawn.Request) returns (ExpressionYawn.Feedback){}; - - - - - - - } \ No newline at end of file diff --git a/protos/cmvr/api/head_joint_command.proto b/protos/cmvr/api/head_joint_command.proto new file mode 100644 index 00000000..6e8d392e --- /dev/null +++ b/protos/cmvr/api/head_joint_command.proto @@ -0,0 +1,198 @@ +syntax = "proto3"; + +package cmvr.api; + +import "cmvr/api/common.proto"; + +// 头部关节运动模式。 +enum HeadJointMotionMode { + HEAD_JOINT_MOTION_IMMEDIATE = 0; + HEAD_JOINT_MOTION_S_CURVE = 1; + HEAD_JOINT_MOTION_FOLLOW = 2; +} + +// 最近一次设备命令的处理结果。 +enum HeadJointCommandOutcome { + HEAD_JOINT_COMMAND_NONE = 0; + HEAD_JOINT_COMMAND_ACKNOWLEDGED = 1; + HEAD_JOINT_COMMAND_REJECTED = 2; + HEAD_JOINT_COMMAND_UNKNOWN = 3; +} + +// 一个关节的目标位置。 +message HeadJointTarget { + string id = 1; + + // 单位:rad。 + // 区分“没有填写目标”和“明确要求移动到 0 rad”。 + oneof target { + double position_rad = 2; + } +} + +// 从设备配置中取得的关节信息。 +message HeadJointInfo { + string id = 1; + double min_position_rad = 2; + double max_position_rad = 3; + double home_position_rad = 4; +} + +// 最近一次获得固件 ACK 的目标缓存。 +// 这里保存的是命令目标,不是机械位置测量值。 +message HeadJointTargetState { + string id = 1; + double target_position_rad = 2; + bool target_valid = 3; +} + +// 头部关节控制命令。 +message HeadJointCommand { + // 单路或多路目标控制。 + message Move { + // 本次未列出的通道不参与目标下发。 + // 驱动会拒绝重复的通道 ID。 + repeated HeadJointTarget targets = 1; + } + + // 显式移动到配置中的 home 位置。 + message Home {} + + // Reopen and probe service 1 without sending any position target. + message Reconnect {} + + // Cancel later host-side expression frames; this is not a hardware stop. + message CancelExpression {} + + // 设置设备运动模式。 + message Mode { + // 区分未填写和明确选择 IMMEDIATE。 + oneof value { + HeadJointMotionMode mode = 1; + } + } + + // 设置指定关节的运动约束。 + message Constraints { + string id = 1; + double max_velocity_rad_s = 2; + double max_acceleration_rad_s2 = 3; + double max_jerk_rad_s3 = 4; + } + + // 设置指定关节的位置增益。 + message PositionGain { + string id = 1; + + // 0 是合法增益,需要与未填写区分。 + oneof value { + double gain = 2; + } + } + + // 设置设备更新周期,单位:ms。 + message UpdatePeriod { + uint32 period_ms = 1; + } + + message Request { + CommandHeader.Request header = 1; + + // 一条请求明确执行一项操作。 + oneof operation { + Move move = 2; + Home home = 3; + Mode mode = 4; + Constraints constraints = 5; + PositionGain position_gain = 6; + UpdatePeriod update_period = 7; + Reconnect reconnect = 8; + CancelExpression cancel_expression = 9; + } + } + + message Feedback { + // Move/configuration: success means firmware ACK, not mechanical arrival. + // Reconnect: success means open + service-1 probe, without automatic motion. + // CancelExpression: success means cancellation was requested for later host + // frames, not that firmware trajectory/PWM or the mechanism was stopped. + // A timed-out write may already have taken effect; do not blindly retry. + CommandHeader.Feedback header = 1; + } +} + +// 查询头部驱动的配置和缓存状态。 +message GetHeadJointStateCommand { + message Request { + CommandHeader.Request header = 1; + } + + message Feedback { + // success=true 表示成功取得驱动状态。 + // 设备连接和命令结果仍需检查下面的对应字段。 + CommandHeader.Feedback header = 1; + + // 表示串口传输连接状态,不是持续的硬件健康检测。 + bool connected = 2; + + // 配置中的关节信息,不是从控制板读取的标定。 + repeated HeadJointInfo joint_info = 3; + + // 最近一次获得 ACK 的目标及其有效性。 + repeated HeadJointTargetState targets = 4; + + HeadJointCommandOutcome last_command_outcome = 5; + string last_error = 6; + + // 当前 eRPC 服务 1 不提供真实关节位置测量反馈。 + bool position_feedback_available = 7; + + // Presets come from configuration, not measured hardware poses. + repeated HeadExpressionInfo expressions = 8; + bool expression_baseline_ready = 9; + bool hardware_emergency_stop_available = 10; + } +} +// One configured expression, with a stable ID and an exact display name. +message HeadExpressionInfo { + string expression_id = 1; + string expression_name = 2; + repeated HeadJointTarget targets = 3; +} + +// Synchronously send a complete five-joint expression through a bounded host +// transition. Omitted joints and partial expressions are rejected. +message SetHeadExpressionCommand { + message Request { + CommandHeader.Request header = 1; + repeated HeadJointTarget targets = 2; + // Finite duration in [0.2, 5.0] seconds; 0 or omission is rejected. + double transition_duration_s = 3; + } + message Feedback { + // Every transmitted frame, including the final target, was acknowledged. + // This is not proof of mechanical arrival; late intermediate frames may be skipped. + CommandHeader.Feedback header = 1; + } +} + +// Select one configured expression by exact stable ID or exact name. +// Unknown selectors and ambiguous names are rejected without fallback. +message PlayHeadExpressionCommand { + message Request { + CommandHeader.Request header = 1; + oneof expression { + string expression_id = 2; + string expression_name = 3; + } + // Finite duration in [0.2, 5.0] seconds; 0 or omission is rejected. + double transition_duration_s = 4; + } + message Feedback { + // Every transmitted frame, including the final target, was acknowledged. + // This is not proof of mechanical arrival; late intermediate frames may be skipped. + CommandHeader.Feedback header = 1; + string expression_id = 2; + string expression_name = 3; + } +} diff --git a/protos/cmvr/config/biohead_config/biohead_config.proto b/protos/cmvr/config/biohead_config/biohead_config.proto index 543a96e7..65605da1 100644 --- a/protos/cmvr/config/biohead_config/biohead_config.proto +++ b/protos/cmvr/config/biohead_config/biohead_config.proto @@ -1,6 +1,8 @@ syntax = "proto3"; + package cmvr.config; +// 原 ESP32 头部的舵机分组配置。 message BioHeadServoGroupConfig { string name = 1; int32 address = 2; @@ -11,13 +13,47 @@ message BioHeadServoGroupConfig { repeated double max_angles = 7; } +// USB eRPC 服务 1 的单个舵机关节配置。 +// 所有位置参数的单位均为弧度 rad。 +message UsbHeadJointConfig { + // 与控制板固件中的舵机 ID 对应。 + string id = 1; + + // 允许下发的最小位置。 + double min_position_rad = 2; + + // 允许下发的最大位置。 + double max_position_rad = 3; + + // 显式调用 home 时使用的目标位置。 + double home_position_rad = 4; +} + +// USB eRPC 服务 1 的设备配置。 +message UsbHeadErpcConfig { + // 应答超时,单位 ms。 + // 后续驱动中:0 表示使用默认 2000 ms,最大允许 30000 ms。 + uint32 response_timeout_ms = 1; + + // 该设备允许控制的关节及其标定参数。 + repeated UsbHeadJointConfig joints = 2; +} + +// 头部设备配置。 message BioHeadRobotConfig { string id = 1; string serial_port = 2; int32 baud_rate = 3; + + // 原 ESP32 后端使用的配置,保留原字段编号。 repeated BioHeadServoGroupConfig servo_groups = 4; -} -message BioHeadRobotRootConfig { - BioHeadRobotConfig bio_head = 1; + + // 配置此字段时,选择新增的 USB eRPC 后端。 + // 未配置时,继续使用原 ESP32 后端。 + UsbHeadErpcConfig usb_erpc = 5; } +// 配置文件的根结构。 +message BioHeadRobotRootConfig { + BioHeadRobotConfig bio_head = 1; +} \ No newline at end of file diff --git a/request.txt b/request.txt index 0cb96b57..1e6bf4ba 100644 --- a/request.txt +++ b/request.txt @@ -39,5 +39,6 @@ third_party/matplotplusplus/1.2.0 third_party/ethercat/v1.7.0 third_party/huayan_robot/v1.0 third_party/aubo_sdk/v0.27.1 +third_party/erpc/v1.14.0