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