diff --git a/README.en.md b/README.en.md index c6891b6c..1bb98fa5 100644 --- a/README.en.md +++ b/README.en.md @@ -26,6 +26,8 @@ and collecting telemetry in the background. CAN/CAN FD communication is provided L6 defaults to Classic CAN. Devices with compatible CAN FD firmware can explicitly select the [optional HOP protocol](docs/en/guides/usage.md#optional-l6-can-fd-protocol). +O6 firmware that supports HOP 0.0.4 can use CAN FD or Classic CAN with explicit protocol selection. +See [O6 HOP connection and CAN mode switching](docs/en/tutorials/o6.md#o6-hop). See [platform and hardware validation scope](docs/en/reference/compatibility.md#platform-and-hardware-validation-scope) for tested platforms, adapters, and limitations. diff --git a/README.md b/README.md index c6891b6c..1bb98fa5 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,8 @@ and collecting telemetry in the background. CAN/CAN FD communication is provided L6 defaults to Classic CAN. Devices with compatible CAN FD firmware can explicitly select the [optional HOP protocol](docs/en/guides/usage.md#optional-l6-can-fd-protocol). +O6 firmware that supports HOP 0.0.4 can use CAN FD or Classic CAN with explicit protocol selection. +See [O6 HOP connection and CAN mode switching](docs/en/tutorials/o6.md#o6-hop). See [platform and hardware validation scope](docs/en/reference/compatibility.md#platform-and-hardware-validation-scope) for tested platforms, adapters, and limitations. diff --git a/README.zh-CN.md b/README.zh-CN.md index 06404c9a..85fdf11f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -24,6 +24,7 @@ | O30 | 20 | HOP / CAN FD 标准帧,无 BRS | 请求 ID 默认 `0x001` | L6 默认使用 Classic CAN;支持 CAN FD 的设备可显式选择[可选 HOP 协议](docs/zh/guides/usage.md#l6-可选-can-fd-协议)。 +O6 固件支持 HOP 0.0.4 时,可显式选择 CAN FD 或 Classic CAN。详见 [O6 HOP 接入与 CAN 模式切换](docs/zh/tutorials/o6.md#o6-hop)。 平台、适配器和实测限制统一见 [平台与硬件验证范围](docs/zh/reference/compatibility.md#平台与硬件验证范围)。 diff --git a/docs/en/connections/manual.md b/docs/en/connections/manual.md index 56082153..bee9601d 100644 --- a/docs/en/connections/manual.md +++ b/docs/en/connections/manual.md @@ -154,6 +154,10 @@ For optional L6 HOP firmware, explicitly set `config.l6_protocol = L6Protocol::k and verify the corresponding address, bitrate, and capabilities. You cannot infer the device protocol from the FD interface configuration. See [Optional HOP connection](../guides/usage.md#optional-l6-can-fd-protocol). +Connect to O6 HOP firmware manually. Set `config.o6_protocol = O6Protocol::kHopV004` for a device currently using CAN FD, +or select `O6Protocol::kHopV004Can` for CAN 2.0 and configure SocketCAN to match the device. The default request ID is `0x001`. +See the connection example and device-side mode switch in [Manual O6 HOP connection](../tutorials/o6.md#o6-hop). + ## PCAN and SLCAN (Windows) diff --git a/docs/en/reference/compatibility.md b/docs/en/reference/compatibility.md index 23fa8c3e..cf2cce7a 100644 --- a/docs/en/reference/compatibility.md +++ b/docs/en/reference/compatibility.md @@ -26,6 +26,12 @@ close/recovery and injected abnormal-reply timing acceptance is claimed. Offline regressions cover these lifecycle and isolation rules independently. The scheduling runs do not establish frequency maxima or dynamic motion accuracy. +## O6 HOP hardware validation + +On 2026-11-25, a Release build from the local C++ SDK source was tested on a right O6 (firmware `5.0.1`, HOP `0.0.4`) on Ubuntu 24.04 x86_64. +candleLightFD / SocketCAN passed common CAN FD operations and single-joint movement with restoration. MiniCANFD verified the C++ FD-to-CAN 2.0 switch and used the vendor API to verify Classic frame I/O and return to FD. +See adapter versions and coverage in the [O6 HOP hardware record](../../hardware-acceptance/o6/report.md#o6-hop-2026-11-25). + ## Historical common-feature hardware baseline Historical hardware acceptance applies to the SDK revision and configuration recorded diff --git a/docs/en/reference/model-capabilities.md b/docs/en/reference/model-capabilities.md index dec9d5e3..0530a1ee 100644 --- a/docs/en/reference/model-capabilities.md +++ b/docs/en/reference/model-capabilities.md @@ -1,6 +1,6 @@ # Model Capabilities -This reference covers control, telemetry, configuration, and model-specific features in C++ SDK `0.3.4`. +This reference covers control, telemetry, configuration, and model-specific features in the C++ SDK. Compare models in the [Capabilities overview](#capabilities-overview), then read the corresponding section: [L6](#l6), [O6](#o6), [L20 Lite](#l20-lite), [L20](#l20), [L30](#l30), [O30](#o30). @@ -19,6 +19,7 @@ for operating systems, adapters, and hardware validation, see [Platform and hard hardware-tested scope is listed separately in [Validation records](#validation-records), not inferred from API existence. - `—` means unsupported by the current unified API. L6 in all overview tables means **default Classic CAN**; CAN FD is an [Explicitly selected optional protocol](#optional-l6-can-fd-protocol), without all Classic features. +- O6 in the overview tables uses the original Classic CAN protocol. See [O6 HOP 0.0.4](#o6-hop-capabilities) for HOP capabilities in the current source. ## Capabilities overview @@ -132,6 +133,8 @@ For complete connection examples, ACK semantics, and pending hardware checks, se ## O6 +### Default Classic CAN + 6 joints, with the same order as L6; Classic CAN, default left `0x28`, right `0x27`. The native model entry point is `o6::O6`. @@ -160,6 +163,21 @@ Limitations and usage notes: - Unified measured speed, torque, gains, limit compensation, voltage, fault clearing, and enable/disable are unsupported. - Speed, current limits, and measured current have no reliably established uniform physical conversion; retain raw values and unit confidence. + + +### O6 HOP 0.0.4 + +The model-specific entry point is `o6::HopO6`. For the unified API, explicitly select a HOP protocol in `HandDevice`. + +| Feature | HOP semantics | +| --- | --- | +| Angles and motion parameters | Device reads and writes for angles, configured speeds, accelerations, current limits, and the three stall protection settings. Per-joint raw range is `0..255` | +| Live telemetry | Reads angles, current, temperature, faults, and tactile data for five fingers using the sensor descriptors for fields and shapes | +| CAN configuration | `get_can_configuration()` reads the mode, request ID, BRS, and bitrates. `set_can_interface_mode()` writes the mode field | + +Use raw counts for numeric data. Physical conversions for speed, acceleration, and current remain unverified. +See the [O6 HOP guide](../tutorials/o6.md#o6-hop) for connection setup, mode switching, and adapter limitations. + ## L20 Lite 10 joints, Classic CAN, default left `0x28`, right `0x27`; native entry point `l20lite::L20lite`. @@ -363,7 +381,8 @@ original per-model reports are in the source repository at `docs/hardware-accept | --- | --- | --- | | L6 Classic | `V2.4.5` | Common reads, angles, speed/current limits, and recovery have hardware records; advanced gains, torque output, and persistence are outside this acceptance scope | | L6 HOP CAN FD (optional) | No hardware acceptance record yet | Offline protocol vectors and FakeTransport do not establish device integration or motion passes | -| O6 | `V1.3.2` | Common APIs and recovery have hardware records; native speed-query configuration changes remain a limitation | +| O6 Classic | `V1.3.2` | Hardware records cover common APIs and recovery. The native speed query can change the configured speed | +| O6 HOP 0.0.4 | `5.0.1` | Common CAN FD APIs and single-joint movement with restoration passed on a right hand. See the [O6 HOP hardware record](../../hardware-acceptance/o6/report.md#o6-hop-2026-11-25) for FD-to-CAN 2.0 switching and Classic frame coverage | | L20 Lite | `V4.6.10` | Common APIs, caches, and recovery have hardware records; scalar tactile fields unsupported; joint 7/8 motion issues retained | | L20 | `V3.0.6` | Common APIs and recovery have hardware records; speed/current-limit writes verify sending only, without configuration readback; intermittent faults retained | | L30 | `V6.1.6` | Common APIs, enable/disable, and recovery have hardware records; one historical skip cannot count as a hardware pass | diff --git a/docs/en/tutorials/o6.md b/docs/en/tutorials/o6.md index 69abf4d3..9dc6f128 100644 --- a/docs/en/tutorials/o6.md +++ b/docs/en/tutorials/o6.md @@ -1,11 +1,13 @@ # O6 Feature Guide -O6 uses Classic CAN and has 6 joints. +O6 has 6 joints. The SDK defaults to the original O6 Classic CAN protocol. Select HOP explicitly on firmware that supports HOP 0.0.4. This page uses C++ `HandDevice` for common operations. The examples follow the current C++ SDK API. ## Contents - [Usage](#usage) +- [Manual HOP 0.0.4 connection](#o6-hop) +- [Switching HOP CAN modes](#hop-can-mode) - [Joint order](#joint-order) - [Device identity](#identity) - [Capabilities](#capabilities) @@ -18,7 +20,7 @@ This page uses C++ `HandDevice` for common operations. The examples follow the c ## Usage -First configure your environment using [Prepare the communication interface](../connections/prepare-interface.md), then choose [Automatic connection](../connections/automatic.md) +For firmware using the original O6 Classic CAN protocol, configure your environment using [Prepare the communication interface](../connections/prepare-interface.md), then choose [Automatic connection](../connections/automatic.md) or [Manual connection](../connections/manual.md). The complete read-only Linux SocketCAN program below provides the `hand` object, chrono literals, and printing/waiting helpers used by the snippets later on this page. For Windows, replace the device construction code with a verified adapter factory; the feature snippets remain the same. @@ -144,6 +146,93 @@ Your application must separately verify mechanical positioning and control effec Check `meta.valid` first, then use `meta.stale` to determine whether a sample has expired; a cached reading is not a live measurement. If closing fails, a long-running application should retain the same object and schedule cleanup retries rather than immediately opening another connection. + + +## Manual HOP 0.0.4 connection + +HOP defines device registers and messages. CAN 2.0 and CAN FD carry those messages. Set `HandDeviceConfig::o6_protocol` to match the device's **current** protocol and frame format. +This setting selects how the SDK communicates. To change the device's frame format, use the [HOP mode-switching API](#hop-can-mode). + +| Setting | Frame format | Addresses | +| --- | --- | --- | +| `O6Protocol::kClassic` (default) | Original O6 Classic CAN | Left `0x28`, right `0x27` | +| `O6Protocol::kHopV004` | HOP 0.0.4, standard CAN FD frames with BRS off on SDK transmissions | Default request ID `0x001`; response ID is the request ID OR `0x400` | +| `O6Protocol::kHopV004Can` | HOP 0.0.4, standard CAN 2.0 frames | Same ID rules as HOP CAN FD | + +Connect to HOP devices manually. Specify the actual hand side, request ID, and adapter channel. `open()` reads the device identity and checks the hand side. +Check the CAN_H and CAN_L wiring and bus termination. The tested right hand used `0x001/0x401`, a 1 Mbit/s nominal bitrate, a 5 Mbit/s data bitrate, and BRS off. +For a Linux SocketCAN device with these settings, configure `can0` as follows. + +```bash +sudo ip link set can0 down +sudo ip link set can0 up type can bitrate 1000000 dbitrate 5000000 fd on +ip -details link show can0 +``` + +This program reads CAN configuration and angles. For a device already using HOP CAN 2.0, select `kHopV004Can` and configure SocketCAN with the nominal bitrate and `fd off`. + +```cpp +#include +#include +#include + +int main() try { + using namespace linkerbot::hand; + HandDeviceConfig config; + config.model = Model::kO6; + config.side = HandSide::kRight; + config.interface_name = "can0"; + config.address = 0x001; + config.o6_protocol = O6Protocol::kHopV004; + + HandDevice hand(config); + hand.open(); + const auto can = hand.get_can_configuration(); + std::cout << "request_id=0x" << std::hex << can.request_id + << " response_id=0x" << can.response_id() << std::dec + << " mode=" << (can.interface_mode == HopCanInterfaceMode::kCanFd ? "canfd" : "can") + << " nominal=" << can.nominal_bitrate << " data=" << can.data_bitrate + << " brs=" << can.brs << '\n'; + const auto angles = hand.get_angles(); + for (const auto angle : angles.raw) { + std::cout << angle << ' '; + } + std::cout << '\n'; + hand.close(); + return angles.meta.valid ? 0 : 1; +} catch (const std::exception &error) { + std::cerr << error.what() << '\n'; + return 1; +} +``` + + + +## Switching HOP CAN modes + +`get_can_configuration()` reads the device's request ID, interface mode, BRS, nominal bitrate, and data bitrate. +Pass `HopCanInterfaceMode::kCan20` or `HopCanInterfaceMode::kCanFd` to `set_can_interface_mode()` to set the device's HOP frame format. +These modes correspond to values `1` and `2` in MI `0x35` / SI `0x06`. Disable device-side BRS before selecting CAN 2.0. +Connect in the device's current mode before switching. Each call sends at most one mode write. Configure the host interface separately. + +The Linux SocketCAN example `hop_can_mode` reads identity and CAN configuration by default. + +```bash +cmake -S . -B build -DLINKERBOT_BUILD_EXAMPLES=ON +cmake --build build --target hop_can_mode +./build/examples/hop_can_mode can0 o6 right --request-id 0x001 +``` + +- `--from-mode canfd|can` selects the connection's frame format and defaults to `canfd`. `can` applies only to O6 HOP. +- `--mode can|canfd` writes the target mode to volatile configuration by default. Add `--save` to send one Flash save command. Power-cycle persistence remains untested. +- Check the actual reply format using the API result's `active_wire_is_fd`. CLI exit code `2` means the register was verified and replies still use the previous format. Recheck after a controlled restart. Once the new format is active, close the original connection, configure the host interface and adapter for the new mode, and open a new connection with the corresponding `o6_protocol`. +- Switching from CAN 2.0 to CAN FD requires a transport that can receive an immediate FD reply. A Classic SocketCAN connection cannot receive it. + The current SDK leaves the Classic frame format implicit on HOP CAN 2.0 requests. FD-enabled SocketCAN and MiniCANFD channels can send those requests as FD frames. + After a timeout, check the device using the target format before attempting another mode write. + +The candleLightFD run verified common C++ `HandDevice` operations over HOP CAN FD. The MiniCANFD run verified the C++ FD-to-CAN 2.0 switch and used the vendor API for Classic frame reads and writes and the return to FD. +See the [O6 HOP hardware record](../../hardware-acceptance/o6/report.md#o6-hop-2026-11-25). + ## Joint order The SDK reads and sets joint data in the following order. @@ -253,9 +342,8 @@ wait_command(hand.set_speeds(std::vector(6, 100.0))); ### Reading configured speeds -Configured-speed reads use the cache of complete speed-write responses from the current connection; they do not send a new speed query. -Set the speed first, then read it in the same connection. The measured-speed API `get_speeds()` is not supported. -On O6 V1.3.2 firmware, do not actively query speeds through the native `speed.get_blocking()` method; this request may set the speed to 0. +HOP reads the device register through `get_configured_speeds()`. The original Classic protocol uses the complete speed-write response cached in the current connection, so set the speed first in that connection. +On Classic V1.3.2 firmware, a native `speed.get_blocking()` query may set the device speed to 0. ```cpp print_sample(hand.get_configured_speeds(1s)); @@ -267,13 +355,13 @@ print_sample(hand.get_configured_speeds(1s)); ### Setting accelerations -`set_accelerations()` takes 6 raw counts in the range `0..254`; do not interpret them directly as physical acceleration. +`set_accelerations()` takes 6 raw counts. The original Classic protocol accepts `0..254`. HOP accepts `0..255`. ```cpp wait_command(hand.set_accelerations(std::vector(6, 100.0))); ``` -For O6, `0` is a special protocol encoding for maximum acceleration, not zero acceleration. +The original Classic protocol uses `0` to encode special maximum acceleration. The physical conversion for HOP acceleration remains unverified. ### Reading configured accelerations @@ -297,7 +385,7 @@ print_sample(hand.get_currents(1s)); ### Reading temperatures -The capabilities for this model declare degrees Celsius as the temperature unit; you must still check sample validity. +The original Classic protocol declares temperatures in degrees Celsius. HOP capabilities report raw counts. Check the sample validity with either protocol. ```cpp print_sample(hand.get_temperatures(1s)); @@ -305,8 +393,8 @@ print_sample(hand.get_temperatures(1s)); ### Reading tactile matrices -In C++, select fields with `get_force(vector{"fn"}, timeout)` and access them through `field("fn")`, -rather than Python's `force.fn.raw`. Each optional vector in `raw` corresponds to one finger; `nullopt` means missing data, +Select fields with `get_force(vector{"fn"}, timeout)` and access them through `field("fn")`. +Each optional vector in `raw` corresponds to one finger. `nullopt` means missing data, and `false` in `valid_values` means an invalid value. The `print_field()` helper above displays this information without filling in zeros or computing sums. ```cpp @@ -314,7 +402,7 @@ const auto force = hand.get_force(std::vector{"fn"}, 1s); print_field(force, "fn"); ``` -The default matrix layout is 5 fingers with 10×4 points per finger. The returned fields and `force.tactile` retain the actual data; use the current capabilities and firmware as the reference. +The original Classic protocol defaults to 5 fingers with 10×4 points per finger. HOP reads fields and shapes from each finger's sensor descriptor. For more features, firmware limitations, and physical units, see [Model capabilities](../reference/model-capabilities.md). diff --git a/docs/hardware-acceptance/README.en.md b/docs/hardware-acceptance/README.en.md index fcc6bc7d..1fc13813 100644 --- a/docs/hardware-acceptance/README.en.md +++ b/docs/hardware-acceptance/README.en.md @@ -12,7 +12,7 @@ retains its revisions, firmware, commands, failures and follow-up results. | Model | Recorded coverage and remaining limits | | --- | --- | | [L6](l6/report.md) | 34 common Linux checks passed; Windows Debug PCAN and SLCAN Classic discovery, reads and single-joint movement/restoration recorded | -| [O6](o6/report.md) | 33 common Linux checks eventually passed; Windows Debug PCAN and SLCAN Classic discovery, reads and single-joint movement/restoration recorded | +| [O6](o6/report.md) | Classic CAN records cover Linux and Windows. The [HOP 0.0.4 run](o6/report.md#o6-hop-2026-11-25) passed 10 CAN FD checks, including single-joint movement and restoration, and recorded the FD-to-CAN 2.0 switch | | [L20 Lite](l20lite/report.md) | Linux joint arrival/coupling differences retained; Windows Debug PCAN and SLCAN Classic checks include joint 0 movement/restoration | | [L20](l20/report.md) | 32 common checks passed; Windows Debug PCAN/SLCAN Classic recorded, with earlier fault and snapshot-expiry observations retained | | [L30](l30/report.md) | 34 Linux checks passed with additional skipped cases; Windows Debug SLCAN FD recorded; previous pose-range and CLI failures remain documented | diff --git a/docs/hardware-acceptance/README.md b/docs/hardware-acceptance/README.md index 36ed8fb0..f978b7f7 100644 --- a/docs/hardware-acceptance/README.md +++ b/docs/hardware-acceptance/README.md @@ -24,7 +24,7 @@ MiniCANFD 需使用该场次验证的配套 DLL,旧版 DLL 的发送失败记 | 型号 | 报告 / 状态 | | --- | --- | | L6 | [Linux 常用功能 34 项通过;Windows PCAN / SLCAN Classic 读取及单关节收发恢复通过](l6/report.md) | -| O6 | [Linux 常用接口 33 项最终通过;Windows PCAN / SLCAN Classic 发现、读取及单关节收发恢复通过](o6/report.md) | +| O6 | [Classic 的 Linux 和 Windows 验收](o6/report.md)。[HOP 0.0.4 实测](o6/report.md#o6-hop-2026-11-25)覆盖 CAN FD 常用接口 10 项、单关节运动恢复及 FD→CAN 2.0 切换 | | L20Lite | [Linux 角度到位/联动差异保留;Windows PCAN / SLCAN Classic 发现、读取及关节 0 运动恢复通过](l20lite/report.md) | | L20 | [常用接口 32 项通过;Windows PCAN / SLCAN Classic 发现、读取及单关节收发恢复通过,历史设备故障及复测记录见报告](l20/report.md) | | L30 | [Linux 34 项通过、另有跳过项;Windows SLCAN FD 发现、读取及单关节运动恢复通过](l30/report.md) | diff --git a/docs/hardware-acceptance/o6/report.md b/docs/hardware-acceptance/o6/report.md index 4440bb38..e10fdedd 100644 --- a/docs/hardware-acceptance/o6/report.md +++ b/docs/hardware-acceptance/o6/report.md @@ -1,11 +1,13 @@ # O6 实机验收报告 -结论:**O6 已完成 SDK 常用接口实机验证,33 个常用用例最终通过**(分组执行,包含 raw 角度复测)。高级调参、恢复出厂和 EEPROM 保存不纳入本次验收。 +历史 Classic CAN 场次 **33 个常用用例最终通过**(分组执行,包含 raw 角度复测)。高级调参、恢复出厂和 EEPROM 保存不纳入本次验收。 2026-10-19 已追加 Windows / SLCAN Classic / Debug 实测:枚举、发现、发现连接、显式连接、六关节读取、关闭重连及单关节运动恢复通过,**6 个用例、416 条断言通过,无失败或跳过**,详见文末。 同日 Windows / PCAN Classic / Debug 也已完成上述接入与单关节运动恢复检查,另有 **6 个用例、416 条断言通过,无失败或跳过**。两种适配器路径分别保留实测记录。 +2026-11-25 已追加 [O6 HOP 0.0.4 右手实测](#o6-hop-2026-11-25),覆盖 CAN FD 常用接口、单关节运动恢复及切到 CAN 2.0 后的经典帧收发。 + ## 环境 - 日期:2026-10-14,UTC+08:00。 @@ -176,3 +178,48 @@ $Cli=@('--backend','pcan','--channel','PCAN_USBBUS1','--mode','classic', `acceptance/o6-pcan-20261019-143704`,含双仓 SHA/状态/差异、 二进制及 DLL 哈希、适配器/驱动/系统、CLI 与用例日志、JUnit、环境变量/退出码、映射配置和 `results.json`。 USB 拔插、PCAN FD、Release、其他手型/固件及长期负载未在本场测试。 + + + +## O6 HOP 0.0.4 实测(2026-11-25,UTC+08:00) + +### 环境 + +- O6 右手,产品码 `LHO6-04.2-0356-R-B-3-D`,固件 `5.0.1`,HOP `0.0.4`,6 关节。 +- HOP 标准帧,请求与响应 ID 为 `0x001/0x401`,标称速率 1 Mbit/s,数据速率 5 Mbit/s,BRS 关闭。 +- Ubuntu 24.04.3 x86_64,Linux `7.0.0-43-generic`,GCC 13,Release。C++ SDK 以 `3b30d54ef4452345fcd2e7614f7273452cbe1112` 为基线,包含本地 HOP 与模式切换改动。Transport 源码为 `0e190032d65ed0b315337b45b3779cf4f650ed68`。 +- CAN FD 常用接口测试使用 candleLightFD(USB `1d50:606f`,`gs_usb`,`can0`)。现场调正 CAN_H 与 CAN_L 接线后,抓包收到请求 `0x001` 对应的设备回复 `0x401`。 +- 模式切换测试使用 HCANFD Mini-I(USB `a8fa:8598`,硬件 `V1.12`,固件 `V1.5.106`),通道 `minicanfd:0:0`。测试机的厂商 `libcanbus.so` 通过 `LD_PRELOAD=libusb-1.0.so.0` 加载所需依赖。 + +### candleLightFD / SocketCAN / C++ HandDevice + +在 `can0` 上按实测速率启用 CAN FD,以 `O6Protocol::kHopV004`、右手和请求 ID `0x001` 打开设备。台架探针的 **10 项检查通过**。 + +| 检查项 | 实机结果 | +| --- | --- | +| 身份及健康 | 核对 O6 右手、HOP 版本、6 关节和已验证连接状态 | +| CAN 配置 | 核对 CAN FD、请求 ID、BRS 及两段速率 | +| 角度读取 | 6 个关节样本有效 | +| 速度与加速度配置 | 读取配置速度,按原值写回加速度并读回确认 | +| 电流、限流、温度和故障 | 读取各关节数据,关节故障为 0 | +| 堵转保护 | 读取堵转时间、阈值和保持电流 | +| 五指触觉 | 5 个传感器在线,返回 2 个字段 | +| 快照、轮询及事件 | 快照更新,收到 13 个角度事件和 6 个电流事件,丢事件为 0 | +| 单关节运动及恢复 | 临时使用小指速度原始值 `48`,实测小指角度 `255 → 243 → 255` | +| 连接恢复 | `recover()` 后核对同一设备身份,重新读取六关节角度和故障 | + +结束时姿态回到起始原始值 `(255, 217, 255, 255, 255, 255)`,原速度和目标寄存器恢复并读回确认。SocketCAN 的收发错误和丢包计数为 0。 + +### MiniCANFD / HOP CAN FD → CAN 2.0 → CAN FD + +| 阶段 | 实机结果 | +| --- | --- | +| C++ API 从 FD 切到 CAN 2.0 | 从 HOP FD 打开 `HandDevice`,调用 `set_can_interface_mode(HopCanInterfaceMode::kCan20, false)`。收到新的 CAN 2.0 寄存器值,回复立即变为 Classic 帧 | +| CAN 2.0 读写 | 厂商原生接口显式收发 Classic 帧,读到 O6 型号、右手、HOP 版本、请求 ID 和六关节角度。按原值写回六关节角度目标,收到 ACK,随后读回目标值一致 | +| CAN 2.0 恢复 FD | 厂商原生接口发送一次易失模式写入。读回原 CAN FD 设置,角度与起始姿态一致,故障码为 0 | + +CAN 2.0 段验证的是寄存器读写。该段目标按原值写回,运动验证来自上面的 CAN FD 单关节测试。 +当前 C++ SDK 在 HOP CAN 2.0 请求中省略了显式 Classic 帧标记。离线帧解析确认,处于 FD 模式的 SocketCAN 和 MiniCANFD 会按各自的 FD 默认行为发送这类请求。 +MiniCANFD 上由 C++ `HandDevice` 直接收发 HOP CAN 2.0 的端到端验收仍待完成。Flash 保存、断电后保持及其他固件版本也待实测。 + +SocketCAN 接入与只读复查命令见 [O6 HOP 教程](../../zh/tutorials/o6.md#o6-hop)。本次常用接口与切换结果来自台架探针及抓包,使用工作区源码构建。 diff --git a/docs/zh/connections/manual.md b/docs/zh/connections/manual.md index c7e966ad..b93a1ee6 100644 --- a/docs/zh/connections/manual.md +++ b/docs/zh/connections/manual.md @@ -154,6 +154,10 @@ L6 可选 HOP 固件需显式设置 `config.l6_protocol = L6Protocol::kHopV004` 并核对对应地址、速率和能力;不能通过 FD 接口配置推断设备协议。 详见[可选 HOP 接入](../guides/usage.md#l6-可选-can-fd-协议)。 +O6 HOP 固件使用显式手动连接。设备当前使用 CAN FD 时选择 `config.o6_protocol = O6Protocol::kHopV004`, +使用 CAN 2.0 时选择 `O6Protocol::kHopV004Can`,并按实际设置配置 SocketCAN。请求 ID 默认 `0x001`。 +连接示例和设备端模式切换见 [O6 HOP 手动接入](../tutorials/o6.md#o6-hop)。 + ## PCAN 与 SLCAN(Windows) diff --git a/docs/zh/reference/compatibility.md b/docs/zh/reference/compatibility.md index 1fc526f6..078648e4 100644 --- a/docs/zh/reference/compatibility.md +++ b/docs/zh/reference/compatibility.md @@ -19,6 +19,12 @@ O6 左手、L20 右手和 O30 右手(显式 V25)已在 Ubuntu 24.04 x86_64 / 本次未新增 L6/L20Lite 调度实机验收,也未实机执行共享 Session、关闭恢复及异常回复时序测试; 生命周期和隔离规则另有离线回归覆盖。这些调度测试不证明频率上限或动态运动精度。 +## O6 HOP 实机验证 + +2026-11-25 在 Ubuntu 24.04 x86_64 / Release 下使用本地 C++ SDK 源码验证了 O6 右手(固件 `5.0.1`,HOP `0.0.4`)。 +candleLightFD / SocketCAN 通过 CAN FD 常用接口及单关节运动恢复。MiniCANFD 完成 C++ 发起的 FD→CAN 2.0 切换,切换后的经典帧收发及恢复 FD 由厂商原生接口验证。 +具体适配器版本及覆盖范围见 [O6 HOP 实机记录](../../hardware-acceptance/o6/report.md#o6-hop-2026-11-25)。 + ## 历史常用功能实机基线 历史实机验收仅对应各报告记录的 SDK 版本和配置,不自动覆盖后续版本的改动。 diff --git a/docs/zh/reference/model-capabilities.md b/docs/zh/reference/model-capabilities.md index beca2c15..a7d0543f 100644 --- a/docs/zh/reference/model-capabilities.md +++ b/docs/zh/reference/model-capabilities.md @@ -1,6 +1,6 @@ # 各型号能力说明 -本文面向 C++ SDK `0.3.4`,按手型说明控制、遥测、配置和专有功能。 +本文按手型说明 C++ SDK 的控制、遥测、配置和专有功能。 先用[能力总览](#能力总览)对照型号,再查看对应章节: [L6](#l6)、[O6](#o6)、[L20 Lite](#l20-lite)、[L20](#l20)、[L30](#l30)、[O30](#o30)。 @@ -19,6 +19,7 @@ 实机通过范围单独列在[验证记录](#验证记录),不由接口存在推导。 - `—` 表示当前统一接口不支持。所有总览表中的 L6 均指**默认 Classic CAN**; CAN FD 是[显式选择的可选协议](#l6-可选-can-fd-协议),不能套用 Classic 的全部功能。 +- 总览表中的 O6 使用原有 Classic CAN 协议。当前源码的 HOP 能力见 [O6 HOP 0.0.4](#o6-hop-capabilities)。 ## 能力总览 @@ -132,6 +133,8 @@ Kp 写入为 `0..200`,两个 Kd 为 `0..255`;回复保留设备实际值, ## O6 +### 默认 Classic CAN + 6 关节,顺序与 L6 的六关节顺序一致;Classic CAN,默认左手 `0x28`、右手 `0x27`。 型号入口为 `o6::O6`。 @@ -160,6 +163,20 @@ Kp 写入为 `0..200`,两个 Kd 为 `0..255`;回复保留设备实际值, - 不支持统一实时速度、扭矩、增益、限位补偿、电压、清故障、使能 / 失能。 - 速度、限流和实时电流没有可靠统一的物理换算结论,保留原始值和单位置信度。 + + +### O6 HOP 0.0.4 + +型号入口为 `o6::HopO6`,统一入口为显式选择 HOP 的 `HandDevice`。 + +| 功能 | HOP 语义 | +| --- | --- | +| 角度及运动参数 | 角度、配置速度、加速度、电流上限和三项堵转保护参数支持写入及设备查询。各关节原始范围为 `0..255` | +| 实时遥测 | 支持角度、电流、温度、故障和五指触觉读取,触觉字段和形状按传感器描述获得 | +| CAN 配置 | `get_can_configuration()` 读取接口模式、请求 ID、BRS 和速率。 `set_can_interface_mode()` 写入模式字段 | + +数值按原始计数处理,速度、加速度和电流的物理换算尚未确认。接入配置、模式切换和适配器限制见 [O6 HOP 教程](../tutorials/o6.md#o6-hop)。 + ## L20 Lite 10 关节,Classic CAN,默认左手 `0x28`、右手 `0x27`;型号入口为 `l20lite::L20lite`。 @@ -364,7 +381,8 @@ int main() { | --- | --- | --- | | L6 Classic | `V2.4.5` | 常用读取、角度、速度 / 限流及恢复有实机记录;高级增益、扭矩输出和持久化不在本轮验收范围 | | L6 HOP CAN FD(可选) | 尚无实机验收记录 | 离线协议向量和 FakeTransport,不据此宣称设备接入或运动通过 | -| O6 | `V1.3.2` | 常用接口和恢复有实机记录;保留原生速度查询会改变配置的限制 | +| O6 Classic | `V1.3.2` | 常用接口和恢复有实机记录。原生速度查询可能改变配置 | +| O6 HOP 0.0.4 | `5.0.1` | 右手 CAN FD 常用接口及单关节运动恢复通过。FD→CAN 2.0 切换及经典帧验证见 [O6 HOP 实机记录](../../hardware-acceptance/o6/report.md#o6-hop-2026-11-25) | | L20 Lite | `V4.6.10` | 常用接口、缓存及恢复有实机记录;标量触觉不支持,关节 7/8 运动问题保留 | | L20 | `V3.0.6` | 常用接口和恢复有实机记录;速度 / 限流写入只验证发送,无配置读回;偶发故障记录保留 | | L30 | `V6.1.6` | 常用接口、使能 / 失能及恢复有实机记录;历史场次有 1 项跳过,不能记为实机通过 | diff --git a/docs/zh/tutorials/o6.md b/docs/zh/tutorials/o6.md index 1e8991af..b73aa0b4 100644 --- a/docs/zh/tutorials/o6.md +++ b/docs/zh/tutorials/o6.md @@ -1,11 +1,13 @@ # O6 功能文档 -O6 使用经典 CAN,包含 6 个关节。 +O6 有 6 个关节。SDK 默认使用原有 O6 Classic CAN 协议,支持 HOP 0.0.4 的固件可显式选择 HOP。 本页以 C++ `HandDevice` 为常用操作入口,示例按当前 C++ SDK 接口编写。 ## 目录 - [使用方式](#usage) +- [HOP 0.0.4 手动接入](#o6-hop) +- [切换 HOP 的 CAN 模式](#hop-can-mode) - [关节顺序](#关节顺序) - [身份识别](#identity) - [能力查询](#capabilities) @@ -18,7 +20,7 @@ O6 使用经典 CAN,包含 6 个关节。 ## 使用方式 -先按[准备接口](../connections/prepare-interface.md)配置环境,选择[自动连接](../connections/automatic.md) +对于使用原有 O6 Classic CAN 协议的固件,先按[准备接口](../connections/prepare-interface.md)配置环境,选择[自动连接](../connections/automatic.md) 或[手动连接](../connections/manual.md)。下面是 Linux SocketCAN 的完整只读程序, 提供本页后续片段使用的 `hand`、chrono 字面量和输出/等待函数。 Windows 连接时替换设备构造部分,传入已确认的 adapter factory;功能片段保持相同。 @@ -144,6 +146,93 @@ int main() try { 样本先检查 `meta.valid`,并按 `meta.stale` 判断是否过期;缓存读数不是实时测量。 关闭异常时长期应用应保留同一对象安排清理重试,不能直接另开连接。 + + +## HOP 0.0.4 手动接入 + +HOP 定义设备的寄存器和消息格式,CAN 2.0 与 CAN FD 承载这些消息。根据设备**当前**的协议与帧格式选择 `HandDeviceConfig::o6_protocol`。 +这个配置项只决定 SDK 如何通信。更改设备的帧格式使用[独立的 HOP 模式切换接口](#hop-can-mode)。 + +| 配置值 | 帧格式 | 地址 | +| --- | --- | --- | +| `O6Protocol::kClassic`(默认) | 原有 O6 Classic CAN | 左手 `0x28`,右手 `0x27` | +| `O6Protocol::kHopV004` | HOP 0.0.4,CAN FD 标准帧,SDK 发送时关闭 BRS | 请求 ID 默认 `0x001`,响应 ID 为请求 ID 按位或 `0x400` | +| `O6Protocol::kHopV004Can` | HOP 0.0.4,CAN 2.0 标准帧 | 与 HOP CAN FD 使用相同的 ID 规则 | + +HOP 使用显式手动连接。根据实际设备指定左右手、请求 ID 和适配器通道,`open()` 会读取设备身份并核对侧别。 +核对 CAN_H 与 CAN_L 的接线及终端匹配。实测右手使用 `0x001/0x401`、标称速率 1 Mbit/s、数据速率 5 Mbit/s、BRS 关闭。 +对于相同设置的 Linux SocketCAN 设备,运行以下命令配置 `can0`。 + +```bash +sudo ip link set can0 down +sudo ip link set can0 up type can bitrate 1000000 dbitrate 5000000 fd on +ip -details link show can0 +``` + +以下程序只读 CAN 配置与角度。若设备当前运行 HOP CAN 2.0,将协议改为 `kHopV004Can`,并用标称速率和 `fd off` 配置 SocketCAN。 + +```cpp +#include +#include +#include + +int main() try { + using namespace linkerbot::hand; + HandDeviceConfig config; + config.model = Model::kO6; + config.side = HandSide::kRight; + config.interface_name = "can0"; + config.address = 0x001; + config.o6_protocol = O6Protocol::kHopV004; + + HandDevice hand(config); + hand.open(); + const auto can = hand.get_can_configuration(); + std::cout << "request_id=0x" << std::hex << can.request_id + << " response_id=0x" << can.response_id() << std::dec + << " mode=" << (can.interface_mode == HopCanInterfaceMode::kCanFd ? "canfd" : "can") + << " nominal=" << can.nominal_bitrate << " data=" << can.data_bitrate + << " brs=" << can.brs << '\n'; + const auto angles = hand.get_angles(); + for (const auto angle : angles.raw) { + std::cout << angle << ' '; + } + std::cout << '\n'; + hand.close(); + return angles.meta.valid ? 0 : 1; +} catch (const std::exception &error) { + std::cerr << error.what() << '\n'; + return 1; +} +``` + + + +## 切换 HOP 的 CAN 模式 + +`get_can_configuration()` 读取设备的请求 ID、接口模式、BRS、标称速率和数据速率。 +向 `set_can_interface_mode()` 传入 `HopCanInterfaceMode::kCan20` 或 `HopCanInterfaceMode::kCanFd` 可切换设备侧 HOP 接口的帧格式, +对应 MI `0x35` / SI `0x06` 的值 `1` 或 `2`。切到 CAN 2.0 前,设备端 BRS 必须已关闭。 +调用前通过设备的当前模式建立连接。一次调用最多发送一次模式写入。主机接口由操作系统或适配器单独配置。 + +Linux SocketCAN 的 `hop_can_mode` 示例可先只读检查身份和当前配置。 + +```bash +cmake -S . -B build -DLINKERBOT_BUILD_EXAMPLES=ON +cmake --build build --target hop_can_mode +./build/examples/hop_can_mode can0 o6 right --request-id 0x001 +``` + +- `--from-mode canfd|can` 选择连接时的帧格式,默认 `canfd`。`can` 仅适用于 O6 HOP。 +- `--mode can|canfd` 写入目标模式。默认仅改易失配置,`--save` 另发一次 Flash 保存指令。断电保持尚未实测。 +- 以实际回复帧格式为准。API 返回 `active_wire_is_fd`。CLI 返回 `2` 表示寄存器已经核对,回复仍使用旧格式,需在受控重启后复查。新模式生效后,关闭原连接,按新模式配置主机和适配器,再以对应的 `o6_protocol` 新建连接。 +- CAN 2.0→CAN FD 需要适配器能接收切换后立即到达的 FD 回复。经典 SocketCAN 连接无法接收该回复。 + 当前 SDK 的 HOP CAN 2.0 请求缺少显式 Classic 帧标记,配置为 FD 的 SocketCAN 和 MiniCANFD 通道可能把它发成 FD 帧。 + 切换超时时,先按目标模式核对设备的实际状态,再决定是否重试。 + +candleLightFD 已验证 C++ `HandDevice` 的 HOP CAN FD 常用功能。MiniCANFD 已验证 C++ 发起 FD→CAN 2.0 切换, +切换后的经典帧读写及恢复 FD 使用适配器的原生接口。完整组合和验证范围见 [O6 HOP 实机记录](../../hardware-acceptance/o6/report.md#o6-hop-2026-11-25)。 + ## 关节顺序 SDK 按以下顺序读取和设置关节数据。 @@ -253,9 +342,8 @@ wait_command(hand.set_speeds(std::vector(6, 100.0))); ### 速度配置读取 -配置速度读取的是本次连接中完整速度写回复的缓存,不发送新的速度查询。 -先执行速度设置,再在同一连接中读取;`get_speeds()` 实时速度接口不支持。 -O6 V1.3.2 固件不得用原生 `speed.get_blocking()` 主动查速度,该请求可能将速度改为 0。 +HOP 的 `get_configured_speeds()` 查询设备寄存器。原有 Classic 协议读取本次连接中完整速度写回复的缓存,须先在同一连接中设置速度。 +Classic V1.3.2 的原生 `speed.get_blocking()` 查询可能将设备速度改为 0。 ```cpp print_sample(hand.get_configured_speeds(1s)); @@ -267,13 +355,13 @@ print_sample(hand.get_configured_speeds(1s)); ### 加速度设置 -`set_accelerations()` 接收 6 个原始计数,范围 `0..254`,不能直接当作物理加速度。 +`set_accelerations()` 接收 6 个原始计数。原有 Classic 协议范围为 `0..254`,HOP 为 `0..255`。 ```cpp wait_command(hand.set_accelerations(std::vector(6, 100.0))); ``` -O6 的 `0` 是协议中的特殊最大加速度编码,不等于零加速度。 +原有 Classic 协议用 `0` 表示特殊最大加速度。HOP 的物理加速度换算尚未确认。 ### 加速度配置读取 @@ -297,7 +385,7 @@ print_sample(hand.get_currents(1s)); ### 温度读取 -本型号温度能力表声明单位为摄氏度;仍须检查样本有效性。 +原有 Classic 协议的温度单位为摄氏度。HOP 能力表提供原始计数。两种协议都应检查样本有效性。 ```cpp print_sample(hand.get_temperatures(1s)); @@ -305,8 +393,8 @@ print_sample(hand.get_temperatures(1s)); ### 触觉点阵读取 -C++ 使用 `get_force(vector{"fn"}, timeout)` 选择字段,并通过 `field("fn")` 读取, -不是 Python 的 `force.fn.raw`。`raw` 中每个可选向量对应一个手指;`nullopt` 表示缺失, +用 `get_force(vector{"fn"}, timeout)` 选择字段,并通过 `field("fn")` 读取。 +`raw` 中每个可选向量对应一个手指,`nullopt` 表示缺失, `valid_values` 中的 `false` 表示该值无效。前置函数 `print_field()` 按这些信息显示,不补零、不自行求和。 ```cpp @@ -314,7 +402,7 @@ const auto force = hand.get_force(std::vector{"fn"}, 1s); print_field(force, "fn"); ``` -默认点阵形状为 5 个手指,每指 10×4。返回字段及 `force.tactile` 保留实际数据;以当前能力和固件为准。 +原有 Classic 协议的默认点阵形状为 5 个手指,每指 10×4。HOP 的字段和形状按各指传感器描述读取。 更多功能、固件限制和物理单位说明见[各型号能力说明](../reference/model-capabilities.md)。 diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index c9aefd27..cd81be5a 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -29,3 +29,12 @@ if(LINKERBOT_BUILD_TESTS) add_test(NAME l6_hop_readonly_invalid COMMAND l6_hop_readonly can0 neither) set_tests_properties(l6_hop_readonly_invalid PROPERTIES WILL_FAIL TRUE) endif() + +# Read-only unless --mode is passed. Help and argument checks perform no I/O. +add_executable(hop_can_mode hop_can_mode.cpp) +target_link_libraries(hop_can_mode PRIVATE linkerbot::cpp-sdk) +if(LINKERBOT_BUILD_TESTS) + add_test(NAME hop_can_mode_help COMMAND hop_can_mode --help) + add_test(NAME hop_can_mode_invalid COMMAND hop_can_mode can0 neither) + set_tests_properties(hop_can_mode_invalid PROPERTIES WILL_FAIL TRUE) +endif() diff --git a/examples/hop_can_mode.cpp b/examples/hop_can_mode.cpp new file mode 100644 index 00000000..48444661 --- /dev/null +++ b/examples/hop_can_mode.cpp @@ -0,0 +1,203 @@ +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace { + constexpr const char *kUsage = + "Usage: hop_can_mode [--request-id 0x001] " + "[--from-mode canfd|can] [--mode can|canfd] [--save]\n" + "Without --mode the tool only reads identity and MI 0x35 CAN configuration.\n" + "--from-mode can is valid for O6. L6 and O30 open a CAN FD socket.\n" + "--save stores the verified mode with MI 0x35 SI 0x1E and requires --mode.\n" + "Exit 2 means the register matches the target but the active wire format is still pending a restart.\n"; + + struct Options { + std::string interface; + std::string model; + std::string side; + uint32_t request_id = 0x001; + std::string from_mode = "canfd"; + std::optional mode; + bool save = false; + }; + + [[nodiscard]] std::string require_value(int argc, char **argv, int &index, std::string_view name) { + if (index + 1 >= argc) { + throw std::invalid_argument(std::string(name) + " requires a value"); + } + ++index; + return argv[index]; + } + + [[nodiscard]] Options parse(int argc, char **argv) { + Options options; + int positionals = 0; + for (int index = 1; index < argc; ++index) { + const std::string arg = argv[index]; + if (arg == "--request-id") { + const auto text = require_value(argc, argv, index, arg); + size_t used = 0; + const auto id = std::stoul(text, &used, 0); + if (used != text.size() || id > 0x3FEU) { + throw std::invalid_argument("request ID must be 0..0x3FE"); + } + options.request_id = static_cast(id); + } else if (arg == "--from-mode") { + options.from_mode = require_value(argc, argv, index, arg); + if (options.from_mode != "can" && options.from_mode != "canfd") { + throw std::invalid_argument("--from-mode must be can or canfd"); + } + } else if (arg == "--mode") { + options.mode = require_value(argc, argv, index, arg); + if (*options.mode != "can" && *options.mode != "canfd") { + throw std::invalid_argument("--mode must be can or canfd"); + } + } else if (arg == "--save") { + options.save = true; + } else if (!arg.empty() && arg[0] == '-') { + throw std::invalid_argument("unknown option " + arg); + } else if (positionals == 0) { + options.interface = arg; + ++positionals; + } else if (positionals == 1) { + options.model = arg; + ++positionals; + } else if (positionals == 2) { + options.side = arg; + ++positionals; + } else { + throw std::invalid_argument("unexpected argument " + arg); + } + } + if (positionals != 3) { + throw std::invalid_argument("expected interface, model and side"); + } + if (options.model != "o6" && options.model != "l6" && options.model != "o30") { + throw std::invalid_argument("model must be o6, l6 or o30"); + } + if (options.side != "left" && options.side != "right") { + throw std::invalid_argument("side must be left or right"); + } + if (options.save && !options.mode) { + throw std::invalid_argument("--save requires --mode"); + } + if (options.from_mode == "can" && options.model != "o6") { + throw std::invalid_argument("--from-mode can is only valid for o6"); + } + return options; + } + + [[nodiscard]] const char *model_name(linkerbot::hand::Model model) { + using linkerbot::hand::Model; + switch (model) { + case Model::kO6: + return "O6"; + case Model::kL6: + return "L6"; + case Model::kO30: + return "O30"; + case Model::kL20: + return "L20"; + case Model::kL20Lite: + return "L20Lite"; + case Model::kL30: + return "L30"; + case Model::kUnknown: + return "unknown"; + } + return "unknown"; + } + + [[nodiscard]] const char *side_name(linkerbot::hand::HandSide side) { + using linkerbot::hand::HandSide; + switch (side) { + case HandSide::kLeft: + return "left"; + case HandSide::kRight: + return "right"; + case HandSide::kUnknown: + return "unknown"; + } + return "unknown"; + } + + void print_configuration(const linkerbot::hand::HopCanConfiguration &configuration) { + std::cout << "request_id=0x" << std::hex << configuration.request_id << std::dec << " response_id=0x" + << std::hex << configuration.response_id() << std::dec << " mode=" + << (configuration.interface_mode == linkerbot::hand::HopCanInterfaceMode::kCanFd ? "canfd" : "can") + << " brs=" << (configuration.brs ? 1 : 0) << " nominal=" << configuration.nominal_bitrate + << " data=" << configuration.data_bitrate << '\n'; + } +} // namespace + +int main(int argc, char **argv) { + if (argc == 1 || (argc == 2 && std::string(argv[1]) == "--help")) { + std::cout << kUsage; + return 0; + } + try { + const auto options = parse(argc, argv); + using namespace linkerbot::hand; + HandDeviceConfig config; + config.interface_name = options.interface; + config.side = options.side == "left" ? HandSide::kLeft : HandSide::kRight; + config.address = options.request_id; + if (options.model == "o6") { + config.model = Model::kO6; + config.o6_protocol = options.from_mode == "can" ? O6Protocol::kHopV004Can : O6Protocol::kHopV004; + } else if (options.model == "l6") { + config.model = Model::kL6; + config.l6_protocol = L6Protocol::kHopV004; + } else { + config.model = Model::kO30; + } + + constexpr auto kTimeout = std::chrono::milliseconds{500}; + HandDevice hand(config); + hand.open(); + const auto identity = hand.get_identity(); + if (!identity) { + throw std::runtime_error("device identity unavailable after open"); + } + std::cout << model_name(identity->model) << ' ' << side_name(identity->side) + << " serial=" << identity->serial_number.value_or("") + << " protocol=" << identity->protocol_name.value_or("") + << " version=" << identity->protocol_version.value_or("") << '\n'; + + int status = 0; + if (!options.mode) { + print_configuration(hand.get_can_configuration(kTimeout)); + } else { + const auto target = *options.mode == "canfd" ? HopCanInterfaceMode::kCanFd : HopCanInterfaceMode::kCan20; + const auto result = hand.set_can_interface_mode(target, options.save, kTimeout); + std::cout << "before "; + print_configuration(result.before); + std::cout << "after "; + print_configuration(result.after); + std::cout << "write_sent=" << (result.write_sent ? "yes" : "no") << '\n'; + if (options.save) { + std::cout << (result.saved_to_flash ? "Flash save confirmed ONCE; power-cycle persistence untested\n" + : "Flash save was not confirmed\n"); + } + const bool target_fd = target == HopCanInterfaceMode::kCanFd; + if (result.active_wire_is_fd == target_fd) { + std::cout << "ACTIVE: target register and actual reply format verified\n"; + } else { + std::cout << "PENDING: target register verified, active format unchanged. " + "No automatic restart; verify after a controlled restart.\n"; + status = 2; + } + } + hand.close(); + return status; + } catch (const std::exception &error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/include/linkerbot/hand/api/can_configuration.hpp b/include/linkerbot/hand/api/can_configuration.hpp new file mode 100644 index 00000000..0af62e4d --- /dev/null +++ b/include/linkerbot/hand/api/can_configuration.hpp @@ -0,0 +1,95 @@ +#pragma once + +#include +#include +#include + +#include + +namespace linkerbot::hand { + // Device-side HOP MI 0x35 CAN controller settings. These values do not + // reconfigure the host adapter. + enum class HopCanInterfaceMode : uint8_t { kCan20 = 1, kCanFd = 2 }; + + // Nominal bitrate codes 1..8 from MI 0x35 SI 0x08. + inline constexpr std::array kHopNominalBitrates{1000000, 800000, 500000, 400000, + 250000, 200000, 125000, 100000}; + + // Data bitrate codes 1..13 from MI 0x35 SI 0x09. + inline constexpr std::array kHopDataBitrates{ + 8000000, 5000000, 4000000, 3000000, 2000000, 1000000, 800000, 500000, 400000, 250000, 200000, 125000, 100000}; + + struct HopCanConfiguration { + uint16_t request_id = 0; + HopCanInterfaceMode interface_mode = HopCanInterfaceMode::kCanFd; + bool brs = false; + uint32_t nominal_bitrate = 0; + uint32_t data_bitrate = 0; + + [[nodiscard]] uint32_t response_id() const noexcept { return static_cast(request_id) | 0x400U; } + }; + + // Outcome of one interface-mode change. A mode write is sent at most once. + // saved_to_flash is true after a single accepted 1-byte completion for + // MI 0x35 SI 0x1E. Real O6/O30 firmware completes Flash save with 0x00; + // existing fixtures echo the request byte 0x01. Both completions are accepted. + // active_format_changed is true when the reply wire format already matches + // the new mode. False means the register was verified and a reboot is still + // required before the active format changes. + struct HopCanModeSwitchResult { + HopCanConfiguration before; + HopCanConfiguration after; + bool write_sent = false; + bool saved_to_flash = false; + bool active_wire_is_fd = true; + bool active_format_changed = false; + }; + + [[nodiscard]] inline bool is_hop_can_interface_mode(HopCanInterfaceMode mode) noexcept { + return mode == HopCanInterfaceMode::kCan20 || mode == HopCanInterfaceMode::kCanFd; + } + + [[nodiscard]] inline uint32_t decode_hop_nominal_bitrate(uint8_t code) { + if (code < 1 || code > kHopNominalBitrates.size()) { + throw ProtocolError("HOP returned invalid CAN configuration codes"); + } + return kHopNominalBitrates[static_cast(code - 1)]; + } + + [[nodiscard]] inline uint32_t decode_hop_data_bitrate(uint8_t code) { + if (code < 1 || code > kHopDataBitrates.size()) { + throw ProtocolError("HOP returned invalid CAN configuration codes"); + } + return kHopDataBitrates[static_cast(code - 1)]; + } + + // SI 0x00 is a little-endian request ID. SI 0x06 is interface mode, BRS, + // nominal bitrate code and data bitrate code. + [[nodiscard]] inline HopCanConfiguration parse_hop_can_configuration(const uint8_t *request_id, + size_t request_id_size, + const uint8_t *interface_bytes, + size_t interface_size) { + if (request_id == nullptr || interface_bytes == nullptr || request_id_size != 2 || interface_size != 4) { + throw ProtocolError("HOP CAN configuration requires a 2-byte request ID and a 4-byte interface block"); + } + const auto id = + static_cast(static_cast(request_id[0]) | (static_cast(request_id[1]) << 8U)); + if (id > 0x3FE) { + throw ProtocolError("HOP returned invalid standard CAN ID"); + } + if (interface_bytes[0] != static_cast(HopCanInterfaceMode::kCan20) && + interface_bytes[0] != static_cast(HopCanInterfaceMode::kCanFd)) { + throw ProtocolError("HOP returned invalid CAN configuration codes"); + } + if (interface_bytes[1] > 1) { + throw ProtocolError("HOP returned invalid CAN configuration codes"); + } + HopCanConfiguration result; + result.request_id = id; + result.interface_mode = static_cast(interface_bytes[0]); + result.brs = interface_bytes[1] == 1; + result.nominal_bitrate = decode_hop_nominal_bitrate(interface_bytes[2]); + result.data_bitrate = decode_hop_data_bitrate(interface_bytes[3]); + return result; + } +} // namespace linkerbot::hand diff --git a/include/linkerbot/hand/api/config.hpp b/include/linkerbot/hand/api/config.hpp index 9a0b88c5..2597be2b 100644 --- a/include/linkerbot/hand/api/config.hpp +++ b/include/linkerbot/hand/api/config.hpp @@ -17,6 +17,7 @@ namespace linkerbot::hand { enum class RuntimeBehavior : uint8_t { kNative, kPython }; enum class L6Protocol : uint8_t { kClassic, kHopV004 }; + enum class O6Protocol : uint8_t { kClassic, kHopV004, kHopV004Can }; // Runtime-only policies that may be supplied independently of a physical // endpoint. Discovery owns model, side, interface and address selection; // callers own these execution policies. @@ -107,6 +108,9 @@ namespace linkerbot::hand { std::chrono::milliseconds recovery_backoff{100}; // Explicit opt-in for the latest L6 firmware; legacy defaults remain Classic. L6Protocol l6_protocol = L6Protocol::kClassic; + // Explicit opt-in for O6 HOP v0.0.4 firmware (CAN FD or Classic CAN 2.0); + // legacy defaults remain Classic. + O6Protocol o6_protocol = O6Protocol::kClassic; // Explicit protocol layout, not firmware inference. V25 matches the // Python whole-hand path; native Managers retain mounted V36 behavior. O30Layout o30_layout = O30Layout::kMountedV36; diff --git a/include/linkerbot/hand/api/device.hpp b/include/linkerbot/hand/api/device.hpp index 5801a422..a9bf4e88 100644 --- a/include/linkerbot/hand/api/device.hpp +++ b/include/linkerbot/hand/api/device.hpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -77,6 +78,13 @@ namespace linkerbot::hand { // Python-compatible read behavior uses refresh_device_info() below. [[nodiscard]] DeviceIdentity get_device_info(std::chrono::milliseconds timeout = std::chrono::milliseconds{ 1000}); + // Reads MI 0x35 SI 0x00 and SI 0x06. Classic hands reject this before any frame is sent. + [[nodiscard]] HopCanConfiguration + get_can_configuration(std::chrono::milliseconds timeout = std::chrono::milliseconds{200}); + // Writes MI 0x35 SI 0x06 at most once, then optionally saves MI 0x35 SI 0x1E once. + [[nodiscard]] HopCanModeSwitchResult + set_can_interface_mode(HopCanInterfaceMode mode, bool save_to_flash = false, + std::chrono::milliseconds timeout = std::chrono::milliseconds{500}); // Active identity read in the current generation. Success does not // cancel commands or restart polling. A physical identity mismatch // faults this facade; timeout/protocol errors leave admission unchanged. diff --git a/include/linkerbot/hand/capabilities.hpp b/include/linkerbot/hand/capabilities.hpp index 871c5a3c..219d24e9 100644 --- a/include/linkerbot/hand/capabilities.hpp +++ b/include/linkerbot/hand/capabilities.hpp @@ -228,6 +228,9 @@ namespace linkerbot::hand { std::vector acknowledged_operations; bool calibrate = false; bool save_parameters_confirmed = false; + // HOP MI 0x35 CAN controller settings. Default false leaves classic profiles unchanged. + bool read_can_configuration = false; + bool write_can_configuration = false; [[nodiscard]] bool supports(DeviceOperation operation) const noexcept; [[nodiscard]] bool acknowledged(DeviceOperation operation) const noexcept; diff --git a/include/linkerbot/hand/l6/hop_l6.hpp b/include/linkerbot/hand/l6/hop_l6.hpp index 71470917..cc9aa729 100644 --- a/include/linkerbot/hand/l6/hop_l6.hpp +++ b/include/linkerbot/hand/l6/hop_l6.hpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -123,6 +124,11 @@ namespace linkerbot::hand::l6 { ConfigManager(const ConfigManager &) = delete; ConfigManager &operator=(const ConfigManager &) = delete; void save(std::chrono::milliseconds timeout = std::chrono::milliseconds{100}); + [[nodiscard]] HopCanConfiguration + get_can_configuration(std::chrono::milliseconds timeout = std::chrono::milliseconds{200}); + [[nodiscard]] HopCanModeSwitchResult + set_can_interface_mode(HopCanInterfaceMode mode, bool save_to_flash = false, + std::chrono::milliseconds timeout = std::chrono::milliseconds{500}); private: friend class HopL6; diff --git a/include/linkerbot/hand/o30/config_manager.hpp b/include/linkerbot/hand/o30/config_manager.hpp index d9382ce3..74eb2b95 100644 --- a/include/linkerbot/hand/o30/config_manager.hpp +++ b/include/linkerbot/hand/o30/config_manager.hpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -37,6 +38,12 @@ namespace linkerbot::hand::o30 { void restore_all(bool confirm, std::chrono::milliseconds timeout_ms = std::chrono::milliseconds{200}); void save_to_flash(bool confirm, std::chrono::milliseconds timeout_ms = std::chrono::milliseconds{200}); + [[nodiscard]] HopCanConfiguration + get_can_configuration(std::chrono::milliseconds timeout = std::chrono::milliseconds{200}); + [[nodiscard]] HopCanModeSwitchResult + set_can_interface_mode(HopCanInterfaceMode mode, bool save_to_flash = false, + std::chrono::milliseconds timeout = std::chrono::milliseconds{500}); + // Raw field access: firmware may reject unverified blocks. Restore, // save and partial standard-ID writes are rejected locally. void write_field(uint8_t si, const std::vector &payload, diff --git a/include/linkerbot/hand/o6/hop_o6.hpp b/include/linkerbot/hand/o6/hop_o6.hpp new file mode 100644 index 00000000..a2a37a9c --- /dev/null +++ b/include/linkerbot/hand/o6/hop_o6.hpp @@ -0,0 +1,200 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace linkerbot::hand::o6 { + // HOP v0.0.4 has different fault meanings from classic O6 FaultCode. + enum class HopFaultCode : uint8_t { + kHandStall = 0x01, + kActuatorStall = 0x02, + kOvercurrent = 0x04, + kOvertemperature = 0x08, + kActuatorAbnormal = 0x40, + kActuatorOffline = 0x80 + }; + + // O6 HOP v0.0.4 firmware: standard CAN FD (no BRS) or Classic CAN 2.0. + // All 0x01..0x0C channels use single-byte u8 counts (0..255); MI 0x20 is + // unsupported by O6 HOP v0.0.4. All managers share one runtime; stop() + // leaves a borrowed Session running. + class HopO6 { + std::shared_ptr session_; + std::shared_ptr runtime_; + bool owns_session_ = false; + uint32_t request_id_; + bool can_fd_ = true; + DeviceCapabilities capabilities_; + runtime::CallDrain calls_; + + public: + class AngleManager { + public: + AngleManager(const AngleManager &) = delete; + AngleManager &operator=(const AngleManager &) = delete; + void set_angles(const std::array &values, + std::chrono::milliseconds timeout = std::chrono::milliseconds{100}); + void set_angles_percent(const std::array &values, + std::chrono::milliseconds timeout = std::chrono::milliseconds{100}); + [[nodiscard]] AngleSample get_blocking(std::chrono::milliseconds timeout = std::chrono::milliseconds{100}); + [[nodiscard]] std::optional get_snapshot() const; + + private: + friend class HopO6; + explicit AngleManager(HopO6 &owner) : owner_(&owner) {} + HopO6 *owner_; + }; + + class VectorManager { + public: + VectorManager(const VectorManager &) = delete; + VectorManager &operator=(const VectorManager &) = delete; + void set_values(const std::array &values, + std::chrono::milliseconds timeout = std::chrono::milliseconds{100}); + [[nodiscard]] RawVectorSample get_blocking(std::chrono::milliseconds timeout = std::chrono::milliseconds{ + 100}); + [[nodiscard]] std::optional get_snapshot() const; + + private: + friend class HopO6; + struct VectorBinding { + uint8_t mi; + bool configured; + TelemetrySemantic semantic; + const char *domain; + const char *family; + }; + VectorManager(HopO6 &owner, uint8_t mi, bool configured, TelemetrySemantic semantic, const char *domain, + const char *family = nullptr) + : VectorManager(owner, VectorBinding{mi, configured, semantic, domain, family}) {} + VectorManager(HopO6 &owner, const VectorBinding &binding) + : owner_(&owner), mi_(binding.mi), configured_(binding.configured), semantic_(binding.semantic), + domain_(binding.domain), family_(binding.family) {} + HopO6 *owner_; + uint8_t mi_; + bool configured_; + TelemetrySemantic semantic_; + const char *domain_; + const char *family_; + }; + + class FaultManager { + public: + FaultManager(const FaultManager &) = delete; + FaultManager &operator=(const FaultManager &) = delete; + [[nodiscard]] FaultSample get_blocking(std::chrono::milliseconds timeout = std::chrono::milliseconds{100}); + [[nodiscard]] std::optional get_snapshot() const; + + private: + friend class HopO6; + explicit FaultManager(HopO6 &owner) : owner_(&owner) {} + HopO6 *owner_; + }; + + class ForceSensorManager { + public: + ForceSensorManager(const ForceSensorManager &) = delete; + ForceSensorManager &operator=(const ForceSensorManager &) = delete; + [[nodiscard]] ForceSample get_blocking(std::chrono::milliseconds timeout = std::chrono::milliseconds{1000}); + [[nodiscard]] std::optional get_snapshot() const; + + private: + friend class HopO6; + explicit ForceSensorManager(HopO6 &owner) : owner_(&owner) {} + HopO6 *owner_; + }; + + class VersionManager { + public: + VersionManager(const VersionManager &) = delete; + VersionManager &operator=(const VersionManager &) = delete; + [[nodiscard]] DeviceIdentity get_blocking(std::chrono::milliseconds timeout = std::chrono::milliseconds{ + 1000}); + [[nodiscard]] std::optional get_snapshot() const; + + private: + friend class HopO6; + explicit VersionManager(HopO6 &owner) : owner_(&owner) {} + HopO6 *owner_; + }; + + class ConfigManager { + public: + ConfigManager(const ConfigManager &) = delete; + ConfigManager &operator=(const ConfigManager &) = delete; + void save(std::chrono::milliseconds timeout = std::chrono::milliseconds{100}); + [[nodiscard]] HopCanConfiguration + get_can_configuration(std::chrono::milliseconds timeout = std::chrono::milliseconds{200}); + [[nodiscard]] HopCanModeSwitchResult + set_can_interface_mode(HopCanInterfaceMode mode, bool save_to_flash = false, + std::chrono::milliseconds timeout = std::chrono::milliseconds{500}); + + private: + friend class HopO6; + explicit ConfigManager(HopO6 &owner) : owner_(&owner) {} + HopO6 *owner_; + }; + + HopO6(Side side, std::string_view interface_name, uint32_t request_id = hop::kDefaultRequestId, + bool can_fd = true); + HopO6(Side side, std::unique_ptr transport, uint32_t request_id = hop::kDefaultRequestId, + bool can_fd = true); + HopO6(Side side, std::shared_ptr session, uint32_t request_id = hop::kDefaultRequestId, + bool can_fd = true); + ~HopO6(); + HopO6(const HopO6 &) = delete; + HopO6 &operator=(const HopO6 &) = delete; + HopO6(HopO6 &&) = delete; + HopO6 &operator=(HopO6 &&) = delete; + + [[nodiscard]] uint32_t request_id() const { return request_id_; } + [[nodiscard]] uint32_t response_id() const { return hop::response_id(request_id_); } + [[nodiscard]] bool can_fd() const noexcept { return can_fd_; } + [[nodiscard]] std::shared_ptr runtime() const { return runtime_; } + [[nodiscard]] const DeviceCapabilities &capabilities() const noexcept { return capabilities_; } + [[nodiscard]] HandHealth health() const { return runtime_->health(); } + [[nodiscard]] HandSnapshot get_snapshot() const; + void start_polling(const PollingPlan &plan = {}); + void stop_polling(); + [[nodiscard]] std::shared_ptr> stream_handle(size_t max_size = 100); + EventQueue &stream(size_t max_size = 100) { return *stream_handle(max_size); } + void stop_stream(); + void recover(); + void stop(); + + AngleManager angle; + VectorManager speed, acceleration, current_limit, current, temperature; + VectorManager stall_detection_time, stall_threshold, stall_hold_current; + FaultManager fault; + ForceSensorManager force_sensor; + VersionManager version; + ConfigManager config; + + private: + runtime::DeviceRuntime::Operation operation(std::chrono::milliseconds timeout); + std::vector read_range(uint8_t mi, uint8_t si, size_t length, bool rts, runtime::Deadline deadline); + runtime::Sample execute(runtime::TransactionPlan plan, runtime::Deadline deadline); + SampleMeta metadata(const runtime::Sample &provenance, const char *domain, bool configured = false) const; + void publish(std::string domain, HandEvent event, runtime::Sample provenance); + mutable std::mutex event_mutex_; + std::mutex lifecycle_mutex_; + std::shared_ptr> events_; + std::vector>> retired_streams_; + }; +} // namespace linkerbot::hand::o6 diff --git a/include/linkerbot/hand/o6/hop_protocol.hpp b/include/linkerbot/hand/o6/hop_protocol.hpp new file mode 100644 index 00000000..9d2022c9 --- /dev/null +++ b/include/linkerbot/hand/o6/hop_protocol.hpp @@ -0,0 +1,186 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace linkerbot::hand::o6::hop { + inline constexpr uint32_t kDefaultRequestId = 1; + // Canonical order: thumb_flex, thumb_abd, index, middle, ring, pinky. + // HOP single-byte slot layout: slot 5 = yaw_thumb (thumb_abd), + // slots 10..14 = root1_thumb..root1_little. + inline constexpr std::array kJointSlots{10, 5, 11, 12, 13, 14}; + inline constexpr uint8_t kFaultMask = 0xcf; + inline constexpr size_t kMaxCan20Payload = 5; + inline constexpr size_t kMaxCanFdPayload = hand::protocol::hop::kMaxHopPayload; + + inline constexpr uint8_t kMiPosition = 0x01; + inline constexpr uint8_t kMiSpeed = 0x02; + inline constexpr uint8_t kMiAcceleration = 0x03; + inline constexpr uint8_t kMiCurrent = 0x04; + inline constexpr uint8_t kMiTemperature = 0x07; + inline constexpr uint8_t kMiStallTime = 0x09; + inline constexpr uint8_t kMiStallThreshold = 0x0a; + inline constexpr uint8_t kMiStallHoldCurrent = 0x0b; + inline constexpr uint8_t kMiFault = 0x0c; + inline constexpr uint8_t kMiSensorCommand = 0x31; + inline constexpr uint8_t kMiSensorData1 = 0x32; + inline constexpr uint8_t kMiSensorData2 = 0x33; + inline constexpr uint8_t kMiSensorData3 = 0x34; + inline constexpr uint8_t kMiConfig = 0x35; + inline constexpr uint8_t kMiProductInfo = 0x41; + + // MI 0x4F history entries are bitmasks, unrelated to O30 immediate errors. + enum class CommunicationError : uint8_t { + kNone = 0, + kMainIndexMissing = 0x01, + kSubIndexMissing = 0x02, + kNotWritable = 0x04, + kLengthMismatch = 0x08, + kPermissionDenied = 0x10, + kZeroPaddedResponse = 0x20 + }; + + inline uint32_t response_id(uint32_t id) { + if (id > 0x3fe) { + throw ValidationError("O6 HOP request ID must be 0..0x3FE"); + } + return id | 0x400U; + } + + inline size_t max_payload_bytes(bool can_fd) noexcept { return can_fd ? kMaxCanFdPayload : kMaxCan20Payload; } + + inline can::Message build_message(uint32_t request_id, uint8_t mi, uint8_t si, uint8_t edl, + const std::vector &payload, bool rts, bool can_fd = true) { + if (can_fd) { + static_cast(response_id(request_id)); + return hand::protocol::hop::build_message(request_id, mi, si, edl, payload, rts); + } + static_cast(response_id(request_id)); + if (edl == 0 || edl > kMaxCan20Payload || static_cast(si) + edl > 256) { + throw ValidationError("O6 HOP CAN 2.0 range must contain 1..5 bytes within 256-byte object"); + } + if (payload.size() > kMaxCan20Payload) { + throw ValidationError("O6 HOP CAN 2.0 write payload exceeds 5 bytes"); + } + if (!payload.empty() && payload.size() != edl) { + throw ValidationError("O6 HOP CAN 2.0 write EDL does not match payload size"); + } + can::Message msg{}; + msg.id = request_id; + msg.is_extended = false; + msg.is_fd = false; + msg.is_brs = false; + msg.dlc = static_cast(hand::protocol::hop::kHeaderBytes + payload.size()); + msg.data[0] = hand::protocol::hop::ctrl_byte(mi, rts); + msg.data[1] = si; + msg.data[2] = edl; + for (size_t i = 0; i < payload.size(); ++i) { + msg.data[hand::protocol::hop::kHeaderBytes + i] = payload[i]; + } + return msg; + } + + // One bounded register range. 0x4F is history, never an implicit negative ACK. + inline hand::protocol::TransactionPlan transaction(uint32_t id, uint8_t mi, uint8_t si, uint8_t length, + const std::vector &payload = {}, bool rts = false, + std::string family = {}, bool can_fd = true) { + const auto reply = response_id(id); + const auto limit = max_payload_bytes(can_fd); + if (!length || length > limit) { + throw ValidationError(can_fd ? "O6 HOP range must contain 1..61 bytes" + : "O6 HOP CAN 2.0 range must contain 1..5 bytes"); + } + hand::protocol::TransactionPlan plan; + plan.keys = {"hop"}; + plan.domain = "hop/range"; + plan.command_family = std::move(family); + plan.publish_after_send = !payload.empty(); + plan.frames = {build_message(id, mi, si, length, payload, rts, can_fd)}; + plan.consume = [reply, mi, si, length, rts, can_fd](const can::Message &msg) { + using hand::protocol::Progress; + if (msg.id != reply || msg.is_extended || msg.is_fd != can_fd) { + return Progress::unmatched(); + } + if (msg.dlc && msg.data[0] != hand::protocol::hop::ctrl_byte(mi, rts)) { + return Progress::unmatched(); + } + // A different range is unrelated (e.g. a duplicate from the previous + // chunk); a malformed response for this range fails the transaction. + if (msg.dlc >= 2 && msg.data[1] != si) { + return Progress::unmatched(); + } + if (can_fd) { + if (msg.dlc > 64 || hand::protocol::hop::canfd_wire_bytes(msg.dlc) != msg.dlc) { + throw ProtocolError("invalid O6 HOP CAN FD wire length"); + } + } else if (msg.dlc > 8) { + throw ProtocolError("invalid O6 HOP CAN 2.0 wire length"); + } + const auto frame = hand::protocol::hop::parse_frame(msg.data.data(), msg.dlc); + if (frame.edl != length) { + throw ProtocolError("O6 HOP response EDL does not match requested range"); + } + return Progress::complete(frame.payload); + }; + return plan; + } + + inline std::array project_bytes(const std::vector &data) { + if (data.size() != 10) { + throw ProtocolError("O6 HOP joint range must contain 10 bytes"); + } + std::array result{}; + for (size_t i = 0; i < result.size(); ++i) { + result[i] = data[kJointSlots[i] - 5]; + } + return result; + } + + // Both mounted ranges (SI=5 len=1 and SI=10 len=5) are one logical transaction: + // one send receipt, and no successful value until both complete replies arrive + // (in either order). Both frames fit within Classic CAN 2.0 (4 and 8 bytes) + // as well as CAN FD. + inline hand::protocol::TransactionPlan write_joints(uint32_t id, uint8_t mi, const std::vector &canonical, + bool rts, std::string family, bool can_fd = true) { + if (canonical.size() != 6) { + throw ValidationError("O6 HOP requires six joint values"); + } + const std::vector thumb{canonical[1]}; + const std::vector roots{canonical[0], canonical[2], canonical[3], canonical[4], canonical[5]}; + auto first = transaction(id, mi, 5, 1, thumb, rts, family, can_fd); + auto second = transaction(id, mi, 10, 5, roots, rts, std::move(family), can_fd); + first.frames.push_back(second.frames.front()); + first.domain = "hop/write"; + first.consume = [a = first.consume, b = second.consume, + parts = + std::array>, 2>{}](const can::Message &msg) mutable { + for (size_t i = 0; i < 2; ++i) { + auto result = (i == 0 ? a : b)(msg); + if (result.kind != hand::protocol::ProgressKind::complete) { + continue; + } + auto bytes = std::any_cast>(result.value); + if (parts[i] && *parts[i] != bytes) { + throw ProtocolError("conflicting O6 HOP write replies"); + } + parts[i] = std::move(bytes); + if (!parts[0] || !parts[1]) { + return hand::protocol::Progress::pending(); + } + std::vector range(10); + std::copy(parts[0]->begin(), parts[0]->end(), range.begin()); + std::copy(parts[1]->begin(), parts[1]->end(), range.begin() + 5); + return hand::protocol::Progress::complete(std::move(range), hand::protocol::Origin::command_feedback); + } + return hand::protocol::Progress::unmatched(); + }; + return first; + } + +} // namespace linkerbot::hand::o6::hop diff --git a/include/linkerbot/hand/o6/o6.hpp b/include/linkerbot/hand/o6/o6.hpp index 96ddc2c2..179e376d 100644 --- a/include/linkerbot/hand/o6/o6.hpp +++ b/include/linkerbot/hand/o6/o6.hpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -32,8 +33,6 @@ namespace linkerbot::hand::o6 { - enum class Side { kLeft, kRight }; - class O6 { // Declared first to ensure initialization before managers. uint32_t arbitration_id_; diff --git a/include/linkerbot/hand/o6/side.hpp b/include/linkerbot/hand/o6/side.hpp new file mode 100644 index 00000000..62feb7ff --- /dev/null +++ b/include/linkerbot/hand/o6/side.hpp @@ -0,0 +1,4 @@ +#pragma once +namespace linkerbot::hand::o6 { + enum class Side { kLeft, kRight }; +} diff --git a/src/hand/capabilities.cpp b/src/hand/capabilities.cpp index 75c64aed..434d2a09 100644 --- a/src/hand/capabilities.cpp +++ b/src/hand/capabilities.cpp @@ -454,7 +454,10 @@ namespace linkerbot::hand { << ",\"save_parameters\":" << (capabilities.operations.save_parameters ? "true" : "false") << ",\"save_parameters_confirmed\":" << (capabilities.operations.save_parameters_confirmed ? "true" : "false") - << ",\"calibrate\":" << (capabilities.operations.calibrate ? "true" : "false") << ",\"acknowledged\":["; + << ",\"calibrate\":" << (capabilities.operations.calibrate ? "true" : "false") + << ",\"read_can_configuration\":" << (capabilities.operations.read_can_configuration ? "true" : "false") + << ",\"write_can_configuration\":" << (capabilities.operations.write_can_configuration ? "true" : "false") + << ",\"acknowledged\":["; for (size_t index = 0; index < capabilities.operations.acknowledged_operations.size(); ++index) { if (index != 0) { out << ','; diff --git a/src/hand/capabilities/l6_hop.cpp b/src/hand/capabilities/l6_hop.cpp index f3618408..3a989832 100644 --- a/src/hand/capabilities/l6_hop.cpp +++ b/src/hand/capabilities/l6_hop.cpp @@ -2,8 +2,91 @@ #include #include #include +#include +#include namespace linkerbot::hand { + namespace { + DeviceCapabilities make_o6_hop_capabilities(const HandDeviceConfig &config) { + if (config.model != Model::kO6) { + throw ValidationError("O6 HOP protocol is only valid for O6"); + } + // Validate the enum even when no device I/O takes place. + (void)declared_capabilities(config.model, config.side); + using namespace capabilities_detail; + const bool can_fd = config.o6_protocol == O6Protocol::kHopV004; + DeviceCapabilities result; + result.model = Model::kO6; + result.side = config.side; + const auto id = config.address.value_or(o6::hop::kDefaultRequestId); + result.transport = {can_fd ? TransportKind::kCanFd : TransportKind::kCan, 1000000U, std::nullopt, false, + can_fd ? "O6 HOP 0.0.4 standard CAN FD; response ID = request ID | 0x400; no BRS" + : "O6 HOP 0.0.4 standard CAN 2.0; response ID = request ID | 0x400"}; + result.transport.request_id = id; + result.transport.response_id = o6::hop::response_id(id); + result.transport.mtu = can_fd ? 64 : 8; + const auto &legacy = declared_capabilities(Model::kO6, config.side); + result.joints = legacy.joints; + for (auto &joint : result.joints) { + joint.raw_angle_range = {0, 255, true, 1}; + joint.percent_mapping = PercentMapping{0, 255, "raw_min", "raw_max", Confidence::kUnknown}; + joint.physical_angle_mapping.reset(); + } + const auto names = channels(o6::kJointNames); + result.commands = { + angle_command(result.joints, "u8", AckSupport::kRequired, true), + command(CommandSemantic::kSpeeds, names, u8_range(), "u8", "count", std::nullopt, Confidence::kUnknown, + AckSupport::kRequired), + command(CommandSemantic::kAccelerations, names, u8_range(), "u8", "count", std::nullopt, + Confidence::kUnknown, AckSupport::kRequired), + command(CommandSemantic::kCurrentLimits, names, u8_range(), "u8", "count", std::nullopt, + Confidence::kUnknown, AckSupport::kRequired), + command(CommandSemantic::kStallDetectionTimes, names, u8_range(), "u8", "count", std::nullopt, + Confidence::kUnknown, AckSupport::kRequired), + command(CommandSemantic::kStallThresholds, names, u8_range(), "u8", "count", std::nullopt, + Confidence::kUnknown, AckSupport::kRequired), + command(CommandSemantic::kStallHoldCurrents, names, u8_range(), "u8", "count", std::nullopt, + Confidence::kUnknown, AckSupport::kRequired), + }; + result.commands.front().unit_confidence = Confidence::kDocumented; + result.telemetry = { + angle_telemetry(result.joints, "u8"), + telemetry(TelemetrySemantic::kConfiguredSpeeds, names, ReadMode::kQuery, "u8", {6}, u8_range(), "count", + std::nullopt, Confidence::kUnknown, false), + telemetry(TelemetrySemantic::kConfiguredAccelerations, names, ReadMode::kQuery, "u8", {6}, u8_range(), + "count", std::nullopt, Confidence::kUnknown, false), + telemetry(TelemetrySemantic::kCurrentLimits, names, ReadMode::kQuery, "u8", {6}, u8_range(), "count", + std::nullopt, Confidence::kUnknown, false), + telemetry(TelemetrySemantic::kCurrents, names, ReadMode::kQuery, "u8", {6}, u8_range(), "count"), + telemetry(TelemetrySemantic::kTemperatures, names, ReadMode::kQuery, "u8", {6}, u8_range(), "count"), + telemetry(TelemetrySemantic::kStallDetectionTimes, names, ReadMode::kQuery, "u8", {6}, u8_range(), + "count", std::nullopt, Confidence::kUnknown, false), + telemetry(TelemetrySemantic::kStallThresholds, names, ReadMode::kQuery, "u8", {6}, u8_range(), "count", + std::nullopt, Confidence::kUnknown, false), + telemetry(TelemetrySemantic::kStallHoldCurrents, names, ReadMode::kQuery, "u8", {6}, u8_range(), + "count", std::nullopt, Confidence::kUnknown, false), + telemetry(TelemetrySemantic::kFaults, names, ReadMode::kQuery, "u8_bitmask", {6}, u8_range()), + telemetry(TelemetrySemantic::kForce, finger_channels(), ReadMode::kQuery, "hop_tactile_descriptor", {5}, + std::nullopt, std::nullopt, "shape and units are supplied by sensor metadata", + Confidence::kDocumented), + }; + result.telemetry.front().unit_confidence = Confidence::kDocumented; + for (auto &channel : result.telemetry) { + channel.source = TelemetrySource::kDevice; + const auto *old = legacy.telemetry_channel(channel.semantic); + if (old) { + channel.freshness_ms = old->freshness_ms; + } + } + result.operations.read_device_info = true; + result.operations.save_parameters = true; + result.operations.read_can_configuration = true; + result.operations.write_can_configuration = true; + result.operations.acknowledged_operations = {DeviceOperation::kSaveParameters}; + return result; + } + } // namespace + DeviceCapabilities declared_capabilities(const HandDeviceConfig &config) { if (config.o30_layout != O30Layout::kMountedV36 && config.o30_layout != O30Layout::kPythonV25) { throw ValidationError("unknown O30 layout"); @@ -11,6 +94,19 @@ namespace linkerbot::hand { if (config.o30_layout == O30Layout::kPythonV25 && config.model != Model::kO30) { throw ValidationError("V25 layout is only valid for O30"); } + if (config.l6_protocol != L6Protocol::kClassic && config.l6_protocol != L6Protocol::kHopV004) { + throw ValidationError("unknown L6 protocol"); + } + if (config.o6_protocol != O6Protocol::kClassic && config.o6_protocol != O6Protocol::kHopV004 && + config.o6_protocol != O6Protocol::kHopV004Can) { + throw ValidationError("unknown O6 protocol"); + } + if (config.l6_protocol != L6Protocol::kClassic && config.model != Model::kL6) { + throw ValidationError("L6 HOP protocol is only valid for L6"); + } + if (config.o6_protocol != O6Protocol::kClassic) { + return make_o6_hop_capabilities(config); + } if (config.l6_protocol == L6Protocol::kClassic) { auto result = declared_capabilities(config.model, config.side); if (config.o30_layout == O30Layout::kPythonV25) { @@ -124,6 +220,8 @@ namespace linkerbot::hand { } result.operations.read_device_info = true; result.operations.save_parameters = true; + result.operations.read_can_configuration = true; + result.operations.write_can_configuration = true; result.operations.acknowledged_operations = {DeviceOperation::kSaveParameters}; return result; } diff --git a/src/hand/capabilities/o30.cpp b/src/hand/capabilities/o30.cpp index 9adca9b5..d66a6839 100644 --- a/src/hand/capabilities/o30.cpp +++ b/src/hand/capabilities/o30.cpp @@ -34,6 +34,8 @@ namespace linkerbot::hand::capabilities_detail { profile.side = side; profile.transport = o30_transport(); profile.operations.read_device_info = true; + profile.operations.read_can_configuration = true; + profile.operations.write_can_configuration = true; profile.joints = joints; profile.commands = { angle_command(joints, encoding, AckSupport::kRequired, true), diff --git a/src/hand/detail/hop_can_mode.hpp b/src/hand/detail/hop_can_mode.hpp new file mode 100644 index 00000000..c39ab8c7 --- /dev/null +++ b/src/hand/detail/hop_can_mode.hpp @@ -0,0 +1,257 @@ +#pragma once + +// Runtime helper for HOP MI 0x35 CAN mode reads and the single mode write. +// Protocol headers stay value-only; this file is the only place that waits. + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace linkerbot::hand::detail { + inline constexpr uint8_t kHopCanMi = 0x35; + inline constexpr uint8_t kHopCanRequestIdSi = 0x00; + inline constexpr uint8_t kHopCanInterfaceSi = 0x06; + inline constexpr uint8_t kHopCanSaveSi = 0x1E; + + struct HopCanFrameResult { + std::vector payload; + bool is_fd = false; + }; + + [[nodiscard]] inline std::chrono::milliseconds hop_can_operation_budget(std::chrono::milliseconds timeout) { + constexpr int kSteps = 8; + if (timeout.count() <= 0) { + return timeout; + } + if (timeout.count() > std::chrono::milliseconds::max().count() / kSteps) { + return std::chrono::milliseconds::max(); + } + return timeout * kSteps; + } + + [[nodiscard]] inline std::optional + exchange_hop_frame(runtime::DeviceRuntime &runtime, uint32_t request_id, bool send_is_fd, uint8_t mi, uint8_t si, + uint8_t edl, const std::vector &payload, bool rts, bool accept_either_format, + bool configuration_write, runtime::Deadline deadline) { + if (request_id > 0x3FEU) { + throw ValidationError("HOP request ID must be 0..0x3FE"); + } + const auto response_id = request_id | 0x400U; + auto frame = protocol::hop::build_message(request_id, mi, si, edl, payload, rts); + if (!send_is_fd) { + const auto useful = protocol::hop::kHeaderBytes + payload.size(); + if (useful > 8) { + throw ValidationError("HOP CAN 2.0 frame exceeds 8 bytes"); + } + frame.is_fd = false; + frame.is_brs = false; + frame.dlc = static_cast(useful); + } + protocol::TransactionPlan plan; + plan.keys = {"hop-can-configuration"}; + plan.domain = "hop/can-configuration"; + plan.poison_on_timeout = false; + plan.late_guard = std::chrono::milliseconds{0}; + plan.preserve_last_success = true; + if (configuration_write) { + plan.command_family = "configuration"; + plan.publish_after_send = true; + } + plan.frames = {std::move(frame)}; + plan.consume = [response_id, mi, si, edl, rts, send_is_fd, accept_either_format](const can::Message &message) { + using protocol::Progress; + if (message.id != response_id || message.is_extended) { + return Progress::unmatched(); + } + if (!accept_either_format && message.is_fd != send_is_fd) { + return Progress::unmatched(); + } + if (message.dlc < protocol::hop::kHeaderBytes) { + return Progress::unmatched(); + } + if (message.data[0] != protocol::hop::ctrl_byte(mi, rts)) { + return Progress::unmatched(); + } + if (message.data[1] != si) { + return Progress::unmatched(); + } + if (message.is_fd) { + if (message.dlc > 64 || protocol::hop::canfd_wire_bytes(message.dlc) != message.dlc) { + throw ProtocolError("invalid HOP CAN FD wire length"); + } + } else if (message.dlc > 8) { + throw ProtocolError("invalid HOP CAN 2.0 wire length"); + } + auto parsed = protocol::hop::parse_frame(message.data.data(), message.dlc); + if (parsed.edl != edl) { + throw ProtocolError("HOP response EDL does not match requested range"); + } + return Progress::complete(HopCanFrameResult{std::move(parsed.payload), message.is_fd}); + }; + try { + auto sample = runtime.execute(std::move(plan), deadline); + if (auto *reply = std::any_cast(&sample.value)) { + return std::move(*reply); + } + throw ProtocolError("HOP CAN configuration reply did not identify its wire format"); + } catch (const TimeoutError &) { + return std::nullopt; + } + } + + template + [[nodiscard]] HopCanConfiguration read_hop_can_configuration(bool wire_is_fd, Exchange &&exchange, + DeadlineFactory &&deadline) { + auto request = exchange(wire_is_fd, kHopCanMi, kHopCanRequestIdSi, 2, std::vector{}, true, false, + false, deadline()); + if (!request) { + throw TimeoutError("HOP CAN request ID read timed out"); + } + auto interface = exchange(wire_is_fd, kHopCanMi, kHopCanInterfaceSi, 4, std::vector{}, true, false, + false, deadline()); + if (!interface) { + throw TimeoutError("HOP CAN interface read timed out"); + } + if (request->is_fd != wire_is_fd || interface->is_fd != wire_is_fd) { + throw ProtocolError("HOP CAN configuration reply format does not match the active wire"); + } + return parse_hop_can_configuration(request->payload.data(), request->payload.size(), interface->payload.data(), + interface->payload.size()); + } + + template + [[nodiscard]] std::optional + probe_hop_can_interface(Exchange &&exchange, DeadlineFactory &&deadline, std::initializer_list formats) { + bool saw_fd = false; + bool saw_classic = false; + for (const bool fd : formats) { + if (fd ? saw_fd : saw_classic) { + continue; + } + if (fd) { + saw_fd = true; + } else { + saw_classic = true; + } + if (auto reply = exchange(fd, kHopCanMi, kHopCanInterfaceSi, 4, std::vector{}, true, true, false, + deadline())) { + return reply; + } + } + return std::nullopt; + } + + [[nodiscard]] inline HopCanConfiguration configuration_from_interface(const HopCanConfiguration &before, + const std::vector &interface) { + const std::array request_id{static_cast(before.request_id & 0xFFU), + static_cast((before.request_id >> 8U) & 0xFFU)}; + return parse_hop_can_configuration(request_id.data(), request_id.size(), interface.data(), interface.size()); + } + + inline void require_confirmed_mode(const HopCanConfiguration &before, const HopCanConfiguration &after, + HopCanInterfaceMode mode) { + if (after.request_id != before.request_id || after.interface_mode != mode || after.brs != before.brs || + after.nominal_bitrate != before.nominal_bitrate || after.data_bitrate != before.data_bitrate) { + throw ProtocolError("Target configuration/BRS/bitrates not confirmed; do not repeat write"); + } + } + + template + [[nodiscard]] HopCanModeSwitchResult set_hop_can_interface_mode(bool current_fd, HopCanInterfaceMode mode, + bool save_to_flash, Exchange &&exchange, + DeadlineFactory &&deadline) { + if (!is_hop_can_interface_mode(mode)) { + throw ValidationError("CAN interface mode must be classic CAN 2.0 (1) or CAN FD (2)"); + } + HopCanModeSwitchResult result; + result.before = read_hop_can_configuration(current_fd, exchange, deadline); + result.after = result.before; + result.active_wire_is_fd = current_fd; + if (mode == HopCanInterfaceMode::kCan20 && result.before.brs) { + throw ValidationError("Disable BRS separately before selecting classic CAN"); + } + const bool target_fd = mode == HopCanInterfaceMode::kCanFd; + if (result.before.interface_mode != mode) { + result.write_sent = true; + const std::vector payload{static_cast(mode)}; + // One write. A missing or wrong-format reply is not a reason to send it again. + auto ack = exchange(current_fd, kHopCanMi, kHopCanInterfaceSi, 1, payload, false, true, true, deadline()); + std::optional verified; + if (ack) { + verified = probe_hop_can_interface(exchange, deadline, {ack->is_fd, !ack->is_fd}); + } else { + verified = probe_hop_can_interface(exchange, deadline, {target_fd, current_fd}); + } + if (!verified) { + throw TimeoutError("Device mode could not be verified; no automatic write retry"); + } + result.active_wire_is_fd = verified->is_fd; + result.after = configuration_from_interface(result.before, verified->payload); + require_confirmed_mode(result.before, result.after, mode); + } + if (save_to_flash) { + auto saved = exchange(result.active_wire_is_fd, kHopCanMi, kHopCanSaveSi, 1, std::vector{0x01}, + false, true, true, deadline()); + if (!saved || saved->payload.size() != 1) { + throw ProtocolError("HOP flash save completion was not confirmed; save was not retried"); + } + result.saved_to_flash = true; + result.active_wire_is_fd = saved->is_fd; + auto refreshed = + probe_hop_can_interface(exchange, deadline, {result.active_wire_is_fd, !result.active_wire_is_fd}); + if (!refreshed) { + throw TimeoutError("Flash save was sent once but the CAN configuration was not reread"); + } + result.active_wire_is_fd = refreshed->is_fd; + result.after = configuration_from_interface(result.before, refreshed->payload); + require_confirmed_mode(result.before, result.after, mode); + } + result.active_format_changed = result.active_wire_is_fd != current_fd; + return result; + } + + template [[nodiscard]] auto hop_can_exchange(Runtime &runtime, uint32_t request_id) { + return [&runtime, request_id](bool send_is_fd, uint8_t mi, uint8_t si, uint8_t edl, + const std::vector &payload, bool rts, bool accept_either_format, + bool configuration_write, runtime::Deadline deadline) { + return exchange_hop_frame(runtime, request_id, send_is_fd, mi, si, edl, payload, rts, accept_either_format, + configuration_write, deadline); + }; + } + + [[nodiscard]] inline HopCanConfiguration read_hop_can_configuration_blocking(runtime::DeviceRuntime &runtime, + uint32_t request_id, bool wire_is_fd, + std::chrono::milliseconds timeout) { + if (timeout.count() <= 0) { + throw ValidationError("CAN configuration timeout must be positive"); + } + auto operation = runtime.operation(runtime::deadline_after(hop_can_operation_budget(timeout))); + return read_hop_can_configuration(wire_is_fd, hop_can_exchange(runtime, request_id), + [timeout] { return runtime::deadline_after(timeout); }); + } + + [[nodiscard]] inline HopCanModeSwitchResult + set_hop_can_interface_mode_blocking(runtime::DeviceRuntime &runtime, uint32_t request_id, bool wire_is_fd, + HopCanInterfaceMode mode, bool save_to_flash, + std::chrono::milliseconds timeout) { + if (timeout.count() <= 0) { + throw ValidationError("CAN configuration timeout must be positive"); + } + if (!is_hop_can_interface_mode(mode)) { + throw ValidationError("CAN interface mode must be classic CAN 2.0 (1) or CAN FD (2)"); + } + auto operation = runtime.operation(runtime::deadline_after(hop_can_operation_budget(timeout))); + return set_hop_can_interface_mode(wire_is_fd, mode, save_to_flash, hop_can_exchange(runtime, request_id), + [timeout] { return runtime::deadline_after(timeout); }); + } +} // namespace linkerbot::hand::detail diff --git a/src/hand/l6/hop_l6.cpp b/src/hand/l6/hop_l6.cpp index 8cc3f68a..b28cde53 100644 --- a/src/hand/l6/hop_l6.cpp +++ b/src/hand/l6/hop_l6.cpp @@ -1,6 +1,8 @@ #include #include #include + +#include "../detail/hop_can_mode.hpp" #include #include #ifdef __linux__ @@ -334,6 +336,18 @@ namespace linkerbot::hand::l6 { (void)owner_->execute(hop::transaction(owner_->request_id_, 0x35, 0x1e, 1, {1}, false, "configuration"), op.deadline()); } + HopCanConfiguration HopL6::ConfigManager::get_can_configuration(std::chrono::milliseconds timeout) { + const auto op = owner_->operation(detail::hop_can_operation_budget(timeout)); + (void)op; + return detail::read_hop_can_configuration_blocking(*owner_->runtime_, owner_->request_id_, true, timeout); + } + HopCanModeSwitchResult HopL6::ConfigManager::set_can_interface_mode(HopCanInterfaceMode mode, bool save_to_flash, + std::chrono::milliseconds timeout) { + const auto op = owner_->operation(detail::hop_can_operation_budget(timeout)); + (void)op; + return detail::set_hop_can_interface_mode_blocking(*owner_->runtime_, owner_->request_id_, true, mode, + save_to_flash, timeout); + } ForceSample HopL6::ForceSensorManager::get_blocking(std::chrono::milliseconds timeout) { auto op = owner_->operation(timeout); // selection + metadata + all banks are one exclusive operation o30::SensorData round; diff --git a/src/hand/o30/config.cpp b/src/hand/o30/config.cpp index e805edfb..942a008c 100644 --- a/src/hand/o30/config.cpp +++ b/src/hand/o30/config.cpp @@ -1,6 +1,8 @@ #include "linkerbot/hand/o30/config.hpp" #include +#include "../detail/hop_can_mode.hpp" + #include #include @@ -100,6 +102,20 @@ namespace linkerbot::hand::o30 { write_confirm(kSiSaveFlash, confirm, timeout_ms); } + HopCanConfiguration ConfigManager::get_can_configuration(std::chrono::milliseconds timeout) { + const auto op = client_->operation(detail::hop_can_operation_budget(timeout)); + (void)op; + return detail::read_hop_can_configuration_blocking(*client_->runtime(), client_->request_id(), true, timeout); + } + + HopCanModeSwitchResult ConfigManager::set_can_interface_mode(HopCanInterfaceMode mode, bool save_to_flash, + std::chrono::milliseconds timeout) { + const auto op = client_->operation(detail::hop_can_operation_budget(timeout)); + (void)op; + return detail::set_hop_can_interface_mode_blocking(*client_->runtime(), client_->request_id(), true, mode, + save_to_flash, timeout); + } + void ConfigManager::write_field(uint8_t si, const std::vector &payload, std::chrono::milliseconds timeout_ms) { auto operation = client_->operation(timeout_ms); diff --git a/src/hand/o6/hop_o6.cpp b/src/hand/o6/hop_o6.cpp new file mode 100644 index 00000000..2b742d5b --- /dev/null +++ b/src/hand/o6/hop_o6.cpp @@ -0,0 +1,733 @@ +#include +#include +#include + +#include "../detail/hop_can_mode.hpp" +#include +#include +#ifdef __linux__ +#include +#endif + +namespace linkerbot::hand::o6 { + namespace { + std::unique_ptr make_transport(std::string_view name, bool can_fd) { +#ifdef __linux__ + return std::make_unique(name, can_fd); +#else + (void)name; + (void)can_fd; + throw TransportError("HopO6 requires an explicit CAN Transport on this platform"); +#endif + } + + DeviceCapabilities profile(Side side, uint32_t id, bool can_fd) { + if (side != Side::kLeft && side != Side::kRight) { + throw ValidationError("invalid O6 side"); + } + HandDeviceConfig config; + config.model = Model::kO6; + config.side = side == Side::kLeft ? HandSide::kLeft : HandSide::kRight; + config.o6_protocol = can_fd ? O6Protocol::kHopV004 : O6Protocol::kHopV004Can; + config.address = id; + return declared_capabilities(config); + } + + // UTF-8 fixed-width strings, terminated by NUL. Reject malformed encodings, + // including overlong sequences, surrogate codepoints and values above U+10FFFF. + std::string text(const std::vector &data, size_t offset, size_t size) { + if (offset + size > data.size()) { + throw ProtocolError("short O6 HOP text field"); + } + std::string result; + for (size_t i = offset; i < offset + size && data[i];) { + uint32_t cp = data[i]; + const size_t width = cp < 0x80 ? 1 + : cp >= 0xc2 && cp <= 0xdf ? 2 + : cp >= 0xe0 && cp <= 0xef ? 3 + : cp >= 0xf0 && cp <= 0xf4 ? 4 + : 0; + if (!width || i + width > offset + size) { + throw ProtocolError("invalid HOP UTF-8 text"); + } + cp &= width == 1 ? 0x7f : (1U << (7 - width)) - 1; + for (size_t j = 1; j < width; ++j) { + if ((data[i + j] & 0xc0) != 0x80) { + throw ProtocolError("invalid HOP UTF-8 continuation"); + } + cp = (cp << 6) | (data[i + j] & 0x3f); + } + if ((width == 2 && cp < 0x80) || (width == 3 && cp < 0x800) || (width == 4 && cp < 0x10000) || + cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) { + throw ProtocolError("invalid HOP UTF-8 codepoint"); + } + result.append(reinterpret_cast(data.data() + i), width); + i += width; + } + const auto first = result.find_first_not_of(" \t\r\n"); + return first == std::string::npos ? std::string{} + : result.substr(first, result.find_last_not_of(" \t\r\n") - first + 1); + } + + template + std::optional vector_snapshot(const std::shared_ptr &core, const char *domain) { + const auto value = core->snapshot_as(domain); + if (!value) { + return {}; + } + T result; + static_cast(result) = *value; + return result; + } + + HandEvent typed_vector_event(TelemetrySemantic semantic, const RawVectorSample &sample) { + switch (semantic) { + case TelemetrySemantic::kConfiguredSpeeds: { + ConfiguredSpeedSample typed; + static_cast(typed) = sample; + return {semantic, typed}; + } + case TelemetrySemantic::kConfiguredAccelerations: { + ConfiguredAccelerationSample typed; + static_cast(typed) = sample; + return {semantic, typed}; + } + case TelemetrySemantic::kCurrentLimits: { + CurrentLimitSample typed; + static_cast(typed) = sample; + return {semantic, typed}; + } + case TelemetrySemantic::kCurrents: { + CurrentSample typed; + static_cast(typed) = sample; + return {semantic, typed}; + } + case TelemetrySemantic::kTemperatures: { + TemperatureSample typed; + static_cast(typed) = sample; + return {semantic, typed}; + } + case TelemetrySemantic::kStallDetectionTimes: { + StallDetectionTimeSample typed; + static_cast(typed) = sample; + return {semantic, typed}; + } + case TelemetrySemantic::kStallThresholds: { + StallThresholdSample typed; + static_cast(typed) = sample; + return {semantic, typed}; + } + case TelemetrySemantic::kStallHoldCurrents: { + StallHoldCurrentSample typed; + static_cast(typed) = sample; + return {semantic, typed}; + } + default: + throw UnsupportedOperationError("unsupported O6 HOP vector event semantic"); + } + } + + AngleSample angles(const std::vector &bytes, SampleMeta meta) { + AngleSample result; + result.meta = std::move(meta); + for (const auto raw : hop::project_bytes(bytes)) { + result.raw.push_back(raw); + result.percent.push_back(raw * 100.0 / 255.0); + result.physical_rad.emplace_back(); + } + return result; + } + } // namespace + + HopO6::HopO6(Side side, std::string_view name, uint32_t id, bool can_fd) + : HopO6(side, make_transport(name, can_fd), id, can_fd) {} + + HopO6::HopO6(Side side, std::unique_ptr transport, uint32_t id, bool can_fd) + : HopO6(side, transport::Session::own(std::move(transport)), id, can_fd) { + owns_session_ = true; + } + + HopO6::HopO6(Side side, std::shared_ptr session, uint32_t id, bool can_fd) + : session_(std::move(session)), runtime_(runtime::DeviceRuntime::acquire( + session_, "o6/hop/" + std::to_string(id), {{hop::response_id(id), false}})), + request_id_(id), can_fd_(can_fd), capabilities_(profile(side, id, can_fd)), angle(*this), + speed(*this, hop::kMiSpeed, true, TelemetrySemantic::kConfiguredSpeeds, "speeds", "speed_targets"), + acceleration(*this, hop::kMiAcceleration, true, TelemetrySemantic::kConfiguredAccelerations, "accelerations", + "acceleration_targets"), + current_limit(*this, hop::kMiCurrent, true, TelemetrySemantic::kCurrentLimits, "current_limits", + "current_limits"), + current(*this, hop::kMiCurrent, false, TelemetrySemantic::kCurrents, "currents"), + temperature(*this, hop::kMiTemperature, false, TelemetrySemantic::kTemperatures, "temperatures"), + stall_detection_time(*this, hop::kMiStallTime, true, TelemetrySemantic::kStallDetectionTimes, + "stall_detection_times", "stall_configuration"), + stall_threshold(*this, hop::kMiStallThreshold, true, TelemetrySemantic::kStallThresholds, "stall_thresholds", + "stall_configuration"), + stall_hold_current(*this, hop::kMiStallHoldCurrent, true, TelemetrySemantic::kStallHoldCurrents, + "stall_hold_currents", "stall_configuration"), + fault(*this), force_sensor(*this), version(*this), config(*this) { + for (const auto *channel : + {"angles", "speeds", "accelerations", "current_limits", "currents", "temperatures", + "stall_detection_times", "stall_thresholds", "stall_hold_currents", "faults", "force", "version"}) { + runtime_->register_channel(channel); + } + for (const auto *family : {"angle_targets", "speed_targets", "acceleration_targets", "current_limits", + "stall_configuration", "configuration"}) { + runtime_->register_command_family(family); + } + } + + HopO6::~HopO6() { + try { + stop(); + } catch (...) { + try { + runtime_->quiesce_for_destruction(); + calls_.drain(); + // Destruction is nonthrowing; explicit close/stop remains the error-reporting path. + // NOLINTNEXTLINE(bugprone-empty-catch) + } catch (...) { + } + } + } + + runtime::DeviceRuntime::Operation HopO6::operation(std::chrono::milliseconds timeout) { + auto call = calls_.hold(); + auto result = runtime_->operation(runtime::deadline_after(timeout)); + result.retain_call(std::move(call)); + return result; + } + + runtime::Sample HopO6::execute(runtime::TransactionPlan plan, runtime::Deadline deadline) { + return runtime_->execute(std::move(plan), deadline); + } + + std::vector HopO6::read_range(uint8_t mi, uint8_t si, size_t length, bool rts, + runtime::Deadline deadline) { + if (!length || size_t(si) + length > 256) { + throw ValidationError("invalid O6 HOP register range"); + } + const auto max_chunk = hop::max_payload_bytes(can_fd_); + std::vector result; + while (result.size() < length) { + const auto count = static_cast(std::min(max_chunk, length - result.size())); + auto sample = execute(hop::transaction(request_id_, mi, static_cast(si + result.size()), count, {}, + rts, {}, can_fd_), + deadline); + const auto &part = std::any_cast &>(sample.value); + result.insert(result.end(), part.begin(), part.end()); + } + return result; + } + + SampleMeta HopO6::metadata(const runtime::Sample &sample, const char *domain, bool configured) const { + SampleMeta result; + const auto previous = runtime_->snapshot(domain); + result.sequence = previous ? previous->sequence + 1 : 1; + result.collected_at = sample.received_at; + result.valid = sample.valid; + result.stale = !sample.valid; + result.connection_generation = sample.device_generation; + result.origin = configured ? TelemetryValueOrigin::kDeviceConfigured : TelemetryValueOrigin::kDeviceMeasured; + result.delivery = sample.origin == hand::protocol::Origin::command_feedback + ? TelemetryDelivery::kCommandResponse + : TelemetryDelivery::kQueryResponse; + return result; + } + + void HopO6::publish(std::string domain, HandEvent event, runtime::Sample provenance) { + std::visit([&](const auto &value) { runtime_->publish(domain, value, provenance); }, event.sample); + const std::lock_guard lock(event_mutex_); + if (events_) { + events_->push(event); + } + } + + AngleSample HopO6::AngleManager::get_blocking(std::chrono::milliseconds timeout) { + auto op = owner_->operation(timeout); + auto bytes = owner_->read_range(hop::kMiPosition, 5, 10, false, op.deadline()); + auto provenance = owner_->runtime_->response_provenance(); + auto result = angles(bytes, owner_->metadata(provenance, "angles")); + owner_->publish("angles", {TelemetrySemantic::kAngles, result}, provenance); + return result; + } + + void HopO6::AngleManager::set_angles(const std::array &values, std::chrono::milliseconds timeout) { + auto op = owner_->operation(timeout); + const std::vector bytes(values.begin(), values.end()); + auto sample = owner_->execute( + hop::write_joints(owner_->request_id_, hop::kMiPosition, bytes, false, "angle_targets", owner_->can_fd_), + op.deadline()); + if (sample.valid) { + auto result = angles(std::any_cast>(sample.value), owner_->metadata(sample, "angles")); + owner_->publish("angles", {TelemetrySemantic::kAngles, result}, sample); + } + } + + void HopO6::AngleManager::set_angles_percent(const std::array &values, + std::chrono::milliseconds timeout) { + std::array raw{}; + for (size_t i = 0; i < raw.size(); ++i) { + if (!std::isfinite(values[i]) || values[i] < 0 || values[i] > 100) { + throw ValidationError("O6 HOP percent must be 0..100"); + } + raw[i] = static_cast(std::lround(values[i] * 255.0 / 100.0)); + } + set_angles(raw, timeout); + } + + std::optional HopO6::AngleManager::get_snapshot() const { + return owner_->runtime_->snapshot_as("angles"); + } + + RawVectorSample HopO6::VectorManager::get_blocking(std::chrono::milliseconds timeout) { + auto op = owner_->operation(timeout); + const auto raw = hop::project_bytes(owner_->read_range(mi_, 5, 10, configured_, op.deadline())); + const auto provenance = owner_->runtime_->response_provenance(); + RawVectorSample result{{raw.begin(), raw.end()}, owner_->metadata(provenance, domain_, configured_)}; + owner_->runtime_->publish(domain_, result, provenance); + const auto event = typed_vector_event(semantic_, result); + const std::lock_guard lock(owner_->event_mutex_); + if (owner_->events_) { + owner_->events_->push(event); + } + return result; + } + + void HopO6::VectorManager::set_values(const std::array &values, std::chrono::milliseconds timeout) { + if (!family_) { + throw UnsupportedOperationError("this O6 HOP channel is read-only"); + } + auto op = owner_->operation(timeout); + auto sample = owner_->execute( + hop::write_joints(owner_->request_id_, mi_, {values.begin(), values.end()}, true, family_, owner_->can_fd_), + op.deadline()); + if (sample.valid) { + const auto raw = hop::project_bytes(std::any_cast>(sample.value)); + RawVectorSample result{{raw.begin(), raw.end()}, owner_->metadata(sample, domain_, true)}; + owner_->runtime_->publish(domain_, result, sample); + const auto event = typed_vector_event(semantic_, result); + const std::lock_guard lock(owner_->event_mutex_); + if (owner_->events_) { + owner_->events_->push(event); + } + } + } + + std::optional HopO6::VectorManager::get_snapshot() const { + return owner_->runtime_->snapshot_as(domain_); + } + + FaultSample HopO6::FaultManager::get_blocking(std::chrono::milliseconds timeout) { + auto op = owner_->operation(timeout); + const auto raw = hop::project_bytes(owner_->read_range(hop::kMiFault, 5, 10, false, op.deadline())); + auto provenance = owner_->runtime_->response_provenance(); + FaultSample result; + result.raw.assign(raw.begin(), raw.end()); + for (auto value : raw) { + result.statuses.push_back(decode_fault_status(value, hop::kFaultMask)); + } + result.meta = owner_->metadata(provenance, "faults"); + owner_->publish("faults", {TelemetrySemantic::kFaults, result}, provenance); + return result; + } + + std::optional HopO6::FaultManager::get_snapshot() const { + return owner_->runtime_->snapshot_as("faults"); + } + + DeviceIdentity HopO6::VersionManager::get_blocking(std::chrono::milliseconds timeout) { + auto op = owner_->operation(timeout); + const auto blob = owner_->read_range(hop::kMiProductInfo, 0, 249, false, op.deadline()); + const auto model = text(blob, 0, 16), uid = text(blob, 0x39, 32), name = text(blob, 0x59, 8); + const auto upper_model = identity_detail::upper(model); + if (upper_model != "O6" && upper_model != "LHO6" && upper_model.rfind("LHO6-", 0) != 0 && + upper_model.rfind("O6-", 0) != 0) { + throw IdentityMismatchError("HOP product model is not O6: " + model); + } + const auto protocol_version = text(blob, 0x61, 8), app = text(blob, 0xa1, 8); + if (identity_detail::upper(name) != "HOP" || protocol_version.empty() || uid.empty() || app.empty()) { + throw IdentityProtocolError("O6 HOP identity requires protocol name/version, device UID and app version"); + } + const auto reported = identity_detail::parse_side(text(blob, 0xf1, 8)); + const auto expected = + owner_->capabilities_.side == HandSide::kLeft ? IdentitySide::kLeft : IdentitySide::kRight; + if (!reported) { + throw IdentityProtocolError("O6 HOP identity does not report a valid side"); + } + if (*reported != expected) { + throw IdentityMismatchError("O6 HOP reported side does not match configuration"); + } + DeviceIdentity result; + result.model = Model::kO6; + result.side = owner_->capabilities_.side; + result.address = owner_->request_id_; + result.product_code = model; + const auto parts = identity_detail::split_product(uid); + if (parts.size() >= 4 && + (identity_detail::upper(parts[0]) == "LHO6" || identity_detail::upper(parts[0]) == "O6")) { + const auto side = identity_detail::parse_side(parts[3]); + if (side && side != reported) { + throw IdentityMismatchError("O6 UID and reported side disagree"); + } + result.product_code = uid; + result.serial_number = parts[2]; + } + result.device_uid = uid; + result.firmware_version = app; + result.protocol_name = name; + result.protocol_version = protocol_version; + result.hardware_version = text(blob, 0x89, 16); + result.mechanical_version = text(blob, 0xa9, 8); + const auto provenance = owner_->runtime_->response_provenance(); + result.timestamp = provenance.received_at; + owner_->runtime_->publish("version", result, provenance); + return result; + } + + std::optional HopO6::VersionManager::get_snapshot() const { + return owner_->runtime_->snapshot_as("version"); + } + + void HopO6::ConfigManager::save(std::chrono::milliseconds timeout) { + auto op = owner_->operation(timeout); + (void)owner_->execute(hop::transaction(owner_->request_id_, hop::kMiConfig, 0x1e, 1, {1}, false, + "configuration", owner_->can_fd_), + op.deadline()); + } + + HopCanConfiguration HopO6::ConfigManager::get_can_configuration(std::chrono::milliseconds timeout) { + const auto op = owner_->operation(detail::hop_can_operation_budget(timeout)); + (void)op; + return detail::read_hop_can_configuration_blocking(*owner_->runtime_, owner_->request_id_, owner_->can_fd_, + timeout); + } + + HopCanModeSwitchResult HopO6::ConfigManager::set_can_interface_mode(HopCanInterfaceMode mode, bool save_to_flash, + std::chrono::milliseconds timeout) { + const auto op = owner_->operation(detail::hop_can_operation_budget(timeout)); + (void)op; + return detail::set_hop_can_interface_mode_blocking(*owner_->runtime_, owner_->request_id_, owner_->can_fd_, + mode, save_to_flash, timeout); + } + + ForceSample HopO6::ForceSensorManager::get_blocking(std::chrono::milliseconds timeout) { + auto op = owner_->operation(timeout); // selection + metadata + all banks are one exclusive operation + o30::SensorData round; + for (uint8_t index = 1; index <= 5; ++index) { + const auto ack = owner_->execute(hop::transaction(owner_->request_id_, hop::kMiSensorCommand, 0x6e, 1, + {index}, false, "sensor_selection", owner_->can_fd_), + op.deadline()); + if (std::any_cast>(ack.value) != std::vector{index}) { + throw ProtocolError("O6 HOP sensor selection was not acknowledged"); + } + const auto blob = owner_->read_range(hop::kMiSensorCommand, 0, 115, false, op.deadline()); + o30::SensorReading reading; + auto &info = reading.info; + info.type = text(blob, 0, 32); + info.unit = text(blob, 32, 8); + info.data_range = blob[40]; + info.maximum_rows = blob[41]; + info.maximum_columns = blob[42]; + const auto descriptor_length = blob[43]; + if (descriptor_length > 64) { + throw ProtocolError("O6 sensor descriptor exceeds its register range"); + } + info.descriptor = text(blob, 44, descriptor_length); + if (info.descriptor.size() != descriptor_length) { + throw ProtocolError("O6 sensor descriptor length does not match its metadata"); + } + info.total_length = hand::protocol::hop::read_u16_le(blob.data() + 108); + info.selected = blob[110]; + info.rows = blob[111]; + info.columns = blob[112]; + info.flags = static_cast(blob[113] | uint16_t(blob[114]) << 8); + if (info.selected != index || info.total_length > 765 || blob[113] > 1 || blob[114] > 1 || + info.rows > info.maximum_rows || info.columns > info.maximum_columns) { + throw ProtocolError("invalid O6 HOP sensor metadata"); + } + if (blob[113]) { + throw ProtocolError("O6 HOP sensor is in validity-mask mode, not measurement mode"); + } + if ((info.type == "NO_SENSOR" || info.type.empty()) && info.total_length) { + throw ProtocolError("missing O6 HOP sensor reports nonempty data"); + } + if (!info.total_length && !info.descriptor.empty()) { + throw ProtocolError("empty O6 sensor has a descriptor"); + } + for (size_t bank = 0; reading.payload.size() < info.total_length; ++bank) { + const auto count = std::min(255, info.total_length - reading.payload.size()); + const auto data = owner_->read_range(static_cast(hop::kMiSensorData1 + bank), 0, count, false, + op.deadline()); + reading.payload.insert(reading.payload.end(), data.begin(), data.end()); + } + // Check that selection did not change while bank reads were in flight. + if (owner_->read_range(hop::kMiSensorCommand, 0x6e, 1, false, op.deadline())[0] != index) { + throw ProtocolError("O6 sensor identity changed during read"); + } + reading.timestamp = owner_->runtime_->response_provenance().received_at; + info.timestamp = reading.timestamp; + if (!reading.payload.empty()) { + (void)hand::protocol::hop::decode_tactile_fields(reading, true); + } + if (index == 1) { + round.info = info; + } + round.timestamp = reading.timestamp; + round.payload.insert(round.payload.end(), reading.payload.begin(), reading.payload.end()); + round.sensors.push_back(std::move(reading)); + } + if (round.payload.empty()) { + throw UnsupportedOperationError("O6 HOP reports no available fingertip sensors"); + } + const auto provenance = owner_->runtime_->response_provenance(); + auto result = hand::protocol::hop::descriptor_force_sample(round, owner_->metadata(provenance, "force"), true); + owner_->publish("force", {TelemetrySemantic::kForce, result}, provenance); + return result; + } + + std::optional HopO6::ForceSensorManager::get_snapshot() const { + return owner_->runtime_->snapshot_as("force"); + } + + HandSnapshot HopO6::get_snapshot() const { + HandSnapshot result; + result.model = Model::kO6; + result.side = capabilities_.side; + result.captured_at = runtime::Clock::now(); + result.connection_generation = runtime_->runtime_health().device_generation; + result.angles = angle.get_snapshot(); + result.configured_speeds = vector_snapshot(runtime_, "speeds"); + result.configured_accelerations = vector_snapshot(runtime_, "accelerations"); + result.currents = vector_snapshot(runtime_, "currents"); + result.current_limits = vector_snapshot(runtime_, "current_limits"); + result.temperatures = vector_snapshot(runtime_, "temperatures"); + result.stall_detection_times = vector_snapshot(runtime_, "stall_detection_times"); + result.stall_thresholds = vector_snapshot(runtime_, "stall_thresholds"); + result.stall_hold_currents = vector_snapshot(runtime_, "stall_hold_currents"); + result.faults = fault.get_snapshot(); + result.force = force_sensor.get_snapshot(); + result.device_info = version.get_snapshot(); + const auto fresh = [&](auto &sample, TelemetrySemantic semantic) { + if (!sample) { + return; + } + auto &meta = sample->meta; + const auto *channel = capabilities_.telemetry_channel(semantic); + if (meta.collected_at) { + meta.age = result.captured_at - *meta.collected_at; + } + meta.stale = !meta.valid || (meta.age && channel && channel->freshness_ms && + *meta.age > std::chrono::duration{*channel->freshness_ms}); + result.snapshot_sequence = std::max(result.snapshot_sequence, meta.sequence); + }; + fresh(result.angles, TelemetrySemantic::kAngles); + fresh(result.configured_speeds, TelemetrySemantic::kConfiguredSpeeds); + fresh(result.configured_accelerations, TelemetrySemantic::kConfiguredAccelerations); + fresh(result.currents, TelemetrySemantic::kCurrents); + fresh(result.current_limits, TelemetrySemantic::kCurrentLimits); + fresh(result.temperatures, TelemetrySemantic::kTemperatures); + fresh(result.stall_detection_times, TelemetrySemantic::kStallDetectionTimes); + fresh(result.stall_thresholds, TelemetrySemantic::kStallThresholds); + fresh(result.stall_hold_currents, TelemetrySemantic::kStallHoldCurrents); + fresh(result.faults, TelemetrySemantic::kFaults); + fresh(result.force, TelemetrySemantic::kForce); + for (size_t i = 0; i < 6; ++i) { + JointState state; + state.index = i; + state.name = kJointNames[i]; + if (result.angles) { + state.angle_raw = result.angles->raw[i]; + state.angle_percent = result.angles->percent[i]; + } + if (result.configured_speeds) { + state.configured_speed_raw = result.configured_speeds->raw[i]; + } + if (result.configured_accelerations) { + state.configured_acceleration_raw = result.configured_accelerations->raw[i]; + } + if (result.currents) { + state.current_raw = result.currents->raw[i]; + } + if (result.current_limits) { + state.current_limit_raw = result.current_limits->raw[i]; + } + if (result.temperatures) { + state.temperature_raw = result.temperatures->raw[i]; + } + if (result.stall_detection_times) { + state.stall_detection_time_raw = result.stall_detection_times->raw[i]; + } + if (result.stall_thresholds) { + state.stall_threshold_raw = result.stall_thresholds->raw[i]; + } + if (result.stall_hold_currents) { + state.stall_hold_current_raw = result.stall_hold_currents->raw[i]; + } + if (result.faults) { + state.fault_raw = result.faults->raw[i]; + } + result.joints.push_back(state); + } + return result; + } + + void HopO6::start_polling(const PollingPlan &plan) { + auto effective = plan; + if (effective.empty()) { + effective = {{TelemetrySemantic::kAngles, std::chrono::milliseconds{100}}}; + } + std::vector tasks; + for (const auto &channel : effective) { + if (!capabilities_.supports(channel.semantic) || channel.interval.count() <= 0) { + throw PollingPlanError("unsupported O6 HOP poll source or nonpositive interval"); + } + const auto semantic = channel.semantic; + const char *domain = nullptr; + switch (semantic) { + case TelemetrySemantic::kAngles: + domain = "angles"; + break; + case TelemetrySemantic::kConfiguredSpeeds: + domain = "speeds"; + break; + case TelemetrySemantic::kConfiguredAccelerations: + domain = "accelerations"; + break; + case TelemetrySemantic::kCurrents: + domain = "currents"; + break; + case TelemetrySemantic::kCurrentLimits: + domain = "current_limits"; + break; + case TelemetrySemantic::kTemperatures: + domain = "temperatures"; + break; + case TelemetrySemantic::kStallDetectionTimes: + domain = "stall_detection_times"; + break; + case TelemetrySemantic::kStallThresholds: + domain = "stall_thresholds"; + break; + case TelemetrySemantic::kStallHoldCurrents: + domain = "stall_hold_currents"; + break; + case TelemetrySemantic::kFaults: + domain = "faults"; + break; + case TelemetrySemantic::kForce: + domain = "force"; + break; + default: + throw PollingPlanError("unsupported O6 HOP poll source"); + } + if (std::any_of(tasks.begin(), tasks.end(), [domain](const auto &task) { return task.name == domain; })) { + throw PollingPlanError("duplicate O6 HOP polling source"); + } + runtime::DeviceRuntime::PollTask task; + task.name = domain; + task.period = channel.interval; + task.isolate_failure = true; + task.run = [this, semantic](runtime::CancellationToken) { + switch (semantic) { + case TelemetrySemantic::kAngles: + (void)angle.get_blocking(); + break; + case TelemetrySemantic::kConfiguredSpeeds: + (void)speed.get_blocking(); + break; + case TelemetrySemantic::kConfiguredAccelerations: + (void)acceleration.get_blocking(); + break; + case TelemetrySemantic::kCurrents: + (void)current.get_blocking(); + break; + case TelemetrySemantic::kCurrentLimits: + (void)current_limit.get_blocking(); + break; + case TelemetrySemantic::kTemperatures: + (void)temperature.get_blocking(); + break; + case TelemetrySemantic::kStallDetectionTimes: + (void)stall_detection_time.get_blocking(); + break; + case TelemetrySemantic::kStallThresholds: + (void)stall_threshold.get_blocking(); + break; + case TelemetrySemantic::kStallHoldCurrents: + (void)stall_hold_current.get_blocking(); + break; + case TelemetrySemantic::kFaults: + (void)fault.get_blocking(); + break; + case TelemetrySemantic::kForce: + (void)force_sensor.get_blocking(); + break; + default: + throw UnsupportedOperationError("unsupported O6 HOP polling source"); + } + }; + tasks.push_back(std::move(task)); + } + runtime_->start_polling(std::move(tasks)); + } + + void HopO6::stop_polling() { runtime_->stop_polling(); } + + std::shared_ptr> HopO6::stream_handle(size_t max_size) { + runtime_->assert_external_lifecycle(); + const std::lock_guard lifecycle(lifecycle_mutex_); + if (runtime_->runtime_health().state != runtime::DeviceState::ready) { + throw ClosedError("O6 HOP runtime is not ready"); + } + const std::lock_guard lock(event_mutex_); + if (events_ && !events_->closed()) { + throw LifecycleError("O6 HOP stream is already active"); + } + if (events_) { + retired_streams_.push_back(events_); + } + events_ = std::make_shared>(max_size); + return events_; + } + + void HopO6::stop_stream() { + const std::lock_guard lock(event_mutex_); + if (events_) { + events_->close(); + } + } + + void HopO6::stop() { + runtime_->assert_external_lifecycle(); + const std::lock_guard lifecycle(lifecycle_mutex_); + stop_stream(); + std::exception_ptr error; + try { + runtime_->close(); + } catch (...) { + error = std::current_exception(); + } + calls_.drain(); + try { + if (owns_session_) { + session_->close(); + } + } catch (...) { + if (!error) { + error = std::current_exception(); + } + } + if (error) { + std::rethrow_exception(error); + } + } + + void HopO6::recover() { + runtime_->assert_external_lifecycle(); + const std::lock_guard lifecycle(lifecycle_mutex_); + stop_stream(); + runtime_->cancel_all(); + calls_.drain(); + runtime_->recover(); + } +} // namespace linkerbot::hand::o6 diff --git a/src/hand/unified/backend.cpp b/src/hand/unified/backend.cpp index 503b859c..959c24f5 100644 --- a/src/hand/unified/backend.cpp +++ b/src/hand/unified/backend.cpp @@ -446,6 +446,35 @@ namespace linkerbot::hand::unified_detail { return handle; } + [[nodiscard]] HopCanConfiguration read_can_configuration(std::chrono::milliseconds timeout) override { + if (timeout.count() <= 0) { + throw ValidationError("CAN configuration timeout must be positive"); + } + const auto deadline = runtime::deadline_after(timeout); + auto lease = execution_gate_->acquire(false, deadline); + dispatch_guard_->wait(deadline, {}); + if constexpr (std::is_same_v || std::is_same_v || + std::is_same_v) { + return device_->config.get_can_configuration(timeout); + } + throw UnsupportedOperationError("CAN configuration is not supported by this device"); + } + + [[nodiscard]] HopCanModeSwitchResult set_can_interface_mode(HopCanInterfaceMode mode, bool save_to_flash, + std::chrono::milliseconds timeout) override { + if (timeout.count() <= 0) { + throw ValidationError("CAN configuration timeout must be positive"); + } + const auto deadline = runtime::deadline_after(timeout); + auto lease = execution_gate_->acquire(true, deadline); + dispatch_guard_->wait(deadline, {}); + if constexpr (std::is_same_v || std::is_same_v || + std::is_same_v) { + return device_->config.set_can_interface_mode(mode, save_to_flash, timeout); + } + throw UnsupportedOperationError("CAN configuration is not supported by this device"); + } + [[nodiscard]] HandSnapshot snapshot(Model model, HandSide side, const DeviceCapabilities &capabilities) const override { if (python_) { @@ -1044,6 +1073,12 @@ namespace linkerbot::hand::unified_detail { } case Model::kO6: { const auto side = concrete_side(config.side); + if (config.o6_protocol != O6Protocol::kClassic) { + const bool can_fd = config.o6_protocol == O6Protocol::kHopV004; + auto hand = std::make_unique( + side, session, config.address.value_or(o6::hop::kDefaultRequestId), can_fd); + return backend(std::move(hand), std::move(owned_session), config); + } auto hand = injected ? std::make_unique(side, session, config.interface_name, config.angle_mapping_path) : std::make_unique(side, config.interface_name, config.angle_mapping_path); diff --git a/src/hand/unified/common.cpp b/src/hand/unified/common.cpp index c5b56667..f3d88cff 100644 --- a/src/hand/unified/common.cpp +++ b/src/hand/unified/common.cpp @@ -93,8 +93,9 @@ namespace linkerbot::hand::unified_detail { } if (config.runtime_behavior == RuntimeBehavior::kPython && ((config.model == Model::kL6 && config.l6_protocol != L6Protocol::kClassic) || + (config.model == Model::kO6 && config.o6_protocol != O6Protocol::kClassic) || (config.model == Model::kO30 && config.o30_layout != O30Layout::kPythonV25))) { - throw ValidationError("Python runtime behavior requires Classic L6 or explicit O30 V25 layout"); + throw ValidationError("Python runtime behavior requires Classic L6, Classic O6 or explicit O30 V25 layout"); } if (config.recovery_timeout.count() <= 0 || config.recovery_quiet.count() < 0) { throw ValidationError("recovery_timeout must be positive and recovery_quiet nonnegative"); @@ -137,6 +138,14 @@ namespace linkerbot::hand::unified_detail { return; } + if (config.o6_protocol != O6Protocol::kClassic) { + (void)classic_address(config.side); // O6 HOP still requires an explicit side. + if (config.host_address || config.auto_start_periodic_reports || config.angle_mapping_path) { + throw ValidationError("O6 HOP does not support host_address, periodic reports or angle mappings"); + } + return; + } + if (is_classic_model(config.model)) { const auto expected = classic_address(config.side); if (config.address && *config.address != expected) { diff --git a/src/hand/unified/detail/backend.hpp b/src/hand/unified/detail/backend.hpp index b048bf33..dbf35e14 100644 --- a/src/hand/unified/detail/backend.hpp +++ b/src/hand/unified/detail/backend.hpp @@ -89,6 +89,13 @@ namespace linkerbot::hand::unified_detail { virtual void close() = 0; virtual void cancel_commands() = 0; virtual void assert_external_lifecycle() const = 0; + [[nodiscard]] virtual HopCanConfiguration read_can_configuration(std::chrono::milliseconds) { + throw UnsupportedOperationError("CAN configuration is not supported by this device"); + } + [[nodiscard]] virtual HopCanModeSwitchResult set_can_interface_mode(HopCanInterfaceMode, bool, + std::chrono::milliseconds) { + throw UnsupportedOperationError("CAN configuration is not supported by this device"); + } }; [[nodiscard]] std::unique_ptr diff --git a/src/hand/unified/detail/model_adapters.hpp b/src/hand/unified/detail/model_adapters.hpp index 0d138a86..4978abf8 100644 --- a/src/hand/unified/detail/model_adapters.hpp +++ b/src/hand/unified/detail/model_adapters.hpp @@ -11,6 +11,7 @@ #include #include #include +#include #include namespace linkerbot::hand::unified_detail { @@ -37,6 +38,12 @@ namespace linkerbot::hand::unified_detail { [[nodiscard]] CommandOutcome operate_device(o6::O6 &device, DeviceOperation operation, std::chrono::milliseconds timeout); + [[nodiscard]] CommandOutcome submit_command(o6::HopO6 &device, const CommandRequest &request); + [[nodiscard]] TelemetrySample read_telemetry(o6::HopO6 &device, TelemetrySemantic semantic, + std::chrono::milliseconds timeout); + [[nodiscard]] CommandOutcome operate_device(o6::HopO6 &device, DeviceOperation operation, + std::chrono::milliseconds timeout); + [[nodiscard]] CommandOutcome submit_command(l20lite::L20lite &device, const CommandRequest &request); [[nodiscard]] TelemetrySample read_telemetry(l20lite::L20lite &device, TelemetrySemantic semantic, std::chrono::milliseconds timeout); @@ -95,9 +102,11 @@ namespace linkerbot::hand::unified_detail { [[nodiscard]] TelemetrySample telemetry_sample(const HandSnapshot &snapshot, TelemetrySemantic semantic); [[nodiscard]] DeviceIdentity read_identity(l6::HopL6 &device, HandSide side, std::chrono::milliseconds timeout); + [[nodiscard]] DeviceIdentity read_identity(o6::HopO6 &device, HandSide side, std::chrono::milliseconds timeout); [[nodiscard]] HandSnapshot unified_snapshot(const HandSnapshot &source, Model model, HandSide side, const DeviceCapabilities &capabilities); void start_device_polling(l6::HopL6 &device, const PollingPlan &plan); + void start_device_polling(o6::HopO6 &device, const PollingPlan &plan); void start_device_polling(l6::L6 &device, const PollingPlan &plan); void start_device_polling(o6::O6 &device, const PollingPlan &plan); void start_device_polling(l20lite::L20lite &device, const PollingPlan &plan); diff --git a/src/hand/unified/device.cpp b/src/hand/unified/device.cpp index 65b577b7..d0b00634 100644 --- a/src/hand/unified/device.cpp +++ b/src/hand/unified/device.cpp @@ -1019,6 +1019,42 @@ namespace linkerbot::hand { DeviceIdentity HandDevice::get_device_info(std::chrono::milliseconds timeout) { return verify_identity(timeout); } + HopCanConfiguration HandDevice::get_can_configuration(std::chrono::milliseconds timeout) { + constexpr const char *operation = "get_can_configuration"; + const auto context = impl_->capture(operation); + if (!context.capabilities.operations.read_can_configuration) { + throw UnsupportedOperationError("configured hand model does not support get_can_configuration", + {operation, unified_detail::model_name(impl_->config_.model)}); + } + if (timeout.count() <= 0) { + throw ValidationError("get_can_configuration timeout must be positive", + {operation, unified_detail::model_name(impl_->config_.model)}); + } + auto lease = impl_->begin_io(context, operation); + return impl_->complete_io(context, operation, [&] { return context.backend->read_can_configuration(timeout); }); + } + + HopCanModeSwitchResult HandDevice::set_can_interface_mode(HopCanInterfaceMode mode, bool save_to_flash, + std::chrono::milliseconds timeout) { + constexpr const char *operation = "set_can_interface_mode"; + const auto context = impl_->capture(operation); + if (!context.capabilities.operations.write_can_configuration) { + throw UnsupportedOperationError("configured hand model does not support set_can_interface_mode", + {operation, unified_detail::model_name(impl_->config_.model)}); + } + if (timeout.count() <= 0) { + throw ValidationError("set_can_interface_mode timeout must be positive", + {operation, unified_detail::model_name(impl_->config_.model)}); + } + if (!is_hop_can_interface_mode(mode)) { + throw ValidationError("CAN interface mode must be classic CAN 2.0 (1) or CAN FD (2)", + {operation, unified_detail::model_name(impl_->config_.model)}); + } + auto lease = impl_->begin_io(context, operation); + return impl_->complete_io( + context, operation, [&] { return context.backend->set_can_interface_mode(mode, save_to_flash, timeout); }); + } + DeviceIdentity HandDevice::refresh_device_info(std::chrono::milliseconds timeout) { if (timeout.count() <= 0) { throw ValidationError("refresh_device_info timeout must be positive"); @@ -1593,6 +1629,7 @@ namespace linkerbot::hand { } if (!capabilities.supports(channel.semantic) || (impl_->config_.l6_protocol != L6Protocol::kHopV004 && + impl_->config_.o6_protocol == O6Protocol::kClassic && !unified_detail::polling_supported(impl_->config_.model, channel.semantic))) { throw UnsupportedOperationError("configured telemetry is not supported for unified polling", {"start_polling", unified_detail::model_name(impl_->config_.model)}); diff --git a/src/hand/unified/o6_hop_adapter.cpp b/src/hand/unified/o6_hop_adapter.cpp new file mode 100644 index 00000000..92c55dbd --- /dev/null +++ b/src/hand/unified/o6_hop_adapter.cpp @@ -0,0 +1,111 @@ +#include "detail/model_adapters.hpp" + +#include +#include + +namespace linkerbot::hand::unified_detail { + CommandOutcome submit_command(o6::HopO6 &device, const CommandRequest &request) { + if (request.raw_values.size() != 6) { + throw ValidationError("O6 HOP commands require six joint values"); + } + std::array raw{}; + std::copy(request.raw_values.begin(), request.raw_values.end(), raw.begin()); + switch (request.semantic) { + case CommandSemantic::kAngles: + device.angle.set_angles(raw, request.timeout); + break; + case CommandSemantic::kSpeeds: + device.speed.set_values(raw, request.timeout); + break; + case CommandSemantic::kAccelerations: + device.acceleration.set_values(raw, request.timeout); + break; + case CommandSemantic::kCurrentLimits: + device.current_limit.set_values(raw, request.timeout); + break; + case CommandSemantic::kStallDetectionTimes: + device.stall_detection_time.set_values(raw, request.timeout); + break; + case CommandSemantic::kStallThresholds: + device.stall_threshold.set_values(raw, request.timeout); + break; + case CommandSemantic::kStallHoldCurrents: + device.stall_hold_current.set_values(raw, request.timeout); + break; + default: + throw UnsupportedOperationError("unsupported O6 HOP command"); + } + return {2, request.ack_expectation != AckExpectation::kNone}; + } + + TelemetrySample read_telemetry(o6::HopO6 &device, TelemetrySemantic semantic, std::chrono::milliseconds timeout) { + switch (semantic) { + case TelemetrySemantic::kAngles: + return device.angle.get_blocking(timeout); + case TelemetrySemantic::kFaults: + return device.fault.get_blocking(timeout); + case TelemetrySemantic::kForce: + return device.force_sensor.get_blocking(timeout); + case TelemetrySemantic::kConfiguredSpeeds: { + ConfiguredSpeedSample sample; + static_cast(sample) = device.speed.get_blocking(timeout); + return sample; + } + case TelemetrySemantic::kConfiguredAccelerations: { + ConfiguredAccelerationSample sample; + static_cast(sample) = device.acceleration.get_blocking(timeout); + return sample; + } + case TelemetrySemantic::kCurrents: { + CurrentSample sample; + static_cast(sample) = device.current.get_blocking(timeout); + return sample; + } + case TelemetrySemantic::kCurrentLimits: { + CurrentLimitSample sample; + static_cast(sample) = device.current_limit.get_blocking(timeout); + return sample; + } + case TelemetrySemantic::kTemperatures: { + TemperatureSample sample; + static_cast(sample) = device.temperature.get_blocking(timeout); + return sample; + } + case TelemetrySemantic::kStallDetectionTimes: { + StallDetectionTimeSample sample; + static_cast(sample) = device.stall_detection_time.get_blocking(timeout); + return sample; + } + case TelemetrySemantic::kStallThresholds: { + StallThresholdSample sample; + static_cast(sample) = device.stall_threshold.get_blocking(timeout); + return sample; + } + case TelemetrySemantic::kStallHoldCurrents: { + StallHoldCurrentSample sample; + static_cast(sample) = device.stall_hold_current.get_blocking(timeout); + return sample; + } + default: + throw UnsupportedOperationError("unsupported O6 HOP telemetry"); + } + } + + CommandOutcome operate_device(o6::HopO6 &device, DeviceOperation operation, std::chrono::milliseconds timeout) { + if (operation != DeviceOperation::kSaveParameters) { + throw UnsupportedOperationError("unsupported O6 HOP operation"); + } + device.config.save(timeout); + return {1, true}; + } + + DeviceIdentity read_identity(o6::HopO6 &device, HandSide side, std::chrono::milliseconds timeout) { + auto result = device.version.get_blocking(timeout); + if (result.side != side) { + throw IdentityMismatchError("O6 HOP side does not match configuration"); + } + return result; + } + + void start_device_polling(o6::HopO6 &device, const PollingPlan &plan) { device.start_polling(plan); } +} // namespace linkerbot::hand::unified_detail diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5fa6dc50..d9fbfd63 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -205,7 +205,7 @@ add_library(linkerbot-protocol STATIC ../src/hand/l30/protocol.cpp) target_include_directories(linkerbot-protocol PUBLIC ../include) target_link_libraries(linkerbot-protocol PUBLIC linkerbot::comm-values) -add_executable(protocol-tests protocol/test_vectors.cpp protocol/test_l6_hop_vectors.cpp protocol/test_o6_vectors.cpp protocol/test_l20lite_vectors.cpp protocol/main.cpp) +add_executable(protocol-tests protocol/test_vectors.cpp protocol/test_l6_hop_vectors.cpp protocol/test_o6_hop_vectors.cpp protocol/test_o6_vectors.cpp protocol/test_l20lite_vectors.cpp protocol/main.cpp) target_link_libraries(protocol-tests PRIVATE linkerbot-protocol Catch2::Catch2) add_test(NAME protocol-vectors COMMAND protocol-tests "[protocol]") diff --git a/tests/hand/device/test_device.cpp b/tests/hand/device/test_device.cpp index 279387df..4c1722bb 100644 --- a/tests/hand/device/test_device.cpp +++ b/tests/hand/device/test_device.cpp @@ -948,7 +948,11 @@ TEST_CASE("HandDevice reads unified angle samples for every model", "[comm][devi DYNAMIC_SECTION("model " << static_cast(model)) { FakeTransport *transport = nullptr; std::shared_ptr hop; - HandDevice device(config_for(model), [&] { + auto config = config_for(model); + // Baseline reads during open include paced multi-frame transactions. + // Allow Windows scheduler headroom; this test checks sample contents. + config.transaction_timeout = std::chrono::seconds{1}; + HandDevice device(config, [&] { auto next = std::make_unique(); transport = next.get(); install_fake_device(model, transport, hop); diff --git a/tests/hand/l6/hop_fixture.hpp b/tests/hand/l6/hop_fixture.hpp index c01e6a47..f4d781c8 100644 --- a/tests/hand/l6/hop_fixture.hpp +++ b/tests/hand/l6/hop_fixture.hpp @@ -18,8 +18,13 @@ namespace l6_hop_test { std::array sensors; uint8_t selected = 1; size_t position_writes = 0; + bool can_fd = true; bool hold_tail = false, short_tail = false, no_reply = false, bad_length = false, bad_selected = false; bool invalid_mask = false; + bool switch_wire_immediately = false; + bool drop_mode_write_reply = false; + bool override_save_ack = false; + uint8_t save_ack = 0; std::optional held; static void put(std::array &target, size_t offset, const std::string &text, size_t width) { std::fill_n(target.begin() + offset, width, 0); @@ -46,6 +51,12 @@ namespace l6_hop_test { } } registers[12][10] = 0xb0; // bit7 known, bits4/5 reserved + auto &can_config = registers[0x35]; + can_config[0] = 0x01; + can_config[6] = 2; + can_config[7] = 0; + can_config[8] = 1; + can_config[9] = 2; sensors[0] = {"FnS_U16_1;Rsv_U16_1;Fn_U8_4", {42, 0, 99, 0, 1, 2, 3, 4}, 2, 2}; sensors[1] = {"FNS_U16_1;FTS_I16_1;FDS_F32_1", {9, 0, 254, 255, 0, 0, 52, 66}, 0, 0}; sensors[3] = {"xyz_F32_1", {0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64}, 0, 0}; @@ -54,13 +65,17 @@ namespace l6_hop_test { can::Message response(const can::Message &req, const std::vector &data) { can::Message result; result.id = req.id | 0x400; - result.is_fd = true; + result.is_fd = can_fd; const size_t count = data.size() + 3; - for (uint8_t n : {3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64}) { - if (n >= count) { - result.dlc = n; - break; + if (can_fd) { + for (uint8_t n : {3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64}) { + if (n >= count) { + result.dlc = n; + break; + } } + } else { + result.dlc = static_cast(count); } result.data[0] = req.data[0]; result.data[1] = req.data[1]; @@ -70,7 +85,7 @@ namespace l6_hop_test { } std::vector handle(const can::Message &req) { const std::lock_guard lock(mutex); - if (no_reply || !req.is_fd || req.is_extended || req.dlc < 3) { + if (no_reply || req.is_fd != can_fd || req.is_extended || req.dlc < 3) { return {}; } const uint8_t mi = req.data[0] & 0x7f, si = req.data[1], length = req.data[2]; @@ -116,8 +131,6 @@ namespace l6_hop_test { return {}; } data.assign(sensor.data.begin() + start, sensor.data.begin() + start + length); - } else if (mi == 0x35) { - data = {1}; } else { auto &object = mi == 0x20 ? positions : registers[mi]; if (write) { @@ -125,6 +138,15 @@ namespace l6_hop_test { } data.assign(object.begin() + si, object.begin() + si + length); } + if (write && mi == 0x35 && si == 0x06 && switch_wire_immediately && !data.empty()) { + can_fd = data[0] == 2; + } + if (write && mi == 0x35 && si == 0x1E && override_save_ack) { + data = {save_ack}; + } + if (drop_mode_write_reply && write && mi == 0x35 && si == 0x06) { + return {}; + } auto reply = response(req, data); if (write && mi == 0x20 && si == 20) { if (short_tail) { @@ -139,6 +161,8 @@ namespace l6_hop_test { return {reply}; } std::unique_ptr transport(uint32_t id = 1) { + registers[0x35][0] = static_cast(id & 0xffU); + registers[0x35][1] = static_cast((id >> 8) & 0xffU); auto result = std::make_unique(); result->on_request(id, [this](const auto &req) { return handle(req); }); return result; diff --git a/tests/hand/l6/test_hop_comm.cpp b/tests/hand/l6/test_hop_comm.cpp index b0749515..808f9917 100644 --- a/tests/hand/l6/test_hop_comm.cpp +++ b/tests/hand/l6/test_hop_comm.cpp @@ -2,8 +2,11 @@ #include "hop_fixture.hpp" #include #include +#include +#include #include #include +#include #include using namespace linkerbot::hand; using namespace std::chrono_literals; @@ -374,3 +377,181 @@ TEST_CASE("L6 HOP no sensors UTF8 and aggregate deadline behavior", "[comm][l6-h REQUIRE(fake->sent().size() < 5); } } + +namespace { + using linkerbot::can::FakeTransport; + using linkerbot::can::Message; + + [[nodiscard]] size_t count_prefix(const std::vector &sent, std::initializer_list prefix, + std::optional fd = std::nullopt) { + size_t count = 0; + for (const auto &message : sent) { + if (message.dlc < prefix.size()) { + continue; + } + bool match = true; + size_t index = 0; + for (const auto byte : prefix) { + if (message.data[index++] != byte) { + match = false; + break; + } + } + if (match && (!fd || message.is_fd == *fd)) { + ++count; + } + } + return count; + } + + [[nodiscard]] size_t count_config_writes(const std::vector &sent) { + size_t count = 0; + for (const auto &message : sent) { + if (message.dlc >= 4 && message.data[0] == 0x35) { + ++count; + } + } + return count; + } + + struct OpenedHop { + std::shared_ptr firmware; + FakeTransport *transport = nullptr; + std::unique_ptr device; + + explicit OpenedHop(uint32_t id) : firmware(std::make_shared()) { + device = std::make_unique(config(id), [this, id] { + auto next = firmware->transport(id); + transport = next.get(); + return next; + }); + device->open(); + transport->clear_sent(); + } + }; + + void install_classic_l6(FakeTransport *transport) { + const std::string code = "LHL6-1-123-L"; + transport->on_request(0x28, [code](const Message &request) { + if (request.data[0] == 0xC0) { + std::vector replies; + for (int chunk = 0; chunk < 4; ++chunk) { + Message reply{}; + reply.id = request.id; + reply.dlc = 8; + reply.data[0] = 0xC0; + reply.data[1] = static_cast(chunk); + for (size_t index = 0; index < 6; ++index) { + const auto offset = static_cast(chunk) * 6 + index; + reply.data[index + 2] = offset < code.size() ? static_cast(code[offset]) : uint8_t{0}; + } + replies.push_back(reply); + } + return replies; + } + if (request.data[0] == 0xC1 || request.data[0] == 0xC2 || request.data[0] == 0xC4) { + Message reply{}; + reply.id = request.id; + reply.dlc = request.data[0] == 0xC1 ? 5 : 4; + reply.data[0] = request.data[0]; + reply.data[1] = 1; + reply.data[2] = 2; + reply.data[3] = 3; + return std::vector{reply}; + } + Message reply{}; + reply.id = request.id; + reply.dlc = 7; + reply.data[0] = request.data[0]; + for (size_t index = 1; index < 7; ++index) { + reply.data[index] = request.dlc > index ? request.data[index] : uint8_t{64}; + } + return std::vector{reply}; + }); + } +} // namespace + +TEST_CASE("L6 HOP reads and switches CAN interface mode", "[comm][l6-hop]") { + REQUIRE(declared_capabilities(config(0x123)).operations.read_can_configuration); + REQUIRE(declared_capabilities(config(0x123)).operations.write_can_configuration); + REQUIRE_FALSE(declared_capabilities(Model::kL6, HandSide::kLeft).operations.read_can_configuration); + REQUIRE_FALSE(declared_capabilities(Model::kL6, HandSide::kLeft).operations.write_can_configuration); + + SECTION("CAN FD read") { + OpenedHop opened(0x123); + const auto configuration = opened.device->get_can_configuration(); + REQUIRE(configuration.request_id == 0x123); + REQUIRE(configuration.response_id() == 0x523); + REQUIRE(configuration.interface_mode == HopCanInterfaceMode::kCanFd); + REQUIRE_FALSE(configuration.brs); + REQUIRE(configuration.nominal_bitrate == 1000000); + REQUIRE(configuration.data_bitrate == 5000000); + const auto sent = opened.transport->sent(); + REQUIRE(count_prefix(sent, {0xB5, 0x00, 0x02}, true) == 1); + REQUIRE(count_prefix(sent, {0xB5, 0x06, 0x04}, true) == 1); + } + SECTION("mode write stays on CAN FD until reboot") { + OpenedHop opened(0x123); + const auto result = opened.device->set_can_interface_mode(HopCanInterfaceMode::kCan20, true); + REQUIRE(result.write_sent); + REQUIRE(result.saved_to_flash); + REQUIRE(result.active_wire_is_fd); + REQUIRE_FALSE(result.active_format_changed); + REQUIRE(result.after.interface_mode == HopCanInterfaceMode::kCan20); + REQUIRE_FALSE(result.after.brs); + const auto sent = opened.transport->sent(); + REQUIRE(count_prefix(sent, {0x35, 0x06, 0x01, 0x01}, true) == 1); + REQUIRE(count_prefix(sent, {0x35, 0x1E, 0x01, 0x01}, true) == 1); + } + SECTION("firmware switches to classic CAN immediately") { + OpenedHop opened(0x123); + opened.firmware->switch_wire_immediately = true; + const auto result = opened.device->set_can_interface_mode(HopCanInterfaceMode::kCan20, true); + REQUIRE(result.write_sent); + REQUIRE(result.saved_to_flash); + REQUIRE_FALSE(result.active_wire_is_fd); + REQUIRE(result.active_format_changed); + REQUIRE(result.after.interface_mode == HopCanInterfaceMode::kCan20); + const auto sent = opened.transport->sent(); + REQUIRE(count_prefix(sent, {0x35, 0x06, 0x01, 0x01}, true) == 1); + REQUIRE(count_prefix(sent, {0x35, 0x1E, 0x01, 0x01}, false) == 1); + } + SECTION("an already selected mode is not written again") { + OpenedHop opened(0x123); + const auto result = opened.device->set_can_interface_mode(HopCanInterfaceMode::kCanFd, true); + REQUIRE_FALSE(result.write_sent); + REQUIRE(result.saved_to_flash); + REQUIRE(result.active_wire_is_fd); + REQUIRE_FALSE(result.active_format_changed); + const auto sent = opened.transport->sent(); + REQUIRE(count_prefix(sent, {0x35, 0x06, 0x01}) == 0); + REQUIRE(count_prefix(sent, {0x35, 0x1E, 0x01, 0x01}, true) == 1); + } + SECTION("classic CAN is rejected while BRS is enabled") { + OpenedHop opened(0x123); + opened.firmware->registers[0x35][7] = 1; + REQUIRE_THROWS_AS(opened.device->set_can_interface_mode(HopCanInterfaceMode::kCan20, true), ValidationError); + REQUIRE(count_config_writes(opened.transport->sent()) == 0); + } +} + +TEST_CASE("classic L6 rejects CAN configuration before any frame", "[comm][l6-hop]") { + FakeTransport *transport = nullptr; + HandDeviceConfig cfg; + cfg.model = Model::kL6; + cfg.side = HandSide::kLeft; + cfg.interface_name = "fake0"; + HandDevice device(cfg, [&] { + auto next = std::make_unique(); + transport = next.get(); + install_classic_l6(transport); + return next; + }); + device.open(); + transport->clear_sent(); + REQUIRE_THROWS_AS(device.get_can_configuration(), UnsupportedOperationError); + REQUIRE(transport->sent().empty()); + REQUIRE_THROWS_AS(device.set_can_interface_mode(HopCanInterfaceMode::kCanFd, true), UnsupportedOperationError); + REQUIRE(transport->sent().empty()); + device.close(); +} diff --git a/tests/hand/o30/comm_helpers.hpp b/tests/hand/o30/comm_helpers.hpp index 6ed604a3..15319b85 100644 --- a/tests/hand/o30/comm_helpers.hpp +++ b/tests/hand/o30/comm_helpers.hpp @@ -54,25 +54,33 @@ namespace o30_comm { return {msg.data.begin(), msg.data.begin() + static_cast(end)}; } - inline Message hop_reply(uint32_t id, uint8_t mi, bool rts, uint8_t si, const std::vector &payload) { + inline Message hop_reply(uint32_t id, uint8_t mi, bool rts, uint8_t si, const std::vector &payload, + bool fd = true) { // Independent of the SDK request encoder: do not share wire-format bugs. if (payload.empty() || payload.size() > 61) { throw std::invalid_argument("fake HOP reply requires 1..61 bytes"); } Message msg{}; msg.id = id; - msg.is_fd = true; + msg.is_fd = fd; msg.data[0] = static_cast(mi | (rts ? 0x80 : 0)); msg.data[1] = si; msg.data[2] = static_cast(payload.size()); - constexpr std::array lengths{0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64}; - msg.dlc = *std::lower_bound(lengths.begin(), lengths.end(), 3 + payload.size()); + if (!fd) { + if (payload.size() + 3 > 8) { + throw std::invalid_argument("fake classic HOP reply exceeds 8 bytes"); + } + msg.dlc = static_cast(payload.size() + 3); + } else { + constexpr std::array lengths{0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64}; + msg.dlc = *std::lower_bound(lengths.begin(), lengths.end(), 3 + payload.size()); + } std::copy(payload.begin(), payload.end(), msg.data.begin() + 3); return msg; } - inline Message error_reply(uint32_t id, uint8_t si, uint8_t code) { - return hop_reply(id, protocol::kMiCommError, false, si, {code}); + inline Message error_reply(uint32_t id, uint8_t si, uint8_t code, bool fd = true) { + return hop_reply(id, protocol::kMiCommError, false, si, {code}, fd); } class HopEndpoint { @@ -80,6 +88,11 @@ namespace o30_comm { uint32_t request_id = protocol::kDefaultRequestId; std::map, std::vector> objects; std::vector writes; + bool enforce_wire_format = false; + bool reply_is_fd = true; + bool switch_wire_on_mode_write = false; + bool override_save_ack = false; + uint8_t save_ack = 0; [[nodiscard]] uint32_t response_id() const { return protocol::expected_response_id(request_id); } @@ -152,11 +165,15 @@ namespace o30_comm { if (req.is_extended || req.dlc < protocol::kHeaderBytes) { return {}; } + if (enforce_wire_format && req.is_fd != reply_is_fd) { + return {}; + } const auto mi = protocol::mi_of(req.data[0]); const auto rts = protocol::rts_of(req.data[0]); const auto si = req.data[1]; const auto edl = req.data[2]; const bool is_write = req.dlc > protocol::kHeaderBytes; + bool response_fd = enforce_wire_format ? reply_is_fd : true; if (is_write) { if (req.dlc < protocol::kHeaderBytes + edl) { return {}; @@ -170,7 +187,16 @@ namespace o30_comm { object.resize(end, 0); } std::copy(payload.begin(), payload.end(), object.begin() + si); - return {hop_reply(response_id(), mi, rts, si, payload)}; + if (mi == protocol::kMiConfig && si == 0x06 && switch_wire_on_mode_write && !payload.empty()) { + reply_is_fd = payload[0] == 2; + if (enforce_wire_format) { + response_fd = reply_is_fd; + } + } + if (mi == protocol::kMiConfig && si == 0x1E && override_save_ack) { + return {hop_reply(response_id(), mi, rts, si, {save_ack}, response_fd)}; + } + return {hop_reply(response_id(), mi, rts, si, payload, response_fd)}; } auto it = objects.find({mi, rts}); @@ -182,7 +208,7 @@ namespace o30_comm { } const auto requested_end = static_cast(si) + edl; if (requested_end > it->second.size()) { - return {error_reply(response_id(), si, protocol::kErrorSubIndexMissing)}; + return {error_reply(response_id(), si, protocol::kErrorSubIndexMissing, response_fd)}; } const std::vector slice(it->second.begin() + si, it->second.begin() + static_cast(requested_end)); @@ -192,7 +218,8 @@ namespace o30_comm { frames.push_back(hop_reply(response_id(), mi, rts, static_cast(static_cast(si) + offset), {slice.begin() + static_cast(offset), - slice.begin() + static_cast(offset + n)})); + slice.begin() + static_cast(offset + n)}, + response_fd)); } return frames; } diff --git a/tests/hand/o30/test_o30_comm.cpp b/tests/hand/o30/test_o30_comm.cpp index a0dcc020..16bf8154 100644 --- a/tests/hand/o30/test_o30_comm.cpp +++ b/tests/hand/o30/test_o30_comm.cpp @@ -5,8 +5,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -16,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -250,3 +253,133 @@ TEST_CASE("comm: stop closes the client used by managers", "[comm][o30][lifecycl h.hand->stop(); REQUIRE_THROWS_AS(h.hand->angle.get_blocking(kTimeout), std::runtime_error); } + +namespace { + struct OpenedO30 { + std::shared_ptr hop; + linkerbot::can::FakeTransport *transport = nullptr; + std::unique_ptr device; + + explicit OpenedO30(bool enforce_switch) : hop(std::make_shared()) { + using namespace linkerbot::hand; + hop->request_id = 0x001; + hop->seed_defaults(); + hop->enforce_wire_format = enforce_switch; + hop->switch_wire_on_mode_write = enforce_switch; + auto &object = hop->objects[{o30::protocol::kMiConfig, false}]; + object[0] = 0x01; + object[1] = 0x00; + object[6] = 2; + object[7] = 0; + object[8] = 1; + object[9] = 2; + HandDeviceConfig cfg; + cfg.model = Model::kO30; + cfg.side = HandSide::kUnknown; + cfg.interface_name = "fake0"; + cfg.address = 0x001; + device = std::make_unique(cfg, [this] { + auto next = std::make_unique(); + transport = next.get(); + o30_comm::attach_hop(transport, hop); + return next; + }); + device->open(); + transport->clear_sent(); + hop->writes.clear(); + } + }; + + [[nodiscard]] size_t count_prefix(const std::vector &sent, + std::initializer_list prefix, std::optional fd = std::nullopt) { + size_t count = 0; + for (const auto &message : sent) { + if (message.dlc < prefix.size()) { + continue; + } + bool match = true; + size_t index = 0; + for (const auto byte : prefix) { + if (message.data[index++] != byte) { + match = false; + break; + } + } + if (match && (!fd || message.is_fd == *fd)) { + ++count; + } + } + return count; + } +} // namespace + +TEST_CASE("O30 HOP reads and switches CAN interface mode", "[comm][o30]") { + using linkerbot::hand::HandDeviceConfig; + using linkerbot::hand::HandSide; + using linkerbot::hand::HopCanInterfaceMode; + using linkerbot::hand::Model; + using linkerbot::hand::ValidationError; + HandDeviceConfig profile; + profile.model = Model::kO30; + profile.side = HandSide::kUnknown; + REQUIRE(linkerbot::hand::declared_capabilities(profile).operations.read_can_configuration); + REQUIRE(linkerbot::hand::declared_capabilities(profile).operations.write_can_configuration); + + SECTION("CAN FD read") { + OpenedO30 opened(false); + const auto configuration = opened.device->get_can_configuration(); + REQUIRE(configuration.request_id == 0x001); + REQUIRE(configuration.response_id() == 0x401); + REQUIRE(configuration.interface_mode == HopCanInterfaceMode::kCanFd); + REQUIRE_FALSE(configuration.brs); + REQUIRE(configuration.nominal_bitrate == 1000000); + REQUIRE(configuration.data_bitrate == 5000000); + const auto sent = opened.transport->sent(); + REQUIRE(count_prefix(sent, {0xB5, 0x00, 0x02}, true) == 1); + REQUIRE(count_prefix(sent, {0xB5, 0x06, 0x04}, true) == 1); + REQUIRE(opened.hop->writes.empty()); + } + SECTION("mode write stays on CAN FD until reboot") { + OpenedO30 opened(false); + const auto result = opened.device->set_can_interface_mode(HopCanInterfaceMode::kCan20, true); + REQUIRE(result.write_sent); + REQUIRE(result.saved_to_flash); + REQUIRE(result.active_wire_is_fd); + REQUIRE_FALSE(result.active_format_changed); + REQUIRE(result.after.interface_mode == HopCanInterfaceMode::kCan20); + const auto sent = opened.transport->sent(); + REQUIRE(count_prefix(sent, {0x35, 0x06, 0x01, 0x01}, true) == 1); + REQUIRE(count_prefix(sent, {0x35, 0x1E, 0x01, 0x01}, true) == 1); + } + SECTION("firmware switches to classic CAN immediately and flash completion may be 0x00") { + OpenedO30 opened(true); + opened.hop->override_save_ack = true; + opened.hop->save_ack = 0x00; + const auto result = opened.device->set_can_interface_mode(HopCanInterfaceMode::kCan20, true); + REQUIRE(result.write_sent); + REQUIRE(result.saved_to_flash); + REQUIRE_FALSE(result.active_wire_is_fd); + REQUIRE(result.active_format_changed); + REQUIRE(result.after.interface_mode == HopCanInterfaceMode::kCan20); + const auto sent = opened.transport->sent(); + REQUIRE(count_prefix(sent, {0x35, 0x06, 0x01, 0x01}, true) == 1); + REQUIRE(count_prefix(sent, {0x35, 0x1E, 0x01, 0x01}, false) == 1); + } + SECTION("an already selected mode is not written again") { + OpenedO30 opened(false); + const auto result = opened.device->set_can_interface_mode(HopCanInterfaceMode::kCanFd, true); + REQUIRE_FALSE(result.write_sent); + REQUIRE(result.saved_to_flash); + REQUIRE_FALSE(result.active_format_changed); + const auto sent = opened.transport->sent(); + REQUIRE(count_prefix(sent, {0x35, 0x06, 0x01}) == 0); + REQUIRE(count_prefix(sent, {0x35, 0x1E, 0x01, 0x01}, true) == 1); + } + SECTION("classic CAN is rejected while BRS is enabled") { + OpenedO30 opened(false); + opened.hop->objects[{linkerbot::hand::o30::protocol::kMiConfig, false}][7] = 1; + REQUIRE_THROWS_AS(opened.device->set_can_interface_mode(HopCanInterfaceMode::kCan20, true), ValidationError); + REQUIRE(opened.hop->writes.empty()); + REQUIRE(count_prefix(opened.transport->sent(), {0x35, 0x06, 0x01}) == 0); + } +} diff --git a/tests/hand/o6/hop_fixture.hpp b/tests/hand/o6/hop_fixture.hpp new file mode 100644 index 00000000..dc044784 --- /dev/null +++ b/tests/hand/o6/hop_fixture.hpp @@ -0,0 +1,196 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace o6_hop_test { + using namespace linkerbot; + struct Sensor { + std::string descriptor; + std::vector data; + uint8_t rows = 0, columns = 0; + }; + + struct Firmware { + std::mutex mutex; + bool can_fd = true; + std::array info{}; + std::map> registers; + std::array sensors; + uint8_t selected = 1; + size_t position_writes = 0; + bool hold_tail = false, short_tail = false, no_reply = false, bad_length = false, bad_selected = false; + bool invalid_mask = false; + bool switch_wire_immediately = false; + bool drop_mode_write_reply = false; + bool override_save_ack = false; + uint8_t save_ack = 0; + std::optional held; + + static void put(std::array &target, size_t offset, const std::string &text, size_t width) { + std::fill_n(target.begin() + static_cast(offset), width, 0); + std::copy_n(text.begin(), std::min(width, text.size()), + target.begin() + static_cast(offset)); + } + + explicit Firmware(bool fd = true) : can_fd(fd) { + put(info, 0, "LHO6", 16); + put(info, 0x39, "LHO6-03.3-632-R-B-1-D", 32); + put(info, 0x59, "HOP", 8); + put(info, 0x61, "1.0.0", 8); + put(info, 0xa1, "1.0.3", 8); + put(info, 0x89, "V0.9.0", 16); + put(info, 0xa9, "2.0.0", 8); + put(info, 0xf1, "RIGHT", 8); + const std::array raw_pos{10, 51, 255, 0, 128, 200}; + for (size_t i = 0; i < 6; ++i) { + registers[hand::o6::hop::kMiPosition][hand::o6::hop::kJointSlots[i]] = raw_pos[i]; + } + for (uint8_t mi : + {hand::o6::hop::kMiSpeed, hand::o6::hop::kMiAcceleration, hand::o6::hop::kMiCurrent, + hand::o6::hop::kMiTemperature, hand::o6::hop::kMiStallTime, hand::o6::hop::kMiStallThreshold, + hand::o6::hop::kMiStallHoldCurrent, hand::o6::hop::kMiFault}) { + for (size_t i = 0; i < 6; ++i) { + registers[mi][hand::o6::hop::kJointSlots[i]] = static_cast(i + 1); + } + } + registers[hand::o6::hop::kMiFault][10] = 0xb0; // bit7 known, bits4/5 reserved + auto &can_config = registers[hand::o6::hop::kMiConfig]; + can_config[0] = 0x01; + can_config[6] = static_cast(fd ? 2 : 1); + can_config[7] = 0; + can_config[8] = 1; + can_config[9] = 2; + sensors[0] = {"FnS_U16_1;Rsv_U16_1;Fn_U8_4", {42, 0, 99, 0, 1, 2, 3, 4}, 2, 2}; + sensors[1] = {"FNS_U16_1;FTS_I16_1;FDS_F32_1", {9, 0, 254, 255, 0, 0, 52, 66}, 0, 0}; + sensors[3] = {"xyz_F32_1", {0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64}, 0, 0}; + sensors[4] = {"Fn_U16_260", std::vector(520, 7), 2, 130}; + } + + can::Message response(const can::Message &req, const std::vector &data) const { + can::Message result; + result.id = req.id | 0x400U; + result.is_fd = can_fd; + const size_t count = data.size() + 3; + if (can_fd) { + for (uint8_t n : {3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64}) { + if (n >= count) { + result.dlc = n; + break; + } + } + } else { + result.dlc = static_cast(count); + } + result.data[0] = req.data[0]; + result.data[1] = req.data[1]; + result.data[2] = static_cast(data.size()); + std::copy(data.begin(), data.end(), result.data.begin() + 3); + return result; + } + + std::vector handle(const can::Message &req) { + const std::lock_guard lock(mutex); + const size_t max_payload = hand::o6::hop::max_payload_bytes(can_fd); + if (no_reply || req.is_fd != can_fd || req.is_extended || req.dlc < 3) { + return {}; + } + const uint8_t mi = req.data[0] & 0x7fU, si = req.data[1], length = req.data[2]; + if (length == 0 || length > max_payload || size_t(si) + length > 256) { + return {}; + } + const bool write = req.dlc > 3; + if (write && mi == hand::o6::hop::kMiPosition) { + ++position_writes; + } + std::vector data; + if (mi == hand::o6::hop::kMiProductInfo) { + data.assign(info.begin() + si, info.begin() + si + length); + } else if (mi == hand::o6::hop::kMiSensorCommand) { + if (write && si == 0x6e) { + selected = req.data[3]; + data = {selected}; + } else { + std::array meta{}; + const auto &sensor = sensors[selected - 1]; + put(meta, 0, sensor.data.empty() ? "NO_SENSOR" : "TEST", 32); + put(meta, 32, "count", 8); + meta[41] = sensor.rows; + meta[42] = sensor.columns; + meta[43] = static_cast(sensor.descriptor.size()); + std::copy(sensor.descriptor.begin(), sensor.descriptor.end(), meta.begin() + 44); + meta[108] = static_cast(sensor.data.size() & 0xffU); + meta[109] = static_cast(sensor.data.size() >> 8U); + meta[110] = static_cast(bad_selected ? selected % 5 + 1 : selected); + meta[111] = sensor.rows; + meta[112] = sensor.columns; + meta[113] = invalid_mask ? 1 : 0; + meta[114] = 1; + if (bad_length) { + ++meta[108]; + } + data.assign(meta.begin() + si, meta.begin() + si + length); + } + } else if (mi >= hand::o6::hop::kMiSensorData1 && mi <= hand::o6::hop::kMiSensorData3) { + const auto &sensor = sensors[selected - 1]; + const size_t start = static_cast(mi - hand::o6::hop::kMiSensorData1) * 255 + si; + if (start + length > sensor.data.size()) { + return {}; + } + data.assign(sensor.data.begin() + static_cast(start), + sensor.data.begin() + static_cast(start + length)); + } else { + auto &object = registers[mi]; + if (write) { + std::copy_n(req.data.begin() + 3, length, object.begin() + si); + } + data.assign(object.begin() + si, object.begin() + si + length); + } + if (write && mi == hand::o6::hop::kMiConfig && si == 0x06 && switch_wire_immediately && !data.empty()) { + can_fd = data[0] == 2; + } + if (write && mi == hand::o6::hop::kMiConfig && si == 0x1E && override_save_ack) { + data = {save_ack}; + } + if (drop_mode_write_reply && write && mi == hand::o6::hop::kMiConfig && si == 0x06) { + return {}; + } + auto reply = response(req, data); + if (write && mi == hand::o6::hop::kMiPosition && si == 10) { + if (short_tail) { + reply.data[2] = 1; + reply.dlc = 4; + } + if (hold_tail) { + held = reply; + return {}; + } + } + return {reply}; + } + + std::unique_ptr transport(uint32_t id = 1) { + registers[hand::o6::hop::kMiConfig][0] = static_cast(id & 0xffU); + registers[hand::o6::hop::kMiConfig][1] = static_cast((id >> 8) & 0xffU); + auto result = std::make_unique(); + result->on_request(id, [this](const auto &req) { return handle(req); }); + return result; + } + }; + + inline hand::HandDeviceConfig config(uint32_t id = 1, bool can_fd = true) { + hand::HandDeviceConfig result; + result.model = hand::Model::kO6; + result.side = hand::HandSide::kRight; + result.o6_protocol = can_fd ? hand::O6Protocol::kHopV004 : hand::O6Protocol::kHopV004Can; + result.address = id; + result.command_timeout = std::chrono::milliseconds{150}; + return result; + } +} // namespace o6_hop_test diff --git a/tests/hand/o6/test_hop_comm.cpp b/tests/hand/o6/test_hop_comm.cpp new file mode 100644 index 00000000..4d03cd9a --- /dev/null +++ b/tests/hand/o6/test_hop_comm.cpp @@ -0,0 +1,550 @@ +#include "hand/support/optional_value.hpp" +#include "hop_fixture.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace linkerbot::hand; +using namespace std::chrono_literals; +using o6_hop_test::config; +using o6_hop_test::Firmware; + +TEST_CASE("O6 HOP explicit capabilities preserve classic default", "[comm][o6-hop]") { + auto cfg = config(0x123, true); + const auto fd_profile = declared_capabilities(cfg); + REQUIRE(fd_profile.validate()); + REQUIRE(fd_profile.transport.kind == TransportKind::kCanFd); + REQUIRE(fd_profile.transport.mtu == 64); + REQUIRE(fd_profile.transport.request_id == 0x123); + REQUIRE(fd_profile.transport.response_id == 0x523); + REQUIRE(fd_profile.joints[0].raw_angle_range.maximum == 255); + REQUIRE(fd_profile.supports(CommandSemantic::kAccelerations)); + REQUIRE(fd_profile.supports(CommandSemantic::kStallDetectionTimes)); + REQUIRE(fd_profile.supports(CommandSemantic::kStallThresholds)); + REQUIRE(fd_profile.supports(CommandSemantic::kStallHoldCurrents)); + REQUIRE(fd_profile.supports(TelemetrySemantic::kConfiguredAccelerations)); + REQUIRE(fd_profile.supports(TelemetrySemantic::kStallDetectionTimes)); + REQUIRE(fd_profile.supports(TelemetrySemantic::kStallThresholds)); + REQUIRE(fd_profile.supports(TelemetrySemantic::kStallHoldCurrents)); + REQUIRE(fd_profile.force_field("fn").supported == std::nullopt); + REQUIRE_FALSE(fd_profile.supports(DeviceOperation::kClearFaults)); + REQUIRE_FALSE(fd_profile.supports(DeviceOperation::kEnable)); + + const auto can_profile = declared_capabilities(config(0x045, false)); + REQUIRE(can_profile.validate()); + REQUIRE(can_profile.transport.kind == TransportKind::kCan); + REQUIRE(can_profile.transport.mtu == 8); + REQUIRE(can_profile.transport.request_id == 0x045); + REQUIRE(can_profile.transport.response_id == 0x445); + + REQUIRE(declared_capabilities(Model::kO6, HandSide::kRight).transport.kind == TransportKind::kCan); + REQUIRE(declared_capabilities(Model::kO6, HandSide::kRight).transport.request_id == 0x27); + + cfg = config(); + cfg.model = Model::kL6; + REQUIRE_THROWS_AS(HandDevice(cfg), ValidationError); + cfg = config(); + cfg.l6_protocol = L6Protocol::kHopV004; + REQUIRE_THROWS_AS(HandDevice(cfg), ValidationError); + cfg = config(); + cfg.runtime_behavior = RuntimeBehavior::kPython; + REQUIRE_THROWS_AS(HandDevice(cfg), ValidationError); + cfg = config(); + cfg.address = 0x3ff; + REQUIRE_THROWS_AS(HandDevice(cfg), ValidationError); + cfg = config(); + cfg.angle_mapping_path = "old.json"; + REQUIRE_THROWS_AS(HandDevice(cfg), ValidationError); + cfg = config(); + cfg.host_address = 1; + REQUIRE_THROWS_AS(HandDevice(cfg), ValidationError); + cfg = config(); + cfg.side = HandSide::kUnknown; + REQUIRE_THROWS_AS(HandDevice(cfg), ValidationError); +} + +TEST_CASE("O6 HOP unified open reads and writes all O6 channels over CAN FD", "[comm][o6-hop]") { + auto firmware = std::make_shared(true); + auto cfg = config(0x123, true); + HandDevice device(cfg, [firmware] { return firmware->transport(0x123); }); + REQUIRE(device.get_capabilities().transport.kind == TransportKind::kCanFd); + device.open(); + + const auto identity = test_support::require_value(device.get_identity()); + REQUIRE(identity.model == Model::kO6); + REQUIRE(identity.side == HandSide::kRight); + REQUIRE(identity.protocol_name == "HOP"); + REQUIRE(identity.protocol_version == "1.0.0"); + REQUIRE(identity.firmware_version == "1.0.3"); + REQUIRE(identity.serial_number == "632"); + + REQUIRE(device.get_angles().raw == std::vector{10, 51, 255, 0, 128, 200}); + REQUIRE(device.get_angles().percent[2] == 100.0); + REQUIRE(device.get_faults().statuses[0].known_bits == 0x80); + REQUIRE(device.get_faults().statuses[0].reserved_bits == 0x30); + REQUIRE(device.get_currents().raw[0] == 1); + REQUIRE(device.get_current_limits().raw[5] == 6); + REQUIRE(device.get_configured_speeds().meta.origin == TelemetryValueOrigin::kDeviceConfigured); + REQUIRE(device.get_configured_accelerations().meta.origin == TelemetryValueOrigin::kDeviceConfigured); + REQUIRE(device.get_temperatures().raw[0] == 1); + REQUIRE(device.get_stall_detection_times().raw == std::vector{1, 2, 3, 4, 5, 6}); + REQUIRE(device.get_stall_thresholds().raw == std::vector{1, 2, 3, 4, 5, 6}); + REQUIRE(device.get_stall_hold_currents().raw == std::vector{1, 2, 3, 4, 5, 6}); + REQUIRE_THROWS_AS(device.clear_faults(), UnsupportedOperationError); + REQUIRE_THROWS_AS(device.enable(), UnsupportedOperationError); + + const auto before_sequence = device.get_angles().meta.sequence; + auto set_pos = device.set_angles({255, 10, 20, 128, 1, 0}); + REQUIRE(set_pos.wait_for(1s)); + REQUIRE(set_pos.stage() == CommandStage::kAcknowledged); + REQUIRE(set_pos.sent_frames() == 2); + REQUIRE(test_support::require_value(device.get_snapshot().angles).meta.sequence > before_sequence); + REQUIRE(device.get_angles().raw == std::vector{255, 10, 20, 128, 1, 0}); + + auto percent = device.set_percent_angles({0, 100, 50, 20, 80, 0}); + REQUIRE(percent.wait_for(1s)); + REQUIRE(percent.stage() == CommandStage::kAcknowledged); + REQUIRE(device.get_angles().raw == std::vector{0, 255, 128, 51, 204, 0}); + + auto speed = device.set_speeds({10, 20, 30, 40, 50, 255}); + REQUIRE(speed.wait_for(1s)); + REQUIRE(speed.stage() == CommandStage::kAcknowledged); + REQUIRE(device.get_configured_speeds().raw == std::vector{10, 20, 30, 40, 50, 255}); + + auto accel = device.set_accelerations({5, 15, 25, 35, 45, 255}); + REQUIRE(accel.wait_for(1s)); + REQUIRE(accel.stage() == CommandStage::kAcknowledged); + REQUIRE(device.get_configured_accelerations().raw == std::vector{5, 15, 25, 35, 45, 255}); + + auto current = device.set_current_limits({255, 2, 3, 4, 5, 6}); + REQUIRE(current.wait_for(1s)); + REQUIRE(current.stage() == CommandStage::kAcknowledged); + REQUIRE(device.get_current_limits().raw[0] == 255); + + auto stall_time = device.set_stall_detection_times({11, 12, 13, 14, 15, 16}); + REQUIRE(stall_time.wait_for(1s)); + REQUIRE(stall_time.stage() == CommandStage::kAcknowledged); + REQUIRE(device.get_stall_detection_times().raw == std::vector{11, 12, 13, 14, 15, 16}); + + auto stall_threshold = device.set_stall_thresholds({21, 22, 23, 24, 25, 26}); + REQUIRE(stall_threshold.wait_for(1s)); + REQUIRE(stall_threshold.stage() == CommandStage::kAcknowledged); + REQUIRE(device.get_stall_thresholds().raw == std::vector{21, 22, 23, 24, 25, 26}); + + auto stall_hold = device.set_stall_hold_currents({31, 32, 33, 34, 35, 36}); + REQUIRE(stall_hold.wait_for(1s)); + REQUIRE(stall_hold.stage() == CommandStage::kAcknowledged); + REQUIRE(device.get_stall_hold_currents().raw == std::vector{31, 32, 33, 34, 35, 36}); + + const auto snapshot = device.get_snapshot(); + REQUIRE(snapshot.joints.size() == 6); + REQUIRE(snapshot.joints[0].configured_acceleration_raw == 5); + REQUIRE(snapshot.joints[0].stall_detection_time_raw == 11); + REQUIRE(snapshot.joints[0].stall_threshold_raw == 21); + REQUIRE(snapshot.joints[0].stall_hold_current_raw == 31); + + auto saved = device.save_parameters(); + REQUIRE(saved.wait_for(1s)); + REQUIRE(saved.stage() == CommandStage::kAcknowledged); + + device.close(); + REQUIRE(device.get_capabilities().transport.kind == TransportKind::kCanFd); +} + +TEST_CASE("O6 HOP supports Classic CAN 2.0 with 5-byte chunking through HandDevice", "[comm][o6-hop]") { + auto firmware = std::make_shared(false); + Firmware::put(firmware->info, 0, "O6", 16); + Firmware::put(firmware->info, 0x39, "LHO6XXXXXXXXXXXX", 32); + auto transport = firmware->transport(0x021); + auto *fake = transport.get(); + auto session = linkerbot::transport::Session::own(std::move(transport)); + + auto cfg = config(0x021, false); + cfg.identity_timeout = 2s; + cfg.transaction_timeout = 1s; + cfg.command_timeout = 1s; + HandDevice device(cfg, session); + REQUIRE(device.get_capabilities().transport.kind == TransportKind::kCan); + device.open(); + + const auto identity = test_support::require_value(device.get_identity()); + REQUIRE(identity.model == Model::kO6); + REQUIRE(identity.device_uid == "LHO6XXXXXXXXXXXX"); + REQUIRE(identity.product_code == "O6"); + + auto set_pos = device.set_angles({100, 110, 120, 130, 140, 150}); + REQUIRE(set_pos.wait_for(1s)); + REQUIRE(set_pos.stage() == CommandStage::kAcknowledged); + REQUIRE(device.get_angles().raw == std::vector{100, 110, 120, 130, 140, 150}); + + const auto force = device.get_force(5s); + REQUIRE(force.meta.valid); + REQUIRE(force.sensors.size() == 5); + REQUIRE(test_support::require_value(force.field("fns")->raw[0]).at(0) == 42); + REQUIRE(force.field("fn")->raw[0] == std::vector{1, 2, 3, 4}); + + const auto sent = fake->sent(); + REQUIRE_FALSE(sent.empty()); + for (const auto &req : sent) { + REQUIRE_FALSE(req.is_fd); + REQUIRE_FALSE(req.is_extended); + REQUIRE(req.dlc <= 8); + REQUIRE(req.data[2] <= 5); + } + + device.close(); + session->close(); +} + +TEST_CASE("O6 HOP angle command waits for both mounted replies and isolates partial failure", "[comm][o6-hop]") { + auto firmware = std::make_shared(true); + auto transport = firmware->transport(); + auto *fake = transport.get(); + auto session = linkerbot::transport::Session::own(std::move(transport)); + HandDevice device(config(), session); + device.open(); + const auto before = device.get_snapshot().angles; + { + std::lock_guard lock(firmware->mutex); + firmware->hold_tail = true; + } + auto handle = device.set_angles({5, 6, 7, 8, 9, 10}); + REQUIRE_FALSE(handle.wait_for(20ms)); + REQUIRE(handle.stage() == CommandStage::kDispatched); + REQUIRE(test_support::require_value(device.get_snapshot().angles).raw == test_support::require_value(before).raw); + std::optional held; + { + std::lock_guard lock(firmware->mutex); + held = firmware->held; + } + REQUIRE(held); + fake->inject(test_support::require_value(held)); + REQUIRE(handle.wait_for(1s)); + REQUIRE(handle.stage() == CommandStage::kAcknowledged); + REQUIRE(test_support::require_value(device.get_snapshot().angles).raw == std::vector{5, 6, 7, 8, 9, 10}); + + { + std::lock_guard lock(firmware->mutex); + firmware->hold_tail = false; + firmware->short_tail = true; + } + auto failed = device.set_angles({1, 2, 3, 4, 5, 6}); + REQUIRE(failed.wait_for(1s)); + REQUIRE(failed.stage() == CommandStage::kFailed); + REQUIRE(failed.error()); + REQUIRE(test_support::require_value(device.get_snapshot().angles).raw == std::vector{5, 6, 7, 8, 9, 10}); + + device.close(); + session->close(); +} + +TEST_CASE("O6 HOP identity rejects wrong model side and protocol", "[comm][o6-hop]") { + for (int scenario = 0; scenario < 3; ++scenario) { + auto firmware = std::make_shared(true); + if (scenario == 0) { + Firmware::put(firmware->info, 0, "L6", 16); + } + if (scenario == 1) { + Firmware::put(firmware->info, 0xf1, "LEFT", 8); + } + if (scenario == 2) { + Firmware::put(firmware->info, 0x59, "OTHER", 8); + } + HandDevice device(config(), [firmware] { return firmware->transport(); }); + REQUIRE_THROWS(device.open()); + REQUIRE_FALSE(device.is_open()); + device.close(); + } +} + +TEST_CASE("O6 HOP unified dynamic force capabilities polling stream and recover", "[comm][o6-hop]") { + auto firmware = std::make_shared(true); + HandDevice device(config(), [firmware] { return firmware->transport(); }); + device.open(); + + const auto force = device.get_force({"fn", "fns", "fts", "fds"}, 2s); + REQUIRE(force.field("fn")); + REQUIRE(force.field("fns")); + REQUIRE(force.field("fts")); + REQUIRE(device.get_capabilities().force_field("fns").supported == true); + + auto handle = device.set_angles({7, 8, 9, 10, 11, 12}); + REQUIRE(handle.wait_for(1s)); + REQUIRE(handle.stage() == CommandStage::kAcknowledged); + + auto stream = device.stream_handle(); + device.start_polling({{TelemetrySemantic::kAngles, 10ms}, + {TelemetrySemantic::kConfiguredAccelerations, 20ms}, + {TelemetrySemantic::kStallThresholds, 20ms}}); + const auto previous = device.get_snapshot(); + const auto next = device.wait_for_snapshot(previous, 500ms); + REQUIRE(test_support::require_value(next.angles).meta.valid); + + device.recover(); + REQUIRE(device.is_open()); + REQUIRE(test_support::require_value(device.get_identity()).device_uid.has_value()); + REQUIRE(device.get_angles().raw == std::vector{7, 8, 9, 10, 11, 12}); + { + std::lock_guard lock(firmware->mutex); + REQUIRE(firmware->position_writes == 2); + } + + device.stop_polling(); + device.stop_stream(); + device.close(); +} + +TEST_CASE("O6 HOP shares a bus without routing one hand to another", "[comm][o6-hop]") { + auto right = std::make_shared(true); + auto left = std::make_shared(true); + Firmware::put(left->info, 0xf1, "LEFT", 8); + Firmware::put(left->info, 0x39, "LHO6-03.3-633-L-B-1-D", 32); + auto transport = right->transport(1); + auto *fake = transport.get(); + fake->on_request(2, [left](const auto &request) { return left->handle(request); }); + auto session = linkerbot::transport::Session::own(std::move(transport)); + + auto cfg_right = config(1, true); + auto cfg_left = config(2, true); + cfg_left.side = HandSide::kLeft; + HandDevice hand_right(cfg_right, session); + HandDevice hand_left(cfg_left, session); + hand_right.open(); + hand_left.open(); + + REQUIRE(hand_right.set_angles({1, 2, 3, 4, 5, 6}).wait_for(1s)); + REQUIRE(hand_left.set_angles({101, 102, 103, 104, 105, 106}).wait_for(1s)); + REQUIRE(hand_right.get_angles().raw == std::vector{1, 2, 3, 4, 5, 6}); + REQUIRE(hand_left.get_angles().raw == std::vector{101, 102, 103, 104, 105, 106}); + + hand_right.close(); + REQUIRE(fake->close_calls() == 0); + REQUIRE(hand_left.get_angles().raw[0] == 101); + hand_left.close(); + session->close(); +} + +namespace { + using linkerbot::can::FakeTransport; + using linkerbot::can::Message; + + [[nodiscard]] size_t count_prefix(const std::vector &sent, std::initializer_list prefix, + std::optional fd = std::nullopt) { + size_t count = 0; + for (const auto &message : sent) { + if (message.dlc < prefix.size()) { + continue; + } + bool match = true; + size_t index = 0; + for (const auto byte : prefix) { + if (message.data[index++] != byte) { + match = false; + break; + } + } + if (match && (!fd || message.is_fd == *fd)) { + ++count; + } + } + return count; + } + + [[nodiscard]] size_t count_config_writes(const std::vector &sent) { + size_t count = 0; + for (const auto &message : sent) { + if (message.dlc >= 4 && message.data[0] == 0x35) { + ++count; + } + } + return count; + } + + struct OpenedHop { + std::shared_ptr firmware; + FakeTransport *transport = nullptr; + std::unique_ptr device; + + OpenedHop(bool can_fd, uint32_t id) : firmware(std::make_shared(can_fd)) { + device = std::make_unique(config(id, can_fd), [this, id] { + auto next = firmware->transport(id); + transport = next.get(); + return next; + }); + device->open(); + transport->clear_sent(); + } + }; + + void install_classic_o6(FakeTransport *transport) { + const std::string code = "LHO6-1-123-L"; + transport->on_request(0x28, [code](const Message &request) { + if (request.data[0] == 0xC0) { + std::vector replies; + for (int chunk = 0; chunk < 4; ++chunk) { + Message reply{}; + reply.id = request.id; + reply.dlc = 8; + reply.data[0] = 0xC0; + reply.data[1] = static_cast(chunk); + for (size_t index = 0; index < 6; ++index) { + const auto offset = static_cast(chunk) * 6 + index; + reply.data[index + 2] = offset < code.size() ? static_cast(code[offset]) : uint8_t{0}; + } + replies.push_back(reply); + } + return replies; + } + if (request.data[0] == 0xC1 || request.data[0] == 0xC2 || request.data[0] == 0xC4) { + Message reply{}; + reply.id = request.id; + reply.dlc = 4; + reply.data[0] = request.data[0]; + reply.data[1] = 1; + reply.data[2] = 2; + reply.data[3] = 3; + return std::vector{reply}; + } + Message reply{}; + reply.id = request.id; + reply.dlc = 7; + reply.data[0] = request.data[0]; + for (size_t index = 1; index < 7; ++index) { + reply.data[index] = request.dlc > index ? request.data[index] : uint8_t{64}; + } + return std::vector{reply}; + }); + } +} // namespace + +TEST_CASE("O6 HOP reads and switches CAN interface mode", "[comm][o6-hop]") { + const auto hop = declared_capabilities(config(0x123, true)); + REQUIRE(hop.operations.read_can_configuration); + REQUIRE(hop.operations.write_can_configuration); + REQUIRE(declared_capabilities(config(0x045, false)).operations.write_can_configuration); + REQUIRE_FALSE(declared_capabilities(Model::kO6, HandSide::kRight).operations.read_can_configuration); + REQUIRE_FALSE(declared_capabilities(Model::kO6, HandSide::kRight).operations.write_can_configuration); + + SECTION("CAN FD read") { + OpenedHop opened(true, 0x123); + const auto configuration = opened.device->get_can_configuration(); + REQUIRE(configuration.request_id == 0x123); + REQUIRE(configuration.response_id() == 0x523); + REQUIRE(configuration.interface_mode == HopCanInterfaceMode::kCanFd); + REQUIRE_FALSE(configuration.brs); + REQUIRE(configuration.nominal_bitrate == 1000000); + REQUIRE(configuration.data_bitrate == 5000000); + const auto sent = opened.transport->sent(); + REQUIRE(count_prefix(sent, {0xB5, 0x00, 0x02}, true) == 1); + REQUIRE(count_prefix(sent, {0xB5, 0x06, 0x04}, true) == 1); + } + SECTION("CAN 2.0 read") { + OpenedHop opened(false, 0x045); + const auto configuration = opened.device->get_can_configuration(); + REQUIRE(configuration.request_id == 0x045); + REQUIRE(configuration.interface_mode == HopCanInterfaceMode::kCan20); + const auto sent = opened.transport->sent(); + REQUIRE(count_prefix(sent, {0xB5, 0x00, 0x02}, false) == 1); + REQUIRE(count_prefix(sent, {0xB5, 0x06, 0x04}, false) == 1); + for (const auto &message : sent) { + REQUIRE_FALSE(message.is_fd); + REQUIRE(message.dlc <= 8); + } + } + SECTION("mode write stays on CAN FD until reboot and accepts flash completion 0x01") { + OpenedHop opened(true, 0x123); + const auto result = opened.device->set_can_interface_mode(HopCanInterfaceMode::kCan20, true); + REQUIRE(result.write_sent); + REQUIRE(result.saved_to_flash); + REQUIRE(result.active_wire_is_fd); + REQUIRE_FALSE(result.active_format_changed); + REQUIRE(result.before.interface_mode == HopCanInterfaceMode::kCanFd); + REQUIRE(result.after.interface_mode == HopCanInterfaceMode::kCan20); + REQUIRE(result.after.brs == result.before.brs); + REQUIRE(result.after.nominal_bitrate == result.before.nominal_bitrate); + REQUIRE(result.after.data_bitrate == result.before.data_bitrate); + const auto sent = opened.transport->sent(); + REQUIRE(count_prefix(sent, {0x35, 0x06, 0x01, 0x01}, true) == 1); + REQUIRE(count_prefix(sent, {0x35, 0x1E, 0x01, 0x01}, true) == 1); + } + SECTION("firmware switches to classic CAN immediately and flash completion may be 0x00") { + OpenedHop opened(true, 0x123); + opened.firmware->switch_wire_immediately = true; + opened.firmware->override_save_ack = true; + opened.firmware->save_ack = 0x00; + const auto result = opened.device->set_can_interface_mode(HopCanInterfaceMode::kCan20, true); + REQUIRE(result.write_sent); + REQUIRE(result.saved_to_flash); + REQUIRE_FALSE(result.active_wire_is_fd); + REQUIRE(result.active_format_changed); + REQUIRE(result.after.interface_mode == HopCanInterfaceMode::kCan20); + const auto sent = opened.transport->sent(); + REQUIRE(count_prefix(sent, {0x35, 0x06, 0x01, 0x01}, true) == 1); + REQUIRE(count_prefix(sent, {0x35, 0x1E, 0x01, 0x01}, false) == 1); + } + SECTION("classic host writes CAN FD mode once and keeps the current wire") { + OpenedHop opened(false, 0x045); + const auto result = opened.device->set_can_interface_mode(HopCanInterfaceMode::kCanFd, true); + REQUIRE(result.write_sent); + REQUIRE(result.saved_to_flash); + REQUIRE_FALSE(result.active_wire_is_fd); + REQUIRE_FALSE(result.active_format_changed); + REQUIRE(result.after.interface_mode == HopCanInterfaceMode::kCanFd); + const auto sent = opened.transport->sent(); + REQUIRE(count_prefix(sent, {0x35, 0x06, 0x01, 0x02}, false) == 1); + REQUIRE(count_prefix(sent, {0x35, 0x1E, 0x01, 0x01}, false) == 1); + } + SECTION("an already selected mode is not written again") { + OpenedHop opened(true, 0x123); + const auto result = opened.device->set_can_interface_mode(HopCanInterfaceMode::kCanFd, true); + REQUIRE_FALSE(result.write_sent); + REQUIRE(result.saved_to_flash); + REQUIRE_FALSE(result.active_format_changed); + const auto sent = opened.transport->sent(); + REQUIRE(count_prefix(sent, {0x35, 0x06, 0x01}) == 0); + REQUIRE(count_prefix(sent, {0x35, 0x1E, 0x01, 0x01}, true) == 1); + } + SECTION("classic CAN is rejected while BRS is enabled") { + OpenedHop opened(true, 0x123); + opened.firmware->registers[o6::hop::kMiConfig][7] = 1; + REQUIRE_THROWS_AS(opened.device->set_can_interface_mode(HopCanInterfaceMode::kCan20, true), ValidationError); + REQUIRE(count_config_writes(opened.transport->sent()) == 0); + } + SECTION("a missed mode ACK is verified once on the new wire format") { + OpenedHop opened(true, 0x123); + opened.firmware->switch_wire_immediately = true; + opened.firmware->drop_mode_write_reply = true; + const auto result = opened.device->set_can_interface_mode(HopCanInterfaceMode::kCan20, false, 100ms); + REQUIRE(result.write_sent); + REQUIRE_FALSE(result.saved_to_flash); + REQUIRE(result.active_format_changed); + REQUIRE_FALSE(result.active_wire_is_fd); + REQUIRE(count_prefix(opened.transport->sent(), {0x35, 0x06, 0x01, 0x01}) == 1); + } +} + +TEST_CASE("classic O6 rejects CAN configuration before any frame", "[comm][o6-hop]") { + FakeTransport *transport = nullptr; + HandDeviceConfig cfg; + cfg.model = Model::kO6; + cfg.side = HandSide::kLeft; + cfg.interface_name = "fake0"; + HandDevice device(cfg, [&] { + auto next = std::make_unique(); + transport = next.get(); + install_classic_o6(transport); + return next; + }); + device.open(); + transport->clear_sent(); + REQUIRE_THROWS_AS(device.get_can_configuration(), UnsupportedOperationError); + REQUIRE(transport->sent().empty()); + REQUIRE_THROWS_AS(device.set_can_interface_mode(HopCanInterfaceMode::kCan20, true), UnsupportedOperationError); + REQUIRE(transport->sent().empty()); + device.close(); +} diff --git a/tests/protocol/test_o6_hop_vectors.cpp b/tests/protocol/test_o6_hop_vectors.cpp new file mode 100644 index 00000000..8e12c862 --- /dev/null +++ b/tests/protocol/test_o6_hop_vectors.cpp @@ -0,0 +1,180 @@ +#include +#include +#include + +using namespace linkerbot::hand; +using linkerbot::can::Message; +namespace hp = linkerbot::hand::o6::hop; +namespace wire = linkerbot::hand::protocol::hop; + +namespace { + Message reply(uint8_t mi, uint8_t si, const std::vector &data, bool rts = false, bool can_fd = true) { + Message result; + result.id = 0x401; + result.is_fd = can_fd; + result.dlc = can_fd ? wire::canfd_wire_bytes(data.size() + 3) : static_cast(data.size() + 3); + result.data[0] = static_cast(mi | (rts ? 0x80U : 0U)); + result.data[1] = si; + result.data[2] = static_cast(data.size()); + std::copy(data.begin(), data.end(), result.data.begin() + 3); + return result; + } +} // namespace + +TEST_CASE("O6 HOP strict range and address vectors for CAN FD and CAN 2.0", "[protocol][o6-hop]") { + REQUIRE(hp::response_id(0) == 0x400); + REQUIRE(hp::response_id(0x3fe) == 0x7fe); + REQUIRE_THROWS_AS(hp::response_id(0x3ff), ValidationError); + REQUIRE_THROWS_AS(hp::transaction(1, 0x80, 0, 1), ValidationError); + REQUIRE_THROWS_AS(hp::transaction(1, 1, 250, 10), ValidationError); + REQUIRE_THROWS_AS(hp::transaction(1, 1, 0, 62), ValidationError); + REQUIRE_THROWS_AS(hp::transaction(1, 1, 0, 6, {}, false, {}, false), ValidationError); + + auto fd_plan = hp::transaction(1, hp::kMiCurrent, 5, 10, {}, true, {}, true); + REQUIRE(fd_plan.frames[0].dlc == 3); + REQUIRE(fd_plan.frames[0].data[0] == 0x84); + REQUIRE(fd_plan.frames[0].is_fd); + REQUIRE_FALSE(fd_plan.frames[0].is_extended); + REQUIRE_FALSE(fd_plan.frames[0].is_brs); + auto fd_msg = reply(hp::kMiCurrent, 5, std::vector(10, 9), true, true); + REQUIRE(fd_plan.consume(fd_msg).kind == protocol::ProgressKind::complete); + fd_msg.is_fd = false; + REQUIRE(fd_plan.consume(fd_msg).kind == protocol::ProgressKind::unmatched); + fd_msg.is_fd = true; + fd_msg.data[0] = hp::kMiCurrent; + REQUIRE(fd_plan.consume(fd_msg).kind == protocol::ProgressKind::unmatched); + fd_msg.data[0] = 0x4f; + fd_msg.data[2] = 1; + REQUIRE(fd_plan.consume(fd_msg).kind == protocol::ProgressKind::unmatched); + fd_msg.data[0] = 0x84; + fd_msg.data[2] = 9; + REQUIRE_THROWS_AS(fd_plan.consume(fd_msg), ProtocolError); + fd_msg.data[2] = 10; + fd_msg.dlc = 13; + REQUIRE_THROWS_AS(fd_plan.consume(fd_msg), ProtocolError); + fd_msg.dlc = 8; + REQUIRE_THROWS_AS(fd_plan.consume(fd_msg), ProtocolError); + + auto can_plan = hp::transaction(1, hp::kMiPosition, 10, 5, {}, false, {}, false); + REQUIRE(can_plan.frames[0].dlc == 3); + REQUIRE(can_plan.frames[0].data[0] == hp::kMiPosition); + REQUIRE_FALSE(can_plan.frames[0].is_fd); + REQUIRE_FALSE(can_plan.frames[0].is_extended); + REQUIRE_FALSE(can_plan.frames[0].is_brs); + auto can_msg = reply(hp::kMiPosition, 10, {1, 2, 3, 4, 5}, false, false); + REQUIRE(can_plan.consume(can_msg).kind == protocol::ProgressKind::complete); + auto fd_mismatch = reply(hp::kMiPosition, 10, {1, 2, 3, 4, 5}, false, true); + REQUIRE(can_plan.consume(fd_mismatch).kind == protocol::ProgressKind::unmatched); + can_msg.dlc = 12; + REQUIRE_THROWS_AS(can_plan.consume(can_msg), ProtocolError); +} + +TEST_CASE("O6 HOP 8 bit projection and mounted write vectors", "[protocol][o6-hop]") { + for (const bool can_fd : {true, false}) { + const std::vector canonical{10, 20, 30, 40, 50, 60}; + auto plan = hp::write_joints(1, hp::kMiPosition, canonical, false, "angle_targets", can_fd); + REQUIRE(plan.frames.size() == 2); + REQUIRE(plan.frames[0].is_fd == can_fd); + REQUIRE(plan.frames[1].is_fd == can_fd); + REQUIRE(plan.frames[0].data[1] == 5); + REQUIRE(plan.frames[0].data[2] == 1); + REQUIRE(plan.frames[0].dlc == 4); + REQUIRE(plan.frames[0].data[3] == 20); + REQUIRE(plan.frames[1].data[1] == 10); + REQUIRE(plan.frames[1].data[2] == 5); + REQUIRE(plan.frames[1].dlc == 8); + REQUIRE(plan.frames[1].data[3] == 10); + REQUIRE(plan.frames[1].data[4] == 30); + REQUIRE(plan.frames[1].data[5] == 40); + REQUIRE(plan.frames[1].data[6] == 50); + REQUIRE(plan.frames[1].data[7] == 60); + + auto tail = reply(hp::kMiPosition, 10, {10, 30, 40, 50, 60}, false, can_fd); + REQUIRE(plan.consume(tail).kind == protocol::ProgressKind::pending); + REQUIRE(plan.consume(tail).kind == protocol::ProgressKind::pending); + const auto result = plan.consume(reply(hp::kMiPosition, 5, {20}, false, can_fd)); + REQUIRE(result.kind == protocol::ProgressKind::complete); + REQUIRE(hp::project_bytes(std::any_cast>(result.value)) == + std::array{10, 20, 30, 40, 50, 60}); + REQUIRE_THROWS_AS(hp::project_bytes({0}), ProtocolError); + + auto stall = + hp::write_joints(1, hp::kMiStallThreshold, {1, 2, 3, 4, 5, 6}, true, "stall_configuration", can_fd); + REQUIRE(stall.frames[0].data[0] == static_cast(hp::kMiStallThreshold | 0x80U)); + REQUIRE(stall.consume(reply(hp::kMiStallThreshold, 5, {2}, true, can_fd)).kind == + protocol::ProgressKind::pending); + REQUIRE_THROWS_AS(stall.consume(reply(hp::kMiStallThreshold, 5, {3}, true, can_fd)), ProtocolError); + } +} + +TEST_CASE("HOP CAN configuration codes and MI 0x35 framing", "[protocol][o6-hop]") { + const uint8_t request_id[] = {0x23, 0x01}; + const uint8_t interface[] = {2, 0, 1, 13}; + const auto parsed = parse_hop_can_configuration(request_id, 2, interface, 4); + REQUIRE(parsed.request_id == 0x123); + REQUIRE(parsed.response_id() == 0x523); + REQUIRE(parsed.interface_mode == HopCanInterfaceMode::kCanFd); + REQUIRE_FALSE(parsed.brs); + REQUIRE(parsed.nominal_bitrate == 1000000); + REQUIRE(parsed.data_bitrate == 100000); + REQUIRE(static_cast(HopCanInterfaceMode::kCan20) == 1); + REQUIRE(static_cast(HopCanInterfaceMode::kCanFd) == 2); + + const uint8_t classic[] = {1, 1, 8, 1}; + const auto classic_config = parse_hop_can_configuration(request_id, 2, classic, 4); + REQUIRE(classic_config.interface_mode == HopCanInterfaceMode::kCan20); + REQUIRE(classic_config.brs); + REQUIRE(classic_config.nominal_bitrate == 100000); + REQUIRE(classic_config.data_bitrate == 8000000); + REQUIRE(decode_hop_nominal_bitrate(1) == 1000000); + REQUIRE(decode_hop_nominal_bitrate(8) == 100000); + REQUIRE(decode_hop_data_bitrate(1) == 8000000); + REQUIRE(decode_hop_data_bitrate(13) == 100000); + + const uint8_t too_large[] = {0xff, 0x03}; + REQUIRE_THROWS_AS(parse_hop_can_configuration(too_large, 2, interface, 4), ProtocolError); + const uint8_t bad_mode[] = {0, 0, 1, 1}; + const uint8_t bad_mode_high[] = {3, 0, 1, 1}; + const uint8_t bad_brs[] = {2, 2, 1, 1}; + REQUIRE_THROWS_AS(parse_hop_can_configuration(request_id, 2, bad_mode, 4), ProtocolError); + REQUIRE_THROWS_AS(parse_hop_can_configuration(request_id, 2, bad_mode_high, 4), ProtocolError); + REQUIRE_THROWS_AS(parse_hop_can_configuration(request_id, 2, bad_brs, 4), ProtocolError); + REQUIRE_THROWS_AS(decode_hop_nominal_bitrate(0), ProtocolError); + REQUIRE_THROWS_AS(decode_hop_nominal_bitrate(9), ProtocolError); + REQUIRE_THROWS_AS(decode_hop_data_bitrate(0), ProtocolError); + REQUIRE_THROWS_AS(decode_hop_data_bitrate(14), ProtocolError); + REQUIRE_THROWS_AS(parse_hop_can_configuration(request_id, 1, interface, 4), ProtocolError); + REQUIRE_THROWS_AS(parse_hop_can_configuration(nullptr, 2, interface, 4), ProtocolError); + + auto request = hp::transaction(1, hp::kMiConfig, 0x00, 2, {}, true, {}, false); + REQUIRE_FALSE(request.frames[0].is_fd); + REQUIRE(request.frames[0].dlc <= 8); + REQUIRE(request.frames[0].data[0] == 0xB5); + REQUIRE(request.frames[0].data[1] == 0x00); + REQUIRE(request.frames[0].data[2] == 0x02); + REQUIRE(request.consume(reply(hp::kMiConfig, 0x00, {0x01, 0x00}, true, false)).kind == + protocol::ProgressKind::complete); + + auto interface_read = hp::transaction(1, hp::kMiConfig, 0x06, 4, {}, true, {}, false); + REQUIRE_FALSE(interface_read.frames[0].is_fd); + REQUIRE(interface_read.frames[0].dlc <= 8); + REQUIRE(interface_read.frames[0].data[0] == 0xB5); + REQUIRE(interface_read.frames[0].data[1] == 0x06); + REQUIRE(interface_read.frames[0].data[2] == 0x04); + + auto mode = hp::transaction(1, hp::kMiConfig, 0x06, 1, {1}, false, {}, false); + REQUIRE_FALSE(mode.frames[0].is_fd); + REQUIRE(mode.frames[0].dlc == 4); + REQUIRE(mode.frames[0].data[0] == 0x35); + REQUIRE(mode.frames[0].data[1] == 0x06); + REQUIRE(mode.frames[0].data[2] == 0x01); + REQUIRE(mode.frames[0].data[3] == 0x01); + + auto save = hp::transaction(1, hp::kMiConfig, 0x1E, 1, {1}, false, {}, true); + REQUIRE(save.frames[0].is_fd); + REQUIRE(save.frames[0].data[0] == 0x35); + REQUIRE(save.frames[0].data[1] == 0x1E); + REQUIRE(save.frames[0].data[2] == 0x01); + REQUIRE(save.frames[0].data[3] == 0x01); + REQUIRE(save.consume(reply(hp::kMiConfig, 0x1E, {0x00}, false, true)).kind == protocol::ProgressKind::complete); +} diff --git a/validation/check_protocol_boundary.py b/validation/check_protocol_boundary.py index 2e95e5e2..474ae915 100644 --- a/validation/check_protocol_boundary.py +++ b/validation/check_protocol_boundary.py @@ -7,7 +7,8 @@ p.add_argument('--compiler', default='c++') a = p.parse_args() entries = ['protocol/transaction.hpp', 'o6/protocol_backend.hpp', 'l6/protocol_backend.hpp', - 'o30/transaction.hpp', 'o30/v25.hpp', 'l30/protocol.hpp', 'l6/hop_protocol.hpp', 'protocol/hop.hpp'] + 'o30/transaction.hpp', 'o30/v25.hpp', 'l30/protocol.hpp', 'l6/hop_protocol.hpp', 'o6/hop_protocol.hpp', + 'protocol/hop.hpp'] # Additional model plans are included once introduced by their migration. for model in ['l20lite', 'l20', 'l30']: for name in ['protocol_backend.hpp', 'transaction.hpp']: