From da049250d6fd749e21dddc4dd57ed650b76fe24a Mon Sep 17 00:00:00 2001 From: zhangyunzhen2027 <143870206+zhangyunzhen2027@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:32:38 +0800 Subject: [PATCH 1/6] fix: recover read-only CAN telemetry after disconnects --- CHANGELOG.md | 10 +++ src/openarm_runtime/config.py | 15 ++++ src/openarm_runtime/telemetry.py | 40 +++++++++-- tests/test_can_recovery.py | 120 +++++++++++++++++++++++++++++++ 4 files changed, 179 insertions(+), 6 deletions(-) create mode 100644 tests/test_can_recovery.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 0257a37..54f44ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## Unreleased + +- Recover read-only Classic CAN telemetry after historical warning counters or + disconnections using bounded sessions and interruptible capped retry backoff. + Revalidate all eight motors and firmware ranges on reconnect; require complete + feedback before clearing errors. Preserve strict motion preflight and never + reset interfaces, switch Classic to FD, or send motor-control commands during + recovery. + + ## 0.6.0 — 2026-10-31 - Add the local OpenArm Platform workspace with unchanged control, teleoperation, diff --git a/src/openarm_runtime/config.py b/src/openarm_runtime/config.py index 0e43bb8..a8c29d7 100644 --- a/src/openarm_runtime/config.py +++ b/src/openarm_runtime/config.py @@ -64,6 +64,21 @@ def require_classic_link(link: dict): raise RuntimeError("Expected healthy Classic 1 Mbps, fd off, restart-ms 0; no automatic reconfiguration") +def require_classic_read_link(link: dict): + """Permit bounded reads to clear historical warnings, never reconfigure a bus. + + Motion still uses require_classic_link, including its zero-error requirement. + Passive, bus-off, down and unknown states cannot start a read attempt. + """ + info = link.get("linkinfo", {}).get("info_data", {}) + if info.get("state") not in ("ERROR-ACTIVE", "ERROR-WARNING"): + raise RuntimeError("Classic read requires ERROR-ACTIVE or ERROR-WARNING; no automatic restart") + normalized = {**link, "linkinfo": {**link.get("linkinfo", {}), "info_data": { + **info, "state": "ERROR-ACTIVE", "berr_counter": {"tx": 0, "rx": 0}, + }}} + require_classic_link(normalized) + + @contextmanager def bus_lease(interface: str, exclusive: bool): """Advisory lock shared by our viewer/check/control processes, not third-party tools.""" diff --git a/src/openarm_runtime/telemetry.py b/src/openarm_runtime/telemetry.py index b19e8b3..35a1ee1 100644 --- a/src/openarm_runtime/telemetry.py +++ b/src/openarm_runtime/telemetry.py @@ -302,17 +302,20 @@ def poll( max_cycles: int | None = None, ): from contextlib import ExitStack - from openarm_runtime.config import bus_lease, require_classic_link + from openarm_runtime.config import bus_lease, require_classic_read_link reader = None ownership = ExitStack() try: ownership.enter_context(bus_lease(interface, exclusive=False)) - reader = ReadOnlyCAN(interface) host = inspect_link(interface) if frame_format == "classic": - require_classic_link(host) + require_classic_read_link(host) + reader = ReadOnlyCAN(interface) with shared.lock: + shared.baud_codes.clear() + shared.ranges.clear() + shared.frame_format = "preflight" shared.link = host shared.requested_format = frame_format shared.message = "只读检查每个电机的 can_br…" @@ -355,10 +358,14 @@ def poll( else: shared.rx_classic += 1 received += 1 - silent_cycles = silent_cycles + 1 if received == 0 else 0 + silent_cycles = silent_cycles + 1 if received < len(IDS) else 0 if silent_cycles >= 3: - raise RuntimeError("No motor replies for three cycles; polling stopped") + raise RuntimeError("Incomplete motor replies for three cycles; polling stopped") with shared.lock: + if received == len(IDS): + shared.error = "" + else: + shared.error = "Incomplete motor feedback; waiting for all eight motors" mode = ( "兼容模式:Classic请求 / 混合回复,非全FD验收" if frame_format == "compat" @@ -380,6 +387,27 @@ def poll( ownership.close() +def poll_reconnecting(interface, shared, stop, *, frame_format="auto"): + """Retry read-only sessions with interruptible, capped exponential backoff. + + Each poll closes its socket and releases ownership before the retry wait. + Old samples retain their timestamps; an error clears only on a complete cycle. + """ + delay = 1.0 + while not stop.is_set(): + before = shared.responses + poll(interface, shared, stop, frame_format=frame_format) + if stop.is_set(): + return + if shared.responses > before: + delay = 1.0 + with shared.lock: + shared.message = f"只读连接中断;{delay:g} 秒后重试(不重置总线)" + if stop.wait(delay): + return + delay = min(delay * 2, 30.0) + + class ArmConnection: """One independent read worker per bus; restarting one never touches the other.""" @@ -397,7 +425,7 @@ def restart(self): self.shared = Telemetry() self.stop = threading.Event() self.worker = threading.Thread( - target=poll, + target=poll_reconnecting, args=(self.interface, self.shared, self.stop), kwargs={"frame_format": self.frame_format}, daemon=True, diff --git a/tests/test_can_recovery.py b/tests/test_can_recovery.py new file mode 100644 index 0000000..f8ed2b1 --- /dev/null +++ b/tests/test_can_recovery.py @@ -0,0 +1,120 @@ +"""Offline regressions: no physical CAN access.""" +from contextlib import nullcontext +import copy +import threading +import time +import unittest +from unittest.mock import Mock, patch +from openarm_runtime.config import require_classic_link, require_classic_read_link +from openarm_runtime.telemetry import MotorRange, MotorState, Telemetry, poll, poll_reconnecting + + +def link(): + return dict(flags=['UP'], mtu=16, linkinfo=dict(info_data=dict( + state='ERROR-WARNING', bittiming=dict(bitrate=1000000), + ctrlmode=[], restart_ms=0, berr_counter=dict(tx=124, rx=0)))) + + +class RecoveryTests(unittest.TestCase): + def test_warning_allowed_only_for_reads_without_mutating_evidence(self): + host = link() + original = copy.deepcopy(host) + require_classic_read_link(host) + self.assertEqual(host, original) + with self.assertRaises(RuntimeError): + require_classic_link(host) + + def test_unsafe_configuration_and_states_still_rejected(self): + for key, value in [('state', 'BUS-OFF'), ('state', 'ERROR-PASSIVE'), + ('state', 'STOPPED'), ('state', 'unknown'), + ('ctrlmode', ['FD']), ('restart_ms', 100), + ('bittiming', {'bitrate': 500000})]: + host = link() + host['linkinfo']['info_data'][key] = value + with self.subTest(key=key, value=value), self.assertRaises(RuntimeError): + require_classic_read_link(host) + for key, value in [('flags', []), ('mtu', 72)]: + host = link() + host[key] = value + with self.assertRaises(RuntimeError): + require_classic_read_link(host) + + def run_poll(self, shared, reader, host=None, cycles=1): + with patch('openarm_runtime.config.bus_lease', return_value=nullcontext()), \ + patch('openarm_runtime.telemetry.inspect_link', return_value=host or link()), \ + patch('openarm_runtime.telemetry.ReadOnlyCAN', return_value=reader) as factory: + poll('can0', shared, threading.Event(), frame_format='classic', max_cycles=cycles) + return factory + + def reader(self): + reader = Mock() + reader.read_parameter.return_value = 4 + reader.read_range.return_value = MotorRange(12.5, 45, 54) + reader.refresh.side_effect = lambda i, limits: MotorState(i, 0, 0, 0, 24, 24, 0, time.monotonic()) + return reader + + def test_warning_recovers_with_complete_new_feedback(self): + shared = Telemetry(error='disconnected', baud_codes={99: 9}) + reader = self.reader() + self.run_poll(shared, reader) + self.assertEqual(shared.error, '') + self.assertEqual(set(shared.states), set(range(1, 9))) + self.assertEqual(shared.baud_codes, dict.fromkeys(range(1, 9), 4)) + self.assertEqual(reader.frame_format, 'classic') + reader.close.assert_called_once() + + def test_wrong_mode_rejected_before_socket_or_send(self): + host = link() + host['mtu'] = 72 + reader = self.reader() + shared = Telemetry() + self.run_poll(shared, reader, host).assert_not_called() + reader.read_parameter.assert_not_called() + self.assertTrue(shared.error) + + def test_missing_one_motor_keeps_error_and_closes(self): + shared = Telemetry(error='disconnected') + reader = self.reader() + refresh = reader.refresh.side_effect + reader.refresh.side_effect = lambda i, limits: None if i == 8 else refresh(i, limits) + self.run_poll(shared, reader, cycles=3) + self.assertIn('three cycles', shared.error) + self.assertNotIn(8, shared.states) + reader.close.assert_called_once() + + def test_retry_backoff_capped_and_stop_interrupts_wait(self): + shared = Telemetry() + stop = Mock() + stop.is_set.return_value = False + stop.wait.side_effect = [False] * 7 + [True] + with patch('openarm_runtime.telemetry.poll') as attempt: + poll_reconnecting('can0', shared, stop, frame_format='classic') + self.assertEqual(attempt.call_count, 8) + self.assertEqual([c.args[0] for c in stop.wait.call_args_list], [1, 2, 4, 8, 16, 30, 30, 30]) + self.assertTrue(all(c.kwargs['frame_format'] == 'classic' for c in attempt.call_args_list)) + + def test_reconnect_after_failure_clears_error(self): + shared = Telemetry() + first, second = self.reader(), self.reader() + first.read_parameter.side_effect = OSError('unplugged') + stop = Mock() + stop.is_set.return_value = False + def wait(delay): + first.close.assert_called_once() + self.assertIn('unplugged', shared.error) + return False + stop.wait.side_effect = wait + original_poll = poll + readers = iter([first, second]) + def attempt(interface, shared, event, **kwargs): + reader = next(readers) + with patch('openarm_runtime.config.bus_lease', return_value=nullcontext()), \ + patch('openarm_runtime.telemetry.inspect_link', return_value=link()), \ + patch('openarm_runtime.telemetry.ReadOnlyCAN', return_value=reader): + original_poll(interface, shared, threading.Event(), max_cycles=1, **kwargs) + if reader is second: + stop.is_set.return_value = True + with patch('openarm_runtime.telemetry.poll', side_effect=attempt): + poll_reconnecting('can0', shared, stop, frame_format='classic') + self.assertEqual(shared.error, '') + second.close.assert_called_once() From c90c5689aacd639fcd126485e0e3144b422ddb20 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 1 Nov 2026 16:43:24 +0800 Subject: [PATCH 2/6] chore: preserve local motor controls on v0.6.0 baseline --- CHANGELOG.md | 10 -- README.md | 14 +- docs/api.md | 7 +- docs/wiki/Architecture.md | 81 --------- docs/wiki/CLI-Reference.md | 212 ---------------------- docs/wiki/Home.md | 54 ------ docs/wiki/Installation.md | 215 ----------------------- docs/wiki/Operations.md | 162 ----------------- docs/wiki/Python-API.md | 273 ----------------------------- docs/wiki/Quick-Start.md | 96 ---------- docs/wiki/Remote-Access.md | 152 ---------------- docs/wiki/Troubleshooting.md | 170 ------------------ docs/wiki/_Footer.md | 1 - docs/wiki/_Sidebar.md | 13 -- docs/workstation.md | 2 +- src/openarm_runtime/__main__.py | 9 +- src/openarm_runtime/arm.py | 91 ++++++++-- src/openarm_runtime/calibration.py | 31 +++- src/openarm_runtime/limits.py | 30 ++++ src/openarm_runtime/motion.py | 113 ++++++++++++ src/openarm_runtime/panel.py | 86 ++++++--- src/openarm_runtime/report.py | 58 +++++- src/openarm_runtime/transport.py | 11 +- tests/test_arm.py | 1 + tests/test_calibration.py | 32 ++++ tests/test_manual_limits.py | 102 +++++++++++ tests/test_motion.py | 122 +++++++++++++ tests/test_queued_report.py | 66 +++++++ tests/test_runtime.py | 7 +- 29 files changed, 727 insertions(+), 1494 deletions(-) delete mode 100644 docs/wiki/Architecture.md delete mode 100644 docs/wiki/CLI-Reference.md delete mode 100644 docs/wiki/Home.md delete mode 100644 docs/wiki/Installation.md delete mode 100644 docs/wiki/Operations.md delete mode 100644 docs/wiki/Python-API.md delete mode 100644 docs/wiki/Quick-Start.md delete mode 100644 docs/wiki/Remote-Access.md delete mode 100644 docs/wiki/Troubleshooting.md delete mode 100644 docs/wiki/_Footer.md delete mode 100644 docs/wiki/_Sidebar.md create mode 100644 src/openarm_runtime/limits.py create mode 100644 src/openarm_runtime/motion.py create mode 100644 tests/test_manual_limits.py create mode 100644 tests/test_motion.py create mode 100644 tests/test_queued_report.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 54f44ef..0257a37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,15 +1,5 @@ # Changelog -## Unreleased - -- Recover read-only Classic CAN telemetry after historical warning counters or - disconnections using bounded sessions and interruptible capped retry backoff. - Revalidate all eight motors and firmware ranges on reconnect; require complete - feedback before clearing errors. Preserve strict motion preflight and never - reset interfaces, switch Classic to FD, or send motor-control commands during - recovery. - - ## 0.6.0 — 2026-10-31 - Add the local OpenArm Platform workspace with unchanged control, teleoperation, diff --git a/README.md b/README.md index eedaf40..db4e6d6 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,6 @@ the CLI for live inspection and user-operated control. Python 3.12 · MIT · Linux SocketCAN for followers · Independent community project -**[中文使用文档 / Wiki](https://github.com/TCXM/openarm-runtime/wiki/Home)** · [常用命令](https://github.com/TCXM/openarm-runtime/wiki/CLI-Reference) · [Python API](https://github.com/TCXM/openarm-runtime/wiki/Python-API) · [Mac / Windows 远程访问](https://github.com/TCXM/openarm-runtime/wiki/Remote-Access) - ## Install only what you need Create a Python 3.12 virtual environment, then install from a release tag: @@ -320,12 +318,20 @@ readback test on the development rig; quantified accuracy and repeatability are not yet established. Read the [operator guide](docs/calibration.md) for the required starting pose, motion sequence, stop behavior and partial-write recovery. +The local motor-control panel also retains **自动标定(不写零位)**, available +as `calibrate --no-write-zero` or `calibrate_arm(..., write_zero=False)`. It runs +the same stop-seeking motion and disables at completion, preserving encoder zeros. +The final pose need not read as zero in the existing encoder coordinates. + ## Scope The working baseline covers eight motors per follower arm, Classic CAN, whole-arm hold/relative targets, two STS3215 leader buses and virtual pose mapping. -Manual control uses validated fixed gains, ±30° relative offsets and -0.1–5°/s target speed. See [validation](docs/validation.md) for measured evidence. +The local manual-control panel retains calibrated absolute J1–J7 angle sliders +and a ±30° relative gripper offset, with 0.1–5°/s target speed and 10°/s² +acceleration smoothing. Its fixed gains, feedback checks, queued reports and +read-only CAN reconnect are retained. The default `hold_arm()` API keeps its +±30° relative offsets. See [validation](docs/validation.md) for measured evidence. Long-duration dual-arm acceptance, collision avoidance, quantified calibration accuracy and long-term reliability are future work. Firmware encoding diff --git a/docs/api.md b/docs/api.md index 70904b6..7ff0107 100644 --- a/docs/api.md +++ b/docs/api.md @@ -86,10 +86,15 @@ your hardware has been separately verified for this behavior. ## Automatic follower calibration (v0.2.0) `calibrate_arm(profile, side, *, cancelled, record, publish, progress, -allow_unreadable_mode=False)` synchronously performs a complete single-arm v2 +allow_unreadable_mode=False, write_zero=True)` synchronously performs a complete single-arm v2 calibration and writes hardware zeros. `side` is `left` or `right`. It owns the bus lease, preflight, enable, motion and disable; stop any reader first. +The retained local `write_zero=False` option runs the same physical trajectory, +then verifies the disabled end pose without writing any encoder zeros. It still +requires the calibration reference starting pose; the end pose may have nonzero +readings in the preserved encoder coordinates. CLI: `calibrate --no-write-zero`. + It returns `{motor_id: raw_zero_radians}` for IDs1–8 (the pre-write encoder frame). `cancelled()` defaults to false; `record(event)`, `publish(states)` and `progress(message)` default to no-ops. For real operation, supply a durable diff --git a/docs/wiki/Architecture.md b/docs/wiki/Architecture.md deleted file mode 100644 index 1b05554..0000000 --- a/docs/wiki/Architecture.md +++ /dev/null @@ -1,81 +0,0 @@ -# 库与统一平台架构 - -适用版本:**v0.6.0**。项目既是可供 Python 程序导入的库,也是一个通过浏览器操作的本地工作台。日常使用只需启动统一入口;各模块仍保留独立 CLI,供开发和诊断使用。 - -[返回首页](Home.md) · [Python API](Python-API.md) · [常用命令](CLI-Reference.md) - -## 一个浏览器地址 - -```mermaid -flowchart LR - Client["Mac / Windows / Linux 浏览器"] -->|"http://127.0.0.1:8888"| SSH["本机 SSH 转发"] - subgraph Workstation["连接硬件的 Linux 工作站"] - SSH -->|"工作站 127.0.0.1:8888"| Platform["NiceGUI / FastAPI / Uvicorn"] - Platform --> Proxy["aiohttp HTTP / WebSocket 代理"] - Proxy --> Control["电机控制 · Viser"] - Proxy --> Teleop["遥操 · Viser"] - Proxy --> Tactile["触觉 · 双嵌套视图"] - Proxy --> Video["视觉 · RGB / 深度 / 腕部"] - Manager["子进程与资源所有权管理"] -.-> Control - Manager -.-> Teleop - Manager -.-> Tactile - Manager -.-> Video - Control --> CAN["SocketCAN / 从臂电机"] - Teleop --> CAN - Teleop --> Leader["主臂串口"] - Tactile --> Sensors["触觉串口"] - Video --> Cameras["相机 / OpenNI2 helper"] - end -``` - -在工作站本机浏览时直接访问平台,不需要 SSH。异地浏览只转发 8888,包括视频图像、Viser WebSocket 及两个嵌套触觉视图。Mac 和 Windows 不承担 Linux CAN 控制;它们作为终端和浏览器客户端。详见[远程访问](Remote-Access.md)。 - -## 使用的框架 - -| 组件 | 职责 | -| --- | --- | -| NiceGUI 3.18.0 | 导航、状态、确认对话框和模块工作区 | -| FastAPI / Uvicorn | 平台 ASGI 应用、HTTP 服务与生命周期 | -| aiohttp 3.14.5 | 复用上游连接,代理 HTTP、流式图像和 WebSocket | -| Viser | 机器人姿态、电机控制、遥操和触觉 3D 页面 | -| Flask | 独立视觉模块的网页和帧接口 | -| ServiceManager | 按外部配置启动子进程,区分自有与外部进程,串行切换控制模式 | - -成熟框架承担网络连接和界面事件;硬件控制、设备租约、退出失能仍由各模块维护。网页切到触觉或视觉时会保留已打开模块的视图和连接。电机控制与遥操是互斥模式,切换时先正常停止当前自有服务,再启动另一模式。 - -## 默认端口与页面 - -| 用途 | 默认工作站端口 | 统一入口路径 | -| --- | --- | --- | -| 平台入口 | 8888 | `/` | -| 电机控制 | 8893 | `/apps/control/` | -| 遥操 | 8890 | `/apps/teleop/` | -| 触觉主页面 | 8891 | `/apps/tactile/` | -| 两个触觉内部视图 | 8901、8902 | 由触觉页面经平台加载 | -| 视觉 | 5003 | `/apps/vision/` | - -子服务在内部仍使用独立端口,以保持设备和退出流程隔离;用户只需记住平台入口和一条 SSH 隧道。端口可在外部 `platform.json` 中修改,所有入口、子服务及嵌套视图端口必须互不冲突。 - -## 所有权与启动行为 - -启动平台会检查已配置端口,启动缺失且配置了命令的服务;电机控制和遥操只选择一个启动,另一个待命。服务进程启动不等于电机使能或开始跟随,这些动作由操作者显式触发。 - -已经存在的端口监听者被标为外部服务。平台可复用其页面,但不会因此取得其进程所有权,也不会关闭该进程。需要平台管理模式切换时,先按原启动方式正常停止旧控制器。`--attach-only` 只连接现有端点,不启动或停止子服务。 - -平台仅负责关闭自己启动的进程,优先走正常退出路径。控制服务若不能正常退出,不会通过强制结束来继续启动竞争控制器。平台进程应为单实例、单 worker;不要用开发热重载器接管真实硬件。 - -端口可连接只表示有监听者,不证明硬件健康或一定是预期程序。具体状态仍需查看模块页面、采样时间和日志。 - -## 配置与代码边界 - -- `openarm_runtime`:从臂链路检查、遥测、控制和标定生命周期。 -- `openarm_leader`:主臂只读采集、软件标定、显示映射和跟随界面。 -- `openarm_tactile`:串口触觉采集与可选可视化。 -- `openarm_video`:RGB/深度采集、最新帧快照、编码和网页。 -- `openarm_platform`:服务协调、统一代理与导航工作区。 - -core 不安装 GUI、串口 SDK 或 CAN 原生绑定;按用途选择 extras。模块导入、配置加载和 CLI 帮助不会打开硬件。模型、SDK、机器设备路径、标定、日志和报告都存放在仓库外。 - -统一入口限定本机访问,并检查 Host / Origin;远程客户端通过 SSH 隧道访问。它没有面向公网的用户认证,也不把内部 `/api/*` 定义为公共控制协议。业务集成使用 [Python API](Python-API.md),日常操作使用网页。 - -配置示例:[platform.example.json](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/platform.example.json)。实现与限制:[平台文档](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/docs/platform.md)、[验证记录](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/docs/validation.md)。 diff --git a/docs/wiki/CLI-Reference.md b/docs/wiki/CLI-Reference.md deleted file mode 100644 index 174bd14..0000000 --- a/docs/wiki/CLI-Reference.md +++ /dev/null @@ -1,212 +0,0 @@ -# 命令行参考 - -适用版本:**v0.6.0**。以下命令在连接硬件的 **Linux 工作站**及已安装相应 extras 的 Python 3.12 环境内执行。Mac/Windows 远程访问命令见[远程访问](Remote-Access.md)。 - -## 入口与参数位置 - -```sh -openarm-runtime --help -python -m openarm_runtime --help -openarm-runtime platform --help -``` - -两个入口等价。`--help` 只显示帮助,不打开设备。`--config` 是全局参数,必须放在子命令前;`--profile` 是 `platform` 或 `video` 自己的参数。 - -```sh -openarm-runtime --config ~/.config/openarm/classic.json check -openarm-runtime platform --profile ~/.config/openarm-runtime/platform.json -``` - -将 `YOUR_*`、`/path/to/...` 替换为本机值。配置文件的用途见[安装与配置](Installation.md)。 - -| 命令 | 用途 | 运行时对硬件的影响 | -| --- | --- | --- | -| `platform` | 统一网页入口 | 按配置启动/复用服务;不自动使能电机或开始跟随 | -| `prepare` | 下载并校验固定版本的模型资源 | 不打开硬件 | -| `check` | 双 CAN 总线和电机只读检查 | 打开总线并查询;不发送运动控制 | -| `view` | 从臂反馈三维显示 | 只读 CAN | -| `panel` | 手动控制及自动标定面板 | 启动时只读;操作按钮可使能、移动、写零位 | -| `leader` | 主臂读取、软件标定、姿态预览 | 读取主臂串口;加 `--follow` 后提供人工启动的真实跟随 | -| `calibrate` | 单臂自动硬件零位标定 | **执行命令即进入运动及写零位流程** | -| `video` | RGB/深度画面 | 真实配置打开相机;`--simulate` 仅生成软件图像 | -| `tactile` | 触觉采集和可视化 | 真实配置打开串口;`--simulate` 不打开硬件 | - -v0.6.0 没有独立的 `hold` 子命令。手动保持用 `panel`;程序集成使用 [`hold_arm`](Python-API.md)。 - -## platform:统一网页 - -日常使用只启动这一项: - -```sh -openarm-runtime platform --profile ~/.config/openarm-runtime/platform.json -``` - -在工作站浏览器打开 **http://127.0.0.1:8888**。已有开发环境也可在仓库根目录执行 `python3 run_platform.py`;该脚本使用仓库 `.venv` 和上述默认配置路径。 - -| 参数 | 默认值 | 说明 | -| --- | --- | --- | -| `--profile PATH` | 不加载文件 | 指定服务命令、端口及日志位置的外部 JSON | -| `--port PORT` | 配置值,未配置时 `8888` | 覆盖浏览器入口端口 | -| `--attach-only` | 关闭 | 只连接现有服务,不启动或停止进程 | - -```sh -# 只查看已经运行的服务 -openarm-runtime platform --profile ~/.config/openarm-runtime/platform.json --attach-only - -# 入口换到 8889;远程 SSH 转发的目标端口也要对应修改 -openarm-runtime platform --profile ~/.config/openarm-runtime/platform.json --port 8889 -``` - -不传 `--profile` 时只有默认端口映射,没有自动发现设备或推断启动命令的能力。内部模块仍使用独立进程与端口,浏览器只需访问统一入口。 - -## prepare:模型资源 - -```sh -openarm-runtime prepare --asset-root ~/.cache/openarm-models -``` - -`--asset-root PATH` 必填。命令需要网络下载固定来源的模型并验证内容;资源保存在仓库外。`view`、`panel`、`leader` 的 `--asset-root` 指向同一位置。 - -## check:只读 CAN 检查 - -```sh -openarm-runtime --config ~/.config/openarm/classic.json check -``` - -无额外参数。输出 JSON,包含总检查结果、左右映射确认标志和各总线检查信息;通过时退出码为 `0`,失败为 `1`。该命令要求电机处于失能状态。先停止占用总线的控制操作,再检查。 - -`check` 虽然只读,仍会检查原生 SDK 编码器,须安装 `follower` extra 和 OpenArm CAN SDK 1.4.1;它不发送编码后的控制帧。仅需 core 的 `ArmConnection` 只读遥测是另一个接口,见 [Python API](Python-API.md)。 - -它检查健康的 Classic CAN、1 Mbps、FD 关闭、`restart-ms 0`,不自动修改链路。`mapping_verified` 仍需操作人员根据接线确认;检查通过不等于左右机械映射已确认。 - -## view 与 panel:从臂查看和控制 - -```sh -# 单独查看从臂反馈 -openarm-runtime --config ~/.config/openarm/classic.json view \ - --asset-root ~/.cache/openarm-models --port 8890 - -# 单独打开控制面板(不要与平台管理的同一模块同时运行) -openarm-runtime --config ~/.config/openarm/classic.json panel \ - --asset-root ~/.cache/openarm-models \ - --report-root ~/openarm-reports --port 8893 -``` - -| 参数 | `view` | `panel` | -| --- | --- | --- | -| 全局 `--config PATH` | 必填 | 必填 | -| `--asset-root PATH` | 必填 | 必填 | -| `--port PORT` | 默认 `8890` | CLI 默认 `8890`;平台示例显式使用 `8893` | -| `--report-root PATH` | 不支持 | 必填,保存控制/标定报告 | - -`panel` 启动时只读,使能前关节偏移滑条不可操作。执行“使能并保持”后才保持当前姿态并响应偏移滑条。页面中的“自动标定”会运行硬件零位标定。操作步骤见[操作指南](Operations.md)。 - -## leader:主臂预览与真实跟随 - -只读取主臂、进行软件标定与虚拟姿态预览: - -```sh -openarm-runtime leader \ - --left-port /dev/serial/by-id/YOUR_LEFT_LEADER \ - --right-port /dev/serial/by-id/YOUR_RIGHT_LEADER \ - --calibration ~/.config/openarm/leader.json \ - --asset-root ~/.cache/openarm-models --port 8890 -``` - -提供人工启动的真实跟随功能: - -```sh -openarm-runtime --config ~/.config/openarm/classic.json leader \ - --left-port /dev/serial/by-id/YOUR_LEFT_LEADER \ - --right-port /dev/serial/by-id/YOUR_RIGHT_LEADER \ - --calibration ~/.config/openarm/leader.json \ - --asset-root ~/.cache/openarm-models \ - --follow --report-root ~/openarm-reports --port 8890 -``` - -| 参数 | 要求/默认值 | -| --- | --- | -| `--left-port PATH`、`--right-port PATH` | 均必填;两个主臂串口的稳定设备路径 | -| `--calibration PATH` | 必填;主臂自然零位和夹爪端点的软件标定文件 | -| `--asset-root PATH` | 必填;已准备的模型目录 | -| `--port PORT` | 默认 `8890` | -| `--follow` | 默认关闭;加入真实从臂跟随控件,**不会自动开始跟随** | -| `--report-root PATH` | 使用 `--follow` 时必填 | -| 全局 `--config PATH` | 使用 `--follow` 时必填,位于 `leader` 前 | - -主臂读取不会写舵机寄存器。主臂软件标定保存在 JSON,与从臂硬件零位标定是两种操作。跟随需要完整且保存的标定、有效反馈和可独占的从臂总线。 - -## calibrate:从臂硬件零位 - -**这是运动命令,不用于测试安装是否成功。** 先完成接线确认、参考姿态、卸载负载、清空运动范围及失能后的支撑准备,再停止所选总线上的读者/控制器。 - -```sh -openarm-runtime --config ~/.config/openarm/classic.json calibrate \ - --side right --report-root ~/openarm-reports -``` - -| 参数 | 要求/默认值 | -| --- | --- | -| 全局 `--config PATH` | 必填 | -| `--side left\|right` | 必填,一次一臂 | -| `--report-root PATH` | 必填 | -| `--allow-unreadable-mode` | 默认关闭;仅明确允许已验证硬件的 RID10 读取超时 | - -成功流程包含寻止挡、回计算零位、失能、写入并验证 8 个电机零位。按 `Ctrl+C` 请求取消和失能。部分写入后发生错误不会自动回滚;检查报告及实际读回再决定后续处理。可读出的非 MIT 模式即使加该选项也会被拒绝。 - -完整步骤、执行边界和恢复要求见[硬件标定说明](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/docs/calibration.md)。 - -## video:视觉与模拟 - -```sh -# 实机:外部配置包含头部、深度和腕部相机 -openarm-runtime video --profile ~/.config/openarm/video-runtime.json --port 5003 - -# 离线:不打开相机 -openarm-runtime video --simulate --port 5004 -``` - -| 参数 | 默认值/说明 | -| --- | --- | -| `--profile PATH` | 外部相机配置;未使用模拟时必填 | -| `--simulate` | 生成软件 RGB/深度画面;可配合配置文件选择画面布局 | -| `--port PORT` | 默认 `5003` | - -离线独立页为 http://127.0.0.1:5004。平台已管理视觉服务时,使用统一入口中的“视觉”,无需另启同一组设备。 - -## tactile:触觉与双传感器 - -```sh -# 单个真实传感器:device-id 需匹配该传感器,已验证设备使用 2 -openarm-runtime tactile --device /dev/serial/by-id/YOUR_TACTILE \ - --device-id 2 --port 8891 - -# 两个真实传感器同页显示 -openarm-runtime tactile \ - --device /dev/serial/by-id/YOUR_TACTILE_A \ - --right-device /dev/serial/by-id/YOUR_TACTILE_B \ - --device-id 2 --port 8891 - -# 单个模拟传感器,不打开串口 -openarm-runtime tactile --simulate --port 8892 -``` - -| 参数 | 默认值/约束 | -| --- | --- | -| `--device PATH` 或 `--simulate` | 必选其一,互斥 | -| `--right-device PATH` | 第二个传感器,必须配合 `--device`,且路径不同 | -| `--port PORT` | 默认 `8891`;双传感器时最大为 `65524` | -| `--baudrate BAUD` | 默认 `921600`,必须为正整数 | -| `--device-id ID` | 默认 `1`,范围 `1–255`;是通信地址,不是串口编号 | - -`--right-device` 是保留的参数名,表示并排显示的第二路。本项目已验证安装中,**两路触觉均属于左臂,右臂没有触觉传感器**。双路共用命令中的波特率和设备地址。 - -双路独立服务还使用主端口 `+10/+11`,默认是 `8901/8902`,需同时空闲;通过平台访问时这些连接全部由 `8888` 转发。力值为原始 counts,未标定为牛顿。 - -## 端口与停止 - -网页端口参数范围为 `1024–65535`,平台端口、各模块及嵌套视图端口必须互不冲突。`Ctrl+C` 或 `SIGTERM` 走正常清理流程;退出 SSH 转发或关闭浏览器不等于停止远端平台。 - -下一步:[操作指南](Operations.md) · [Mac/Windows 远程访问](Remote-Access.md) · [故障排查](Troubleshooting.md) - -参数依据:[v0.6.0 CLI 实现](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/src/openarm_runtime/__main__.py)。 diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md deleted file mode 100644 index d0e4bcf..0000000 --- a/docs/wiki/Home.md +++ /dev/null @@ -1,54 +0,0 @@ -# OpenArm Runtime 使用文档 - -**适用版本:[v0.6.0](https://github.com/TCXM/openarm-runtime/releases/tag/v0.6.0)** · Python 3.12 · Linux 硬件工作站 · Mac / Windows 浏览器客户端 - -OpenArm Runtime 将电机控制、主臂遥操、触觉和视觉放在同一个工作区。日常使用只需启动 `openarm-runtime platform`,访问 **http://127.0.0.1:8888**;从其他电脑访问时,只转发这一个端口。 - -这是 `TCXM/openarm-runtime` 社区项目的使用文档,说明本项目的已发布功能。原生 CAN SDK、模型等上游组件的来源见 [第三方说明](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/THIRD_PARTY.md)。 - -## 从这里开始 - -| 你想完成什么 | 阅读页面 | -| --- | --- | -| 已装好工作站,启动并查看全部模块 | [快速上手](Quick-Start.md) | -| 在新机器安装、选择依赖、准备配置 | [安装与配置](Installation.md) | -| 查启动、查看、模拟、标定等命令 | [CLI 命令参考](CLI-Reference.md) | -| 把库接入自己的 Python 项目 | [Python API](Python-API.md) | -| 按流程使用电机、遥操、触觉和相机 | [日常操作](Operations.md) | -| 在 Mac / Windows 打开实时网页、查看日志 | [终端与远程访问](Remote-Access.md) | -| 处理 CAN、端口、串口和腕部相机故障 | [故障排查](Troubleshooting.md) | -| 理解单端口、进程和各个库的关系 | [架构与库](Architecture.md) | - -## 常用命令速查 - -以下启动命令在**已配置好的 Linux 工作站**执行。首次使用先完成 [安装与配置](Installation.md)。 - -```bash -# 使用安装了运行库及所需 extras 的 Python 环境。 -source ~/.venvs/openarm/bin/activate - -# 日常入口:电机、遥操、触觉、视觉。 -openarm-runtime platform --profile ~/.config/openarm-runtime/platform.json -``` - -在 **Mac Terminal / Windows PowerShell** 建立转发,保留此终端运行: - -```sh -ssh -N -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -L 127.0.0.1:8888:127.0.0.1:8888 USER@WORKSTATION -``` - -将 `USER`、`WORKSTATION` 替换为工作站账号和主机名或 IP,然后在客户端浏览器打开 **http://127.0.0.1:8888**。完整登录、打开浏览器和排错命令见 [远程访问](Remote-Access.md)。 - -## 使用范围 - -- 启动平台或打开电机面板不会自动使能电机;启动后的硬件读取由所配置的子服务决定。 -- 电机控制与遥操互斥;触觉和视觉可以同时查看。切换方式见 [日常操作](Operations.md)。 -- `calibrate` 会运动并写入硬件零位;`hold_arm` 会使能电机。命令与 API 页面分别标出了这些操作。 -- 一台 Mac / Windows 电脑作为浏览器客户端时,只需要浏览器和 SSH 客户端;硬件 SDK 与设备配置留在 Linux 工作站。 -- 单端口指浏览器访问入口。各模块仍使用工作站内部端口,平台统一代理页面、图像和 WebSocket。 - -## 版本与维护 - -安装示例固定在 v0.6.0;开发分支可能增加不同功能。Python API 接入应固定版本。参见 [变更记录](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/CHANGELOG.md)、[验证记录](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/docs/validation.md) 和 [问题反馈](https://github.com/TCXM/openarm-runtime/issues)。 - -在线阅读:[GitHub Wiki](https://github.com/TCXM/openarm-runtime/wiki)。本目录保留文档源文件,README 顶部提供 Wiki 入口。文档随代码审查和维护;升级版本时同步核对安装标签、命令参数和 API 契约。 diff --git a/docs/wiki/Installation.md b/docs/wiki/Installation.md deleted file mode 100644 index a38dc3c..0000000 --- a/docs/wiki/Installation.md +++ /dev/null @@ -1,215 +0,0 @@ -# 安装与配置 - -[返回首页](Home.md) · [快速开始](Quick-Start.md) · [故障排查](Troubleshooting.md) - -本文对应 **v0.6.0 / Python 3.12**。连接机器人、相机和传感器的服务运行在 Linux 工作站;Mac 和 Windows 可以只安装 SSH 客户端并用浏览器访问,无需在客户端安装 Python、CAN SDK 或本项目。远程访问见 [Mac / Windows 连接](Remote-Access.md)。 - -## 1. 安装发布版 - -在 Linux 工作站上准备 Python 3.12 和 Git,再创建独立环境: - -```sh -mkdir -p ~/.venvs -python3.12 -m venv ~/.venvs/openarm -source ~/.venvs/openarm/bin/activate -python -m pip install "openarm-runtime @ git+https://github.com/TCXM/openarm-runtime.git@v0.6.0" -python -c 'import openarm_runtime; print(openarm_runtime.__version__)' -openarm-runtime --help -``` - -本项目通过 GitHub 标签与 [Release 附件](https://github.com/TCXM/openarm-runtime/releases/tag/v0.6.0)分发。使用标签可固定项目版本;仓库内的 `uv.lock` 还固定了开发环境的依赖版本。导入核心模块或查看帮助不会打开硬件。 - -### 按需要选择依赖 - -| 安装项 | 用途 | 额外要求 | -| --- | --- | --- | -| 无 extra | 配置、状态类型、控制与映射 API | 具体硬件操作时才需要对应依赖 | -| `platform` | NiceGUI 总入口、HTTP / WebSocket 代理 | 仍需安装各子模块依赖 | -| `leader` | Feetech STS3215 串口读取 | 串口访问权限 | -| `viewer` | Viser 机器人与触觉三维界面 | 机器人视图需要模型资源 | -| `tactile` | Paxini 68 点串口采集 | 社区 Paxini SDK、串口权限 | -| `video` | RGB / 深度采集和网页 | 深度另需匹配的 OpenNI2 SDK / helper | -| `follower` | OpenArm 从臂 Classic CAN | Linux SocketCAN、原生 OpenArm CAN SDK 1.4.1 | - -例如安装总入口、主臂预览、触觉和视觉: - -```sh -python -m pip install "openarm-runtime[platform,leader,viewer,tactile,video] @ git+https://github.com/TCXM/openarm-runtime.git@v0.6.0" -``` - -要使用电机控制和实体跟随,还需完成下一节。仅安装 `[platform]` 不会自动装齐相机、串口和电机 SDK。 - -## 2. 电机控制所需的原生 SDK - -此部分在连接从臂的 **Linux 工作站**执行。Mac / Windows 的浏览器访问不需要这一步;本项目未提供原生 Windows / macOS 从臂控制方案。 - -先按 [Linux 原生 SDK 安装说明](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/docs/workstation.md#build-the-official-sdk)构建或复用已验证的安装: - -- OpenArm CAN SDK:1.4.1,对应提交 `bfd4e52194aefe38389fa6e670be3738136facb9`。 -- CLI11:对应提交 `4160d259d961cd393fd8d67590a8c7d210207348`。 -- 构建工具:Git、CMake、C++ 编译器、uv。 - -在已激活的 `~/.venvs/openarm` 环境里,指定实际 SDK 安装前缀后安装 Python 绑定。下面的 `/path/to/openarm-can-1.4.1` 必须替换为真实目录: - -```sh -export OPENARM_CAN_PREFIX=/path/to/openarm-can-1.4.1 -test -f "$OPENARM_CAN_PREFIX/lib/cmake/OpenArmCAN/OpenArmCANConfig.cmake" -uv pip install nanobind==2.10.2 scikit-build-core==1.1.1 -export CMAKE_ARGS="-Dnanobind_DIR=$(python -m nanobind --cmake_dir) -DCMAKE_DISABLE_FIND_PACKAGE_OpenArmCAN=OFF -DCMAKE_PREFIX_PATH=$OPENARM_CAN_PREFIX -DCMAKE_INSTALL_RPATH=$OPENARM_CAN_PREFIX/lib" -export CMAKE_BUILD_PARALLEL_LEVEL=4 -uv pip install --no-build-isolation-package openarm-can "openarm-runtime[follower] @ git+https://github.com/TCXM/openarm-runtime.git@v0.6.0" -python -c 'import openarm_runtime, openarm_can; print(openarm_runtime.__version__, openarm_can.__version__)' -uv pip check -``` - -依赖项目的 uv 构建设置不会自动传入你的应用环境,因此应保留上面的 CMake 参数与 `--no-build-isolation-package`。移动原生 SDK 目录后需要重新构建绑定;仅修改 Python 路径不能修复动态库引用。 - -## 3. 创建机器配置 - -配置、标定、日志和模型放在仓库外。首次配置时下载或克隆对应标签的示例;下面用 `/path/to/openarm-runtime` 表示 v0.6.0 源码目录。 - -```sh -git clone --branch v0.6.0 --depth 1 https://github.com/TCXM/openarm-runtime.git /path/to/openarm-runtime -cd /path/to/openarm-runtime -mkdir -p ~/.config/openarm ~/.config/openarm-runtime -# 已存在的文件保持不变;更新配置前另行备份并人工合并。 -test -e ~/.config/openarm/classic.json || cp classic.example.json ~/.config/openarm/classic.json -test -e ~/.config/openarm/video-runtime.json || cp video.example.json ~/.config/openarm/video-runtime.json -test -e ~/.config/openarm-runtime/platform.json || cp platform.example.json ~/.config/openarm-runtime/platform.json -``` - -按实际硬件编辑以下文件: - -| 文件 | 必须核对的内容 | -| --- | --- | -| `~/.config/openarm/classic.json` | 左右臂与 CAN 接口的对应关系;物理核对后才将 `mapping_verified` 设为 `true` | -| `~/.config/openarm/video-runtime.json` | RGB 设备路径、左右腕映射、深度 helper 路径、分辨率 / 帧率 | -| `~/.config/openarm-runtime/platform.json` | 各子服务命令、设备路径、端口、模型路径和报告目录 | -| `~/.config/openarm/leader.json` | 由主臂标定流程保存的软件零位与夹爪端点;不从示例捏造数据 | - -[Classic 示例](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/classic.example.json)中的 `left=can1`、`right=can0` 是示例映射,不是所有机器的固定接线。程序要求 Classic CAN 1 Mbps、FD 关闭、`restart-ms=0` 和健康链路;运行时只检查,不自动改 CAN。检查与恢复见 [故障排查](Troubleshooting.md)。 - -[平台示例](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/platform.example.json)中的 `command` 是参数数组: - -- `{python}` 使用启动平台的 Python 解释器,因此该环境必须包含子服务依赖。 -- `~/` 会展开为当前用户目录;`cwd` 和 `log_dir` 的相对路径以平台配置文件目录为基准。 -- 不执行 shell 展开,不能把管道、`&&`、`$HOME` 等拼成一个命令字符串。 -- 平台入口默认 `8888`;内部端口必须互不重复,并与对应命令的 `--port` 一致。 -- 只配置单个触觉视图时设 `extra_ports: []`;双视图默认占用主触觉端口加 10、加 11。 - -触觉命令中的 `--right-device` 表示页面第二个传感器。当前双传感器布局中,两块都安装在左臂,不能据参数名推断成左右机械臂各一块。 - -深度 helper 不随 pip 自动安装。Astra Pro 应使用同一套匹配的 OpenNI2 头文件、运行库和 Orbbec 驱动,构建方式见 [深度相机配置](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/docs/video.md#astra-pro-depth-helper)。 - -## 4. 准备模型并启动 - -在安装了 `viewer` 的环境中下载、校验固定版本的官方模型: - -```sh -source ~/.venvs/openarm/bin/activate -openarm-runtime prepare --asset-root ~/.cache/openarm-models -openarm-runtime platform --profile ~/.config/openarm-runtime/platform.json -``` - -打开工作站上的 `http://127.0.0.1:8888`,或从 Mac / Windows 建立一个 SSH 转发后访问。平台启动不会使能电机或自动跟随。首次迁移应先正常停止原来独立启动的控制与采集服务,使平台能够管理其生命周期。 - -完整日常流程见 [操作指南](Operations.md);只需复制常用启动命令时看 [快速开始](Quick-Start.md)。 - -## 5. 只用软件数据体验平台 - -这个演示在独立端口运行视频和单个触觉模拟页,不配置电机或遥操启动命令,也不需要 CAN SDK、相机或串口设备。仅安装 core 不够;模拟界面仍需要 `platform,tactile,viewer,video` 的 Python 依赖: - -```sh -source ~/.venvs/openarm/bin/activate -python -m pip install "openarm-runtime[platform,tactile,viewer,video] @ git+https://github.com/TCXM/openarm-runtime.git@v0.6.0" -ss -ltn -``` - -先确认 `18888`、`18893`、`18890`、`18891`、`15004` 未被其他服务使用。若有占用,选择另一组空闲端口,并同步修改服务端口及命令中的 `--port`;不要复用真实控制器的端口。 - -在 Linux 工作站生成外部配置。代码只在文件不存在时创建,不会覆盖已有配置: - -```sh -python - <<'PYCODE' -import json -from pathlib import Path - -path = Path("~/.config/openarm-runtime/platform-sim.json").expanduser() -config = { - "port": 18888, - "log_dir": "~/.local/state/openarm-platform-sim", - "services": { - "control": {"port": 18893}, - "teleop": {"port": 18890}, - "tactile": { - "port": 18891, - "extra_ports": [], - "command": ["{python}", "-m", "openarm_runtime", "tactile", - "--simulate", "--port", "18891"], - }, - "vision": { - "port": 15004, - "command": ["{python}", "-m", "openarm_runtime", "video", - "--simulate", "--port", "15004"], - }, - }, -} -path.parent.mkdir(parents=True, exist_ok=True) -try: - with path.open("x") as output: - json.dump(config, output, ensure_ascii=False, indent=2) - output.write("\n") -except FileExistsError: - print(f"保留已有文件,请先核对其内容:{path}") -else: - print(f"已创建:{path}") -PYCODE -``` - -确认配置仍然只有上述模拟命令后启动: - -```sh -openarm-runtime platform --profile ~/.config/openarm-runtime/platform-sim.json -``` - -在工作站浏览器打开 `http://127.0.0.1:18888`,进入“触觉”或“视觉”,页面会明确标记模拟数据。“电机控制”和“遥操”没有启动命令,显示未连接是预期行为;此演示不包含运动控制模拟。终端按 `Ctrl+C` 退出演示及其子服务。 - -从 Mac / Windows 访问时,把 [远程访问](Remote-Access.md) 中的转发端口替换为 `18888`,然后打开本地 `http://127.0.0.1:18888`。 - -## 6. 把库接入自己的项目 - -在自己的 Python 3.12 项目中,用固定版本作为依赖: - -```sh -uv add "openarm-runtime[leader,viewer] @ git+https://github.com/TCXM/openarm-runtime.git@v0.6.0" -``` - -开发应用和本库时,可把本库放在任意目录,用 editable 安装: - -```sh -python -m pip install -e "/path/to/openarm-runtime[leader,viewer]" -# uv 管理的应用可改用: -uv add --editable "/path/to/openarm-runtime[leader,viewer]" -``` - -Python 源码修改通常在重启应用后生效;依赖、入口点或构建配置变化时重新安装。交付应用前改回已发布标签或固定提交,并更新应用的锁文件。API 用法见 [Python API](Python-API.md)。 - -## 7. 在本仓库中开发 - -开发模式使用仓库自己的 `.venv`,与上文的发布版环境分开: - -```sh -cd /path/to/openarm-runtime -uv sync --locked --extra platform --extra leader --extra viewer --extra tactile --extra video -uv run --no-sync python -m openarm_runtime --help -``` - -需要完整硬件依赖时,先准备原生 SDK,再用仓库的安装脚本: - -```sh -export OPENARM_CAN_PREFIX=/path/to/openarm-can-1.4.1 -sh sync.sh -python3 run_platform.py -``` - -`sync.sh` 安装锁定的全部 extra 并配置原生绑定构建参数;它不设置 CAN,也不构造电机对象。`run_platform.py` 使用仓库 `.venv` 和外部平台配置。开发测试只能使用离线回归、模拟服务或经操作者明确安排的实机验证。 diff --git a/docs/wiki/Operations.md b/docs/wiki/Operations.md deleted file mode 100644 index c4e537d..0000000 --- a/docs/wiki/Operations.md +++ /dev/null @@ -1,162 +0,0 @@ -# 日常操作指南 - -适用版本:**v0.6.0**。硬件采集与控制运行在 Linux 工作站;本机或远程浏览器通过 **http://127.0.0.1:8888** 使用电机控制、遥操、触觉和视觉。 - -首次使用先完成[安装与配置](Installation.md),远程用户另见[Mac/Windows 访问](Remote-Access.md)。本页描述操作者流程;复制命令时参照[完整 CLI 参数](CLI-Reference.md)。 - -## 1. 启动统一平台 - -在已激活项目 Python 环境的工作站终端运行: - -```sh -openarm-runtime platform --profile ~/.config/openarm-runtime/platform.json -``` - -已配置的开发仓库也可运行: - -```sh -cd /path/to/openarm-runtime -python3 run_platform.py -``` - -浏览器打开 http://127.0.0.1:8888。平台根据配置启动缺失的服务或复用已运行服务。启动本身不会使能电机、开始跟随或写入零位。 - -首次替换旧启动方式时,先通过旧服务的原终端 `Ctrl+C` 或其正常停止方式退出独立服务,再只启动平台。平台会保留外部进程的所有权;它不会代替其他用户停止电机控制器。 - -### 状态要看两层 - -| 位置 | 表示什么 | 不代表什么 | -| --- | --- | --- | -| 平台总览的服务状态 | 对应页面端口是否可连接 | 不代表相机在线、电机已失能或反馈新鲜 | -| 模块内部状态 | 实际设备连接、采集错误、反馈与操作结果 | 不等同于所有机械条件已确认 | - -进入模块后读取内部状态,再执行该模块的操作。服务启动失败时查看对应日志,修复原因后显式重试;平台不会循环自动重启服务。 - -## 2. 看视觉与触觉 - -### 视觉 - -选择侧栏“视觉”,查看头部 RGB、深度、左腕和右腕四路画面及各自状态。实机配置须指向存在的设备;画面可打开并不代表四个采集源都正常。 - -腕部摄像头若共享相同设备序列号,应使用不同且有效的 `/dev/v4l/by-path/` 路径,并对照实物确认左右。USB Hub 断连或插口拓扑变化后,旧路径可能失效。先按[故障排查](Troubleshooting.md)确认设备,再更新外部视频配置并正常重启视觉采集。 - -模拟验证使用独立端口: - -```sh -openarm-runtime video --simulate --port 5004 -``` - -打开 http://127.0.0.1:5004。页面上的模拟标记不能当作硬件在线的证据。 - -### 触觉 - -选择“触觉”,在同页查看左臂两个传感器的三维分布、选定测点、XYZ 合力和历史曲线。当前已验证安装中,右臂没有触觉传感器;界面两栏和 `--right-device` 的名称不改变这个物理归属。 - -- 轻按并松开对应传感器,确认分布和曲线随实际接触变化。 -- “暂停显示”只冻结画面,不停止后台采集。 -- 读取错误或过期时,最后一个样本不再是实时数据;修复设备后使用模块“重新连接”。 -- 读数单位是原始 counts。合力和 68 点分布来自两次读取,不是同步采样帧;不能直接当成已校准的牛顿值。 - -两路传感器各有独立采集和视图。平台已转发其嵌套 WebSocket,远程客户端只需 `8888` 一个 SSH 转发。 - -## 3. 电机只读检查 - -页面正常显示不等于 CAN 配置正常。需要单独检查时,先停止运动操作及冲突的总线读者,再在工作站运行: - -```sh -ip -details -statistics link show can0 -ip -details -statistics link show can1 -openarm-runtime --config ~/.config/openarm/classic.json check -``` - -这组命令读取链路和电机状态,不修改 CAN 配置。运行时要求健康的 Classic CAN、1 Mbps、FD 关闭、`restart-ms 0`。出现 `DOWN/STOPPED`、`BUS-OFF` 或参数不符时,先定位原因;平台不会自动重配链路。 - -配置的 `left`/`right` 必须与接线一致,确认后才把 `mapping_verified` 设为 `true`。示例中的接口名称是示例映射,不能代替实物确认。 - -## 4. 手动电机控制 - -1. 在侧栏打开“电机控制”,检查左右设备反馈。 -2. 在面板选择目标“机械臂”,将“操作”设为“手动控制”。 -3. 确认工作范围、支撑和设备状态后勾选“机械臂已就绪”。 -4. 点击“使能并保持”。此时电机保持使能时捕获的当前位置。 -5. 调整该臂关节偏移滑条。界面偏移单位为度,相对于本次使能位置;手动模式范围为 ±30°,速度为 0.1–5°/s。 -6. 完成后点击“停止 · 失能”,等待页面报告 8 个电机均已确认失能。 - -滑条不是绝对零位设置。停止后的失能确认失败会显示错误,应保留报告并检查实际状态,不能仅凭按钮点击认定失能成功。 - -当前控制会跟踪发起操作的浏览器连接;连接断开会请求停止。但切换平台的“视觉/触觉”页会保留控制页连接,**不会停止正在进行的控制**。停止操作应明确点击控制页的停止按钮。 - -## 5. 主臂标定与遥操 - -### 主臂软件标定 - -在“遥操”页面展开“主臂标定”,选择双臂或单臂: - -1. 主臂处于失能状态,自然下垂并保持稳定,点击“① 记录自然零位”。 -2. 张开夹爪并保持稳定,点击“② 记录夹爪张开”。 -3. 闭合夹爪并保持稳定,点击“③ 记录夹爪闭合”。 -4. 点击“④ 保存标定”,确认状态显示已保存。 - -采集时保持静止约一秒。标定记录的是本地软件参考与夹爪端点,保存在 `--calibration` 指定的外部 JSON 中,不写主臂舵机寄存器。左右映射及方向需与实物一致。 - -### 真实跟随 - -平台配置的 `leader` 命令须带 `--follow`、从臂 `--config` 和 `--report-root`。进入遥操页后: - -1. 选择“跟随机械臂”:双臂、右臂或左臂。 -2. 确认主臂标定完整并保存,主臂反馈新鲜有效且处于失能状态。 -3. 检查从臂状态和可运动范围,点击“开始跟随”。 -4. 系统完成预检后建立本次接管参考。双臂跟随会协调两侧,任一侧故障会请求停止另一侧。 -5. 结束时点击“停止 · 失能”,检查结果和报告。 - -`--follow` 只提供这些控件,不会自动开始。单独的电压告警在有效新鲜反馈下按当前项目策略不阻断跟随;其他/组合故障、反馈失效或主臂已使能会被拒绝。 - -### 电机控制与遥操之间切换 - -两个模式共享 CAN,平台将它们作为互斥组。确认切换后,平台先通过正常清理流程停止自己启动的旧模式,再启动新模式;新模式仍需人工开始运动。触觉和视觉可以保持连接。 - -若旧控制器由平台外部启动,平台会拒绝替它终止进程。由原操作者正常停止后再切换。关闭超时或异常也会阻止切换,平台不会强杀运动进程来抢占 CAN。 - -## 6. 从臂硬件零位标定 - -这与主臂软件标定不同:它会实际移动选中从臂,寻找止挡并写入 8 个电机的硬件零位。仅针对已验证的 OpenArm v2 结构和安装假设;绝对精度、重复性及其他机器尚未完成量化验收。 - -1. 确认左右映射,卸载负载,清空整个运动范围及线缆,准备失能后的机械支撑。 -2. 将选中臂摆到规定参考姿态。 -3. 在“电机控制”选择机械臂和“自动标定”。 -4. 勾选“姿态已摆好,运动范围已清空”,点击“开始标定”。 -5. 等待完整流程及写入验证完成;需要中止时点击“停止 · 失能”。 -6. 检查报告、模型对齐及独立读回,不将运动阶段结束当作标定成功。 - -CLI 是另一入口,执行即开始流程: - -```sh -openarm-runtime --config ~/.config/openarm/classic.json calibrate \ - --side right --report-root ~/openarm-reports -``` - -写入不是原子操作。异常可能出现在部分电机已写入之后,必须根据报告和实际读回处理,不应盲目重试。详见[标定步骤与恢复](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/docs/calibration.md)。 - -## 7. 日志、报告与退出 - -默认平台子进程日志位于仓库外的 `~/.local/state/openarm-platform/`: - -```sh -# 在 Linux 工作站另开终端查看;Ctrl+C 只结束 tail -tail -n 100 -F ~/.local/state/openarm-platform/control.log -tail -n 100 -F ~/.local/state/openarm-platform/teleop.log -tail -n 100 -F ~/.local/state/openarm-platform/tactile.log -tail -n 100 -F ~/.local/state/openarm-platform/vision.log -``` - -上述每条是独立命令,按需选择一个。平台配置的 `log_dir` 可覆盖目录。控制、跟随和标定报告位于相应服务 `--report-root`,包括结束原因及失能验证信息。 - -正常收工顺序: - -1. 在正在操作的模块点击“停止 · 失能”,等待确认。 -2. 回到启动平台的工作站终端按 `Ctrl+C`,等待平台及自己管理的子服务完成关闭。 -3. 最后在客户端 SSH 转发终端按 `Ctrl+C`。 - -只关闭浏览器、切换页面或断开 SSH 转发,不等于停止整个远端平台。已由外部启动的服务也不会随平台退出而关闭。需要停止后台进程时,先核实进程身份,再向自己的目标 PID 发送 `SIGTERM`,保留清理和查看报告的机会。 - -下一步:[常用命令](CLI-Reference.md) · [故障排查](Troubleshooting.md) · [Python 集成](Python-API.md) diff --git a/docs/wiki/Python-API.md b/docs/wiki/Python-API.md deleted file mode 100644 index 00f739a..0000000 --- a/docs/wiki/Python-API.md +++ /dev/null @@ -1,273 +0,0 @@ -# Python API 与库参考 - -适用版本:**v0.6.0 · Python 3.12**。项目安装名是 `openarm-runtime`,Python 导入名按模块区分。所有模块的导入均不会打开硬件;构造同步设备对象、启动采集器或进入控制上下文才会产生相应操作。 - -[返回首页](Home.md) · [安装与依赖](Installation.md) · [命令参考](CLI-Reference.md) - -## 模块与依赖 - -| 导入模块 | 主要接口 | 使用时需要的 extra | -| --- | --- | --- | -| `openarm_runtime` | `Profile`、`ArmConnection`、`MotorState`、`MotorRange`、`hold_arm`、`calibrate_arm` | 只读 Linux SocketCAN 遥测用 core;实际控制用 `follower` 和原生 SDK | -| `openarm_leader` | `LeaderBus`、`LeaderReader`、`Sample`、`Mapping` | 串口采集用 `leader`;软件映射本身无 SDK 依赖 | -| `openarm_tactile` | `TactileReader`、`Sample`、`SENSOR`、`POINT_COUNT` | 真实采集和软件仿真均用 `tactile`;显示页面再加 `viewer` | -| `openarm_video` | `CameraConfig`、`Frame`、`CameraReader`、`VideoCapture`、编解码和网页接口 | `video`;真实深度另需 OpenNI2 helper | -| `openarm_platform` | `PlatformConfig`、`load_config` | 配置读取用 core;启动统一网页用 `platform` | -| `openarm_viewer` | 机器人和触觉可视化实现 | `viewer`;优先通过 CLI 使用 | - -例如,采集视频并供自己的程序处理,只需安装 `[video]`,不需要启动平台或 Viser。需要机器人网页的使用方式见[操作指南](Operations.md)。 - -## 通用生命周期与数据约定 - -- 后台采集类使用 `with` 或显式 `start()` / `close()`;`ArmConnection` 使用 `restart()` / `close()`。 -- `snapshot()` 返回最新已知数据,不代表刚刚完成采样。检查错误状态和数据年龄,再用于业务逻辑。 -- 时间戳采用 `time.monotonic()`,单位秒,用于本机年龄计算,不是 Unix 时间或跨设备同步时间。 -- 读取器报错时可能保留旧数据;禁止把旧数据当成当前反馈。关闭失败会抛出异常,应交由上层处理。 -- 物理控制要求同一 CAN 总线只有一个控制者。进入控制或标定前先停止该总线的只读采集器。 - -## 主臂:`openarm_leader` - -### 同步读取 - -`LeaderBus(path)` 在构造时打开串口,以 1 Mbps 读取 STS3215 的 ID 1–8。只发读取请求,不写舵机寄存器。 - -以下示例会读取真实串口;先替换设备占位符,并确认设备没有被其他读取器占用: - -```python -from openarm_leader import LeaderBus - -with LeaderBus("/dev/serial/by-id/YOUR_LEADER") as bus: - sample = bus.sample() - print("编码器计数:", sample.positions) - print("电压 V:", sample.voltages) - print("使能状态:", sample.torque) - print("故障位:", sample.errors) -``` - -`Sample` 中的各元组按 ID 1–8 排列。`positions` 是原始编码器计数;`torque` 是使能状态,**不是力矩值**。`received_at` 为一次采样的起始时间,`duration` 为读取耗时。`fresh(now)` 要求年龄小于 0.4 秒。 - -### 后台读取 - -```python -import time -from openarm_leader import LeaderReader - -with LeaderReader("/dev/serial/by-id/YOUR_LEADER") as reader: - deadline = time.monotonic() + 5 - while time.monotonic() < deadline: - sample, error, count = reader.snapshot() - if not error and sample is not None and sample.fresh(time.monotonic()): - print(count, sample.positions) - time.sleep(0.1) -``` - -`LeaderReader` 在读取失败后自动尝试重新连接。仅电压故障位不阻止有效数据读取;其他故障、损坏数据和超时会作为错误处理。物理跟随还会检查主臂是否处于失能状态。 - -### 软件标定与映射 - -`Mapping(left, right, path)` 接收两条不同串口路径以及外部 JSON 标定文件路径,标定按设备身份保存。 - -| 方法 | 含义 | -| --- | --- | -| `capture(side, sample, kind, now)` | 记录 `zero`、`open` 或 `closed`;`side` 为 `left` / `right`,拒绝过期或已使能主臂样本 | -| `angles(side, positions)` | 返回 `(angles, opening)`:七关节角度为弧度,夹爪开度在 `[0, 1]`;夹爪未标定则为 `None` | -| `save()` | 将软件标定写入指定 JSON 文件 | -| `swap()` | 交换左右设备映射,之后需显式保存 | - -尚未采集关节零位时,`angles()` 会用编码器 2048 作为显示基准;得到角度不等于完成标定。实际跟随需完整校验标定。该软件标定不会写入舵机或从臂电机的硬件零位。 - -## 从臂只读反馈:`ArmConnection` - -此接口运行于 Linux SocketCAN,发送参数/反馈读取请求,不使能电机、不写控制目标。CAN 应已配置为经过验证的 Classic 1 Mbps 链路。 - -```python -import time -from openarm_runtime import ArmConnection - -reader = ArmConnection("can0", "classic") -try: - reader.restart() - deadline = time.monotonic() + 5 - while time.monotonic() < deadline: - states, error, message, replies, missed = reader.shared.snapshot() - if not error: - now = time.monotonic() - positions = { - mid: state.position - for mid, state in states.items() - if state.fresh(now, 0.4) - } - print("关节位置 rad:", positions) - else: - print("读取错误:", error) - time.sleep(0.2) -finally: - reader.close() -``` - -`MotorState` 包含 `motor_id`、`position`(rad)、`velocity`(rad/s)、`torque`(Nm)、`mos_temperature`、`rotor_temperature`、`status`、`received_at` 和 `frame_format`。初始或掉线时 `states` 可能不完整;整臂逻辑必须验证所需全部 ID 的状态。 - -`MotorRange(position, velocity, torque)` 是固件数据解码范围,不能作为机械碰撞或运动边界。 - -## 从臂控制与硬件标定 - -以下接口会控制真实电机。先完成[操作指南](Operations.md)中的设备映射、链路和工作空间检查。API 使用外部 `Profile.load(path)`,配置示例见 [`classic.example.json`](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/classic.example.json)。 - -### 保持当前姿态:`hold_arm` - -```python -import signal -import threading -import time -from openarm_runtime import Profile, hold_arm - -profile = Profile.load("/path/to/classic.json") -stop = threading.Event() -for sig in (signal.SIGINT, signal.SIGTERM): - signal.signal(sig, lambda *_: stop.set()) - -period = 1.0 / profile.rate_hz -offsets = dict.fromkeys(range(1, 9), 0.0) -try: - # 进入上下文会使能所选物理臂;零偏移表示保持刚采集的姿态。 - with hold_arm(profile, "right", cancelled=stop.is_set) as arm: - while not stop.is_set(): - started = time.monotonic() - arm.tick(offsets, speed=1.0, period=period) - stop.wait(max(0.0, period - (time.monotonic() - started))) -except InterruptedError: - pass # 上下文已执行退出清理;其他控制/失能异常仍向外传播。 -``` - -`hold_arm(profile, side, *, allow_unreadable_mode=False, cancelled=..., record=..., publish=...)` 管理独占总线、预检、使能、退出失能和连接关闭。调用者负责循环调度,没有隐藏控制线程。 - -| `arm.tick` 参数 | 单位与限制 | -| --- | --- | -| `offsets` | 必须提供 ID 1–8;相对本次使能姿态的偏移角,单位度,范围 ±30° | -| `speed` | 0.1–5°/s | -| `period` | 0.02–0.1 s;默认配置为 20 Hz | - -这是 Python 尽力调度的控制循环,不提供硬实时保证。`record(event)` 和 `publish(states)` 回调应保持快速;回调异常也会触发退出清理。无法确认失能时会抛出错误,不应在上层静默忽略。 - -`allow_unreadable_mode=True` 仅针对已验证的 RID10 读取超时情况;如果读回明确的非 MIT 模式,仍会拒绝控制。默认保持 `False`。 - -### 自动标定:`calibrate_arm` - -```python -# 接口调用形式;仅在操作者决定执行物理标定时调用。 -# zeros = calibrate_arm( -# profile, "left", cancelled=stop.is_set, -# record=report.record, publish=on_feedback, progress=on_progress, -# ) -``` - -完整签名为 `calibrate_arm(profile, side, *, cancelled=..., record=..., publish=..., progress=..., allow_unreadable_mode=False)`。 - -该同步调用会使能、运动、寻找止挡、到达计算零位、失能,并写入/验证硬件零位。返回 `{motor_id: raw_zero_radians}`,覆盖 ID 1–8,数值使用写入前的编码器坐标。需提供取消回调和持久日志,例如 `openarm_runtime.report.Report(...).record`;CLI 和网页已实现相应调度。 - -标定失败可能发生在部分硬件零位已写入之后,不会自动回滚。开始前阅读[标定说明](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/docs/calibration.md),不要把此接口当作只读估计函数。 - -## 触觉:`openarm_tactile` - -`TactileReader(device=None, *, simulate=False, baudrate=921600, device_id=1)` 在 `start()` 或进入 `with` 后开始采集。必须选择串口设备或 `simulate=True` 中的一种。`device_id` 是板上模块 ID,与 `/dev/ttyUSB*` 的数字无关;项目验证的设备使用 ID 2。 - -下面的示例生成软件数据,不访问真实串口。仿真仍需要 `[tactile]` 中 SDK 提供的传感器点位表: - -```python -import time -from openarm_tactile import TactileReader, POINT_COUNT - -with TactileReader(simulate=True) as reader: - deadline = time.monotonic() + 5 - while time.monotonic() < deadline: - state = reader.snapshot() - if state["state"] == "error": - raise RuntimeError(state["error"]) - if state["state"] == "live": - sample = state["sample"] - assert len(sample.forces) == POINT_COUNT == 68 - print("合力原始计数:", sample.resultant) - print("第一个测点 XYZ:", sample.forces[0]) - break - time.sleep(0.02) - else: - raise TimeoutError("未收到触觉仿真数据") -``` - -真实采集将构造参数换为 `TactileReader("/dev/serial/by-id/YOUR_TACTILE", device_id=2)`。 - -`snapshot()` 是字典,包含 `state`、`error`、`sample`、`sequence`、`age_s`、`rate_hz`。仅 `state == "live"` 表示可使用当前样本;其他状态为 `waiting`、`stale`、`error`、`closed`。超过 0.5 秒的样本视为过期。 - -`Sample.resultant` 为 XYZ 合力,`Sample.forces` 为 68 个 XYZ 测点;数据是原始计数,**不是标定后的牛顿值**。Fx/Fy 有符号,Fz 无符号。合力与分布来自独立事务,不是严格同步的一帧。采集速率上限为 60 Hz。 - -失败后不会自动转入仿真或自动重连;在已启动的 reader 上调用 `restart()` 显式重连。`close()` 最多等待工作线程 3 秒并报告失败;关闭后创建新实例。 - -## 视觉:`openarm_video` - -### 采集配置与数据 - -`CameraConfig(name, device="", kind="rgb", width=640, height=480, fps=30, preview_width=None, preview_height=None, depth_helper=None, uri=None)` 只保存配置。 - -- RGB 指定 `device`。深度指定 `kind="depth"`、外部 `depth_helper`,必要时指定 OpenNI `uri`。 -- `preview_width` 和 `preview_height` 必须同时设置,只影响网页预览;Python 获取原始采集分辨率。 -- `load_cameras(path)` 从外部 `{"cameras": [...]}` JSON 文件读取配置元组。 -- RGB `Frame.image` 为 H×W×3、`uint8`、BGR;深度为 H×W、`uint16`、毫米,0 表示无效。 -- `Frame` 还包含 `received_at`、`sequence`、`pixel_format`。图像由采集器持有,消费者修改前应 `.copy()`。 - -### 多路软件采集 - -此示例只需 `[video]`,无需摄像头或深度 SDK: - -```python -import time -from openarm_video import CameraConfig, VideoCapture, encode_frame - -configs = [CameraConfig("head"), CameraConfig("depth", kind="depth")] -with VideoCapture(configs, simulate=True) as capture: - deadline = time.monotonic() + 5 - while time.monotonic() < deadline: - frame, error, count = capture.snapshot("head") - if error: - raise RuntimeError(error) - if frame is not None and frame.fresh(time.monotonic()): - data, mime = encode_frame(frame) - print(frame.image.shape, count, len(data), mime) - break - time.sleep(0.02) - else: - raise TimeoutError("未收到视频仿真帧") -``` - -`VideoCapture(configs, *, source_factory=None, stale_after=3, simulate=False)` 持有一组具名读取器。构造不访问硬件;`with` / `start()` 才开始。`snapshot(name)` 返回 `(frame_or_none, error, count)`;`status()` 返回按相机名组织的状态。关闭时尝试清理所有读取器,即使某个关闭失败。 - -单路可用 `CameraReader(config, *, source_factory=None, stale_after=3, retry_interval=1, simulate=False)`;读取失败后会重新连接。关闭后的实例不能重新启动。可注入 `source_factory(config)`,返回提供 `read() -> Frame` 与有界、可重复 `close()` 的自定义源;采集器负责关闭它。 - -### 同步源、编码与网页 - -| 接口 | 用途 | -| --- | --- | -| `OpenCVCamera(config)` | 构造时打开同步 RGB 源;`read()` 返回 `Frame`,支持 `with` | -| `OpenNIDepthCamera(config)` | 启动已配置的深度 helper;`read()` 返回深度 `Frame` | -| `build_depth_helper(include_dir, library_dir, output)` | 使用外部匹配的 OpenNI2 SDK 编译 helper,不打开设备 | -| `encode_frame(frame, *, raw=False, near=0.3, far=4)` | 返回 `(bytes, MIME)`;RGB 为 JPEG,深度为 PNG;深度预览范围参数单位米 | -| `create_app(capture)` | 返回 Flask app,采集器生命周期由调用者管理 | -| `serve(capture, host="127.0.0.1", port=5003)` | 先绑定端口,再启动采集并阻塞服务;退出时关闭采集器 | - -`raw=True` 的深度编码保留原始毫米数值。相关 HTTP 帧路径和图像语义见[视觉文档](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/docs/video.md)。 - -## 平台配置与接口边界 - -```python -from openarm_platform import load_config - -config = load_config("/path/to/platform.json") -print(config.port) -for page in config.pages: - print(page.id, page.port) -``` - -`load_config(path=None)` 和 `PlatformConfig` 可在 core 环境中使用,不启动子服务。配置参数和启动命令见[架构说明](Architecture.md)及[命令参考](CLI-Reference.md)。 - -平台的 `openarm_platform.app.create_app`、服务管理类和 `/api/*` 路由服务于内部网页,并非承诺兼容的公共硬件 REST API;v0.6.0 也未开放 OpenAPI 页面。集成采集/控制优先使用本文 Python API,启动平台使用 `openarm-runtime platform`。 - -0.x 系列消费者应固定版本标签或提交。完整契约以 [v0.6.0 API 文档](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/docs/api.md)及对应实现为准;不兼容 API 变更会写入变更记录并提升次版本号。 diff --git a/docs/wiki/Quick-Start.md b/docs/wiki/Quick-Start.md deleted file mode 100644 index 5b3227e..0000000 --- a/docs/wiki/Quick-Start.md +++ /dev/null @@ -1,96 +0,0 @@ -# 快速上手 - -[文档首页](Home.md) · 适用 v0.6.0 - -本页针对**已完成安装和设备配置**的 Linux 工作站。新机器先看 [安装与配置](Installation.md),只有 Mac / Windows 客户端则直接看 [终端与远程访问](Remote-Access.md)。 - -## 1. 在工作站启动统一平台 - -在 Linux 工作站本机终端或登录工作站后的 SSH 终端执行: - -```bash -source ~/.venvs/openarm/bin/activate -openarm-runtime platform --profile ~/.config/openarm-runtime/platform.json -``` - -如果使用开发仓库及其 `.venv`,可以用仓库启动器替代上面两行: - -```bash -cd /path/to/openarm-runtime -python3 run_platform.py -``` - -两种启动方式选择一种。已有平台运行时直接访问页面,不再启动第二个实例。终端显示 `OpenArm Platform: http://127.0.0.1:8888` 后,保留终端运行。 - -平台配置指定各模块的启动命令、设备配置和内部端口。`platform` 不会自动发现设备、生成主臂标定或设置 CAN。未填写模块命令时,平台只能连接该端口已经存在的服务。 - -## 2. 打开实时网页 - -工作站本机直接打开 **http://127.0.0.1:8888**。 - -其他电脑在 **Mac Terminal 或 Windows PowerShell** 执行: - -```sh -ssh -N -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -L 127.0.0.1:8888:127.0.0.1:8888 USER@WORKSTATION -``` - -替换账号和主机地址,登录后保持该终端打开。在这台客户端电脑的浏览器访问 **http://127.0.0.1:8888**。`ssh -N` 没有命令提示符、持续等待是正常现象。 - -这一条转发覆盖所有模块页面、实时图像、3D 视图和触觉嵌套视图。端口被占用、需要更换 SSH 端口等情况见 [远程访问](Remote-Access.md)。 - -## 3. 使用侧栏打开模块 - -| 模块 | 查看内容 | 操作提示 | -| --- | --- | --- | -| 电机控制 | 双臂反馈、用户控制、从臂标定 | 初始为只读;使能、移动与标定需在面板主动操作 | -| 遥操 | 主臂反馈、标定、姿态预览、可选物理跟随 | `--follow` 提供跟随控件,启动命令本身不会自动开始跟随 | -| 触觉 | 两个传感器的分布、合力、曲线 | 当前验证布局的两个传感器都在左臂;第二个串口参数名沿用 `--right-device` | -| 视觉 | 头部 RGB、深度、左右腕部图像 | 图像是否实时取决于设备在线状态和帧新鲜度 | - -切换到触觉、视觉时,已打开的模块视图会保留。电机控制与遥操属于互斥模式,切换时按界面确认并等待原服务完成关闭。平台复用的外部电机服务需要先由原启动者正常停止,才能交给平台切换管理。 - -具体控制和标定流程见 [日常操作](Operations.md)。 - -## 4. 查看日志与状态 - -另开一个 Linux 工作站终端: - -```bash -# 平台启动的子服务输出;可只选需要的日志。 -tail -n 80 -F ~/.local/state/openarm-platform/control.log -tail -n 80 -F ~/.local/state/openarm-platform/vision.log -``` - -平台主进程的输出默认显示在启动终端。子服务日志目录可通过平台配置的 `log_dir` 更改。`tail -F` 用于跟踪日志,按 Ctrl+C 只结束日志查看。 - -以下查询不会启动或切换模块: - -```bash -curl -fsS http://127.0.0.1:8888/api/status | python3 -m json.tool -``` - -`/api/status` 是 v0.6.0 平台内部诊断接口;应用集成使用 [Python API](Python-API.md),不把这个地址视为稳定的设备控制协议。 - -## 5. 结束使用 - -1. 如果进行了物理控制,先在所属模块停止操作,并确认关闭/失能结果。 -2. 在平台启动终端按 Ctrl+C,等待平台关闭自己启动的子服务。 -3. 在客户端 SSH 转发终端按 Ctrl+C,结束本地转发。 - -关闭浏览器或 SSH 转发不会关闭远端平台;平台也不会关闭它复用的外部服务。 - -## 无设备时先试界面 - -安装相应 extras 后,在 Linux 开发环境选择以下软件模拟命令;它们各自是独立模块示例: - -```bash -# 需要 video extra,不打开真实相机。 -openarm-runtime video --simulate --port 5004 - -# 在另一个终端执行;需要 tactile、viewer extras,不打开真实串口。 -openarm-runtime tactile --simulate --port 8895 -``` - -访问各命令打印的本机 URL。平台模拟配置示例见 [安装与配置](Installation.md);软件模拟不能验证真实 CAN、电机、接线或跟踪精度。 - -下一步:[常用 CLI 命令](CLI-Reference.md) · [Python API](Python-API.md) · [故障排查](Troubleshooting.md) diff --git a/docs/wiki/Remote-Access.md b/docs/wiki/Remote-Access.md deleted file mode 100644 index e4b0a34..0000000 --- a/docs/wiki/Remote-Access.md +++ /dev/null @@ -1,152 +0,0 @@ -# 终端与远程访问:Linux / Mac / Windows - -[文档首页](Home.md) · 适用 v0.6.0 - -**Linux 工作站运行硬件服务;Mac / Windows 运行 SSH 客户端和浏览器。** 统一网页入口为 `http://127.0.0.1:8888`。以下 `USER@WORKSTATION` 是占位符,替换为工作站账号和主机名或 IP。 - -## 命令在哪里执行 - -| 位置 | 执行内容 | -| --- | --- | -| Linux 工作站终端,或 SSH 登录后的远端提示符 | 启动平台、查 CAN/串口、查看服务日志 | -| Mac 的 Terminal | `ssh` 建立连接/转发;`open` 打开本机浏览器 | -| Windows 的 PowerShell / Windows Terminal | `ssh` 建立连接/转发;`Start-Process` 打开本机浏览器 | -| 客户端浏览器 | 访问本机的 `127.0.0.1:8888`,数据通过 SSH 到达工作站 | - -只做远程查看时,客户端不需要安装 Python、CAN SDK 或本项目。硬件工作站应已配置 SSH 登录和 OpenArm Runtime,参见 [安装与配置](Installation.md)。 - -## 情况 A:平台已经在工作站运行 - -### Mac Terminal - -打开 Terminal,在终端 A 执行并保留: - -```bash -ssh -N -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L 127.0.0.1:8888:127.0.0.1:8888 USER@WORKSTATION -``` - -在另一个本机终端 B 执行,或手动输入浏览器地址: - -```bash -open http://127.0.0.1:8888 -``` - -### Windows PowerShell - -先确认 SSH 客户端可用: - -```powershell -ssh -V -``` - -如果提示找不到 `ssh`,在 Windows 的“可选功能”安装 **OpenSSH 客户端**。也可以在管理员 PowerShell 执行下列安装命令,完成后重新打开普通 PowerShell;此步骤只在缺少客户端时需要。参见 [Microsoft OpenSSH 安装文档](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse)。 - -```powershell -Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0 -``` - -在普通 PowerShell 窗口 A 执行并保留: - -```powershell -ssh -N -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L 127.0.0.1:8888:127.0.0.1:8888 USER@WORKSTATION -``` - -在另一个本机 PowerShell 窗口 B 打开浏览器: - -```powershell -Start-Process "http://127.0.0.1:8888" -``` - -这里使用单行命令,不需要 Bash 的续行反斜杠。首次登录请核对工作站的 SSH 主机指纹,然后按提示输入凭据;密码输入时不回显。 - -## 情况 B:同时登录工作站并启动平台 - -Mac Terminal 和 Windows PowerShell 都可以使用下面的命令。这里省略 `-N`,同一个 SSH 会话提供远端 shell 和端口转发: - -```sh -ssh -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -L 127.0.0.1:8888:127.0.0.1:8888 USER@WORKSTATION -``` - -登录成功后,以下两行是在 **Linux 工作站的远端提示符**下执行: - -```bash -source ~/.venvs/openarm/bin/activate -openarm-runtime platform --profile ~/.config/openarm-runtime/platform.json -``` - -如果实际使用的是开发仓库环境,改为: - -```bash -cd /path/to/openarm-runtime -python3 run_platform.py -``` - -两种启动方式选择一种;已有平台时不要再启动。随后在 Mac / Windows 的本机浏览器打开 **http://127.0.0.1:8888**。平台留在前台运行,输出直接显示在这个 SSH 终端。 - -## 参数与端口说明 - -| 参数 | 作用 | -| --- | --- | -| `-N` | 只建立转发,不启动远端命令;终端持续等待是正常状态 | -| `-L 127.0.0.1:8888:127.0.0.1:8888` | 客户端回环地址的 8888 转到工作站回环地址的 8888 | -| `-o ExitOnForwardFailure=yes` | 转发监听建立失败时退出,例如本地端口已被占用 | -| `-o ServerAliveInterval=30` | 无服务端数据时,每 30 秒发送保活消息 | -| `-p 2222` | 若管理员配置了非默认 SSH 端口,可添加此选项;数值按实际修改 | - -`ExitOnForwardFailure` 不能证明远端平台已经启动;远端目标拒绝连接时仍须检查服务。参数语义见 [OpenSSH ssh 手册](https://man.openbsd.org/ssh) 和 [ssh_config 手册](https://man.openbsd.org/ssh_config)。 - -本地 8888 被其他程序占用时,只改本地监听端口: - -```sh -ssh -N -o ExitOnForwardFailure=yes -L 127.0.0.1:8889:127.0.0.1:8888 USER@WORKSTATION -``` - -此时在客户端打开 **http://127.0.0.1:8889**,工作站平台仍运行在 8888。默认内部端口 8893、8890、8891、8901、8902、5003 都由网关转发,无需额外 SSH 转发。平台要求通过 localhost 地址访问,不能直接用 `http://工作站IP:8888` 替代隧道。 - -## 从客户端查看实时终端日志 - -平台已经运行时,另开一个本机 Terminal / PowerShell 窗口: - -```sh -# 这里引号里的命令由远端 Linux 执行,两种客户端都适用。 -ssh USER@WORKSTATION "tail -n 80 -F ~/.local/state/openarm-platform/vision.log" -``` - -其他模块把 `vision.log` 替换为 `control.log`、`teleop.log` 或 `tactile.log`。这些是平台启动的子服务日志;配置了 `log_dir` 时使用该目录。平台自身的日志默认在其启动终端,`platform.log` 只有自行重定向输出时才存在。 - -按 Ctrl+C 结束日志跟踪。需要完整交互终端时,先 `ssh USER@WORKSTATION`,再执行 Linux 命令。 - -## 浏览器打不开时逐层检查 - -**先在 Linux 工作站检查平台:** - -```bash -ss -ltnp 'sport = :8888' -curl -fsS http://127.0.0.1:8888/api/status | python3 -m json.tool -``` - -**再在 Mac 本机检查转发:** - -```bash -lsof -nP -iTCP:8888 -sTCP:LISTEN -curl -fsS http://127.0.0.1:8888/api/status -``` - -**或者在 Windows PowerShell 检查转发:** - -```powershell -Get-NetTCPConnection -LocalPort 8888 -State Listen -Test-NetConnection 127.0.0.1 -Port 8888 -Invoke-RestMethod -Uri "http://127.0.0.1:8888/api/status" | ConvertTo-Json -Depth 6 -``` - -诊断接口 `/api/status` 属于平台内部实现;以上只做读取,不会切换模块。工作站本地请求失败时查平台启动输出;本地成功但客户端失败时查 SSH 隧道;网页可打开但单个模块离线时查该模块日志。 - -## 结束与保留会话 - -- `ssh -N` 窗口按 Ctrl+C:仅结束转发,远端平台仍可能运行。 -- 日志跟踪窗口按 Ctrl+C:仅结束 `tail`。 -- 平台前台窗口按 Ctrl+C:请求平台关闭自己启动的服务,并等待清理结果。 -- 关闭浏览器:不代表电机已经失能,也不代表远端服务停止。 - -需要长期保留终端时,可使用工作站已安装的终端复用工具并按其运维方式管理;不要依赖直接关闭 SSH 窗口完成正常停机。完整停止顺序见 [日常操作](Operations.md)。 diff --git a/docs/wiki/Troubleshooting.md b/docs/wiki/Troubleshooting.md deleted file mode 100644 index 201d22e..0000000 --- a/docs/wiki/Troubleshooting.md +++ /dev/null @@ -1,170 +0,0 @@ -# 故障排查 - -[返回首页](Home.md) · [安装与配置](Installation.md) · [日常操作](Operations.md) · [远程访问](Remote-Access.md) - -先区分 **网页服务是否可达** 和 **硬件数据是否正常**。平台概览中的在线状态表示对应端口能连接;相机断开、串口超时或 CAN 异常时,网页本身仍可能在线。 - -## 快速定位 - -| 现象 | 优先检查 | -| --- | --- | -| 工作站也打不开 `8888` | 平台是否启动、环境依赖、入口端口占用 | -| 工作站能打开,Mac / Windows 不能 | SSH 是否连对工作站、转发是否存活、本地端口是否占用 | -| 平台打开但某个模块失败 | 该模块日志、启动命令、设备路径及依赖 | -| 电机提示 `Expected healthy Classic...` | CAN 当前状态与参数,不能直接判断为权限不足 | -| 左右腕无图,头部正常 | 外部视频配置中的设备路径、USB 拓扑、左右对应关系 | -| 触觉有旧数值但不更新 | `live / stale / error` 状态、设备 ID、串口占用 | -| 无法从电机控制切到遥操 | 原控制器是否由平台管理,旧服务是否正常退出 | - -以下终端命令默认在 Linux 工作站执行。远程客户端应先 `ssh USER@WORKSTATION` 登录工作站;Mac / Windows 本地排查命令见 [远程访问](Remote-Access.md)。 - -## 1. 平台或模块打不开 - -```sh -ss -ltnp 'sport = :8888' -curl --fail --max-time 3 http://127.0.0.1:8888/api/status -ls -l ~/.local/state/openarm-platform/ -tail -n 80 ~/.local/state/openarm-platform/control.log -tail -n 80 ~/.local/state/openarm-platform/teleop.log -tail -n 80 ~/.local/state/openarm-platform/tactile.log -tail -n 80 ~/.local/state/openarm-platform/vision.log -``` - -日志目录默认如上,也可由平台配置的 `log_dir` 指定。`/api/status` 仅适合诊断页面服务,不代表电机已失能,也不是同步传感器数据接口。 - -如果 `openarm-runtime` 找不到或缺依赖: - -```sh -source ~/.venvs/openarm/bin/activate -command -v python -command -v openarm-runtime -python -c 'import openarm_runtime; print(openarm_runtime.__version__)' -python -m pip check -``` - -检查安装环境是否包含 `[platform]` 及失败子模块的 extra。开发启动器 `run_platform.py` 使用仓库 `.venv`,并不使用另一个发布版环境。两者不可混为同一个安装位置。 - -### 端口占用与重复服务 - -```sh -ss -ltnp 'sport = :8893' -ss -ltnp 'sport = :8890' -ss -ltnp 'sport = :8891' -ss -ltnp 'sport = :5003' -``` - -这些是默认内部端口;以平台配置为准。确认进程用户、命令及用途后,在原终端按 `Ctrl+C` 正常退出旧服务。平台不会停止外部启动的进程;由其他账号启动的服务应由其操作者停止。不要仅凭端口号误停正在工作的控制器。 - -外部电机控制器存在时,平台可复用页面,但会拒绝自动切走它。正常停止旧控制器后,由平台重新管理电机控制和遥操。不要删除 CAN 锁文件或强行终止运动进程来绕过所有权检查。 - -## 2. CAN 健康检查错误 - -错误示例: - -```text -RuntimeError: Expected healthy Classic 1 Mbps, fd off, restart-ms 0; no automatic reconfiguration -``` - -这是链路前置检查未满足,并不等同于“没有 sudo 权限”。检查命令: - -```sh -ip -details -statistics link show can0 -ip -details -statistics link show can1 -``` - -程序要求同时满足: - -| 项目 | 期望值 | -| --- | --- | -| 管理标志 | 包含 `UP` | -| CAN 状态 | `ERROR-ACTIVE` | -| MTU | `16`,即 Classic CAN | -| bitrate | `1000000` | -| FD | 关闭 | -| restart-ms | `0` | -| 收发错误计数 | 全部为 `0` | - -只看普通 `state UP / DOWN` 一行不够,应查看详细 CAN 参数。`ERROR-ACTIVE` 是正常的 CAN 错误管理状态名称,不表示当前发生了故障。 - -### 为什么变成 DOWN / STOPPED - -重启、显式关闭接口、USB CAN 适配器或其 Hub 断开后重新枚举,都可能使接口回到未启用状态。重枚举还可能丢失原先的 bitrate 设置。查看内核日志,结合实际时间确认: - -```sh -journalctl -k --since '30 minutes ago' -ip -details link show can0 -ip -details link show can1 -``` - -看到 USB disconnect 只说明设备发生过断开,不能单凭日志确定是拔线、供电、Hub、驱动还是软件操作。先恢复稳定连接,再核对物理左右臂映射。 - -### 人工启用接口 - -只在操作者确认目标接口、总线无活动控制器、已知配置与设备要求一致后执行。以下是人工维护命令,不是平台启动步骤或自动恢复逻辑。 - -若接口已保存 **Classic 1 Mbps、FD off、restart-ms 0** 配置,只需启用: - -```sh -sudo ip link set dev can0 up -sudo ip link set dev can1 up -``` - -若 USB 重枚举后 bitrate 未配置,且接口已经是 DOWN,先由操作者明确设置已确认的参数: - -```sh -sudo ip link set dev can0 type can bitrate 1000000 fd off restart-ms 0 -sudo ip link set dev can1 type can bitrate 1000000 fd off restart-ms 0 -sudo ip link set dev can0 up -sudo ip link set dev can1 up -``` - -然后重新检查详细状态。不要对一个正在使用或已经健康的总线反复 down/up;错误计数持续增加或出现 BUS-OFF 时,应查供电、线缆、终端电阻、设备波特率和总线负载,不能用自动重启掩盖原因。程序本身不会替你修改 CAN。 - -明确的 `Operation not permitted` 才指向该项操作的权限问题。sudo 密码应仅在工作站终端输入;普通网页访问和大多数运行命令不需要以 root 启动整个程序。 - -## 3. 左腕 / 右腕没有画面 - -```sh -v4l2-ctl --list-devices -ls -l /dev/v4l/by-id /dev/v4l/by-path -curl --fail --max-time 3 http://127.0.0.1:8888/apps/vision/status -``` - -检查每路的错误、帧计数和帧龄。重点核对 `~/.config/openarm/video-runtime.json`: - -- `/dev/camera_wrist_*` 自定义别名可能指向旧 USB 拓扑;名称存在与否须按实际机器检查。 -- 两个同型号相机可能报告相同序列号,导致 `/dev/v4l/by-id` 无法区分。可使用两个不同的 `by-path`,通常选择可采集节点 `video-index0`。 -- `by-path` 比易变化的 `/dev/videoN` 更适合区分 USB 端口,但换 Hub 或物理插口后仍须重新核对。 -- 根据实际画面确认左 / 右映射,不能根据枚举先后猜测。 -- 相机可能被旧采集进程占用;先正常停止旧采集者,再由新服务打开设备。 - -修改外部配置后,正常重启对应视觉服务以重新加载。深度单独失败时,核对 `depth_helper` 是否存在、可执行,以及 OpenNI2 / Orbbec 库是否来自匹配版本;它与 RGB UVC 路径不同。 - -## 4. 触觉无响应或保留旧数据 - -```sh -ls -l /dev/serial/by-id/ -id -``` - -确认配置中的串口路径存在,并且运行账号有设备访问权限。USB 重新插拔可能使临时 ACL 失效;持久权限应通过针对实际设备的系统用户组或 udev 规则管理,不应将全部串口改成所有人可写。 - -检查 `--device-id` 与实际模块设置。已验证的设备地址是 **2**,CLI 默认是 **1**;设备地址与 `/dev/ttyACM0` 中的数字没有关系。已验证波特率为 **921600**。不要把所有超时都归因于波特率,更不要在排查时让多个采集者同时打开一个传感器。 - -页面保留最后读数不代表数据仍有效:`stale`、`error` 或“已失效”状态都不能作为实时样本。故障后触觉采集关闭串口,需要点击“重新连接”;不会自动切为模拟。暂停只冻结显示,不等于停止采集。 - -原始力单位为 counts;没有按传感器标定,不能将数值直接当作 N。当前两个传感器都属于左臂,页面左右顺序与机械臂左右是不同含义。 - -## 5. 主臂预览正常,但不能实体跟随 - -检查外部 `leader.json` 是否包含对应设备的有效标定,主臂串口路径是否正确,从臂配置中的物理映射是否经过确认。实体跟随还要求从臂总线没有其他读写者占用。 - -新鲜、有效反馈中的单独低压 / 电压告警按本项目已确认规则不阻断跟随;其他或组合错误、过期 / 损坏反馈、主臂已使能等仍会拒绝跟随。不能为了消除提示而伪造标定值或屏蔽其他故障。具体操作见 [操作指南](Operations.md)。 - -## 6. 退出、切换或清理超时 - -关闭浏览器、切换到视觉 / 触觉页面,或断开 SSH 转发,都不等于停止远端运动或服务。先使用运动页面的停止 / 失能操作,再按正常流程关闭服务。 - -平台给自有运动服务最多 40 秒进行正常退出;超时或异常退出会阻止模式切换,不会强杀运动进程。保留日志并确认硬件状态后再处理。相机驱动阻塞、串口或 CAN 清理失败也应视为未确认正常关闭,不能仅凭网页已消失判断资源已释放。 - -向维护者反馈时提供版本、执行命令(去除私有路径和身份信息)、错误全文、相关时间段日志与设备状态。不要上传标定、凭据、整份机器配置或未经处理的原始日志。 diff --git a/docs/wiki/_Footer.md b/docs/wiki/_Footer.md deleted file mode 100644 index cf4645a..0000000 --- a/docs/wiki/_Footer.md +++ /dev/null @@ -1 +0,0 @@ -[OpenArm Runtime](https://github.com/TCXM/openarm-runtime) · 文档适用 v0.6.0 · [文档首页](Home.md) · [版本记录](https://github.com/TCXM/openarm-runtime/blob/v0.6.0/CHANGELOG.md) diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md deleted file mode 100644 index db44e05..0000000 --- a/docs/wiki/_Sidebar.md +++ /dev/null @@ -1,13 +0,0 @@ -**OpenArm Runtime · v0.6.0** - -- [文档首页](Home.md) -- [快速上手](Quick-Start.md) -- [安装与配置](Installation.md) -- [CLI 命令参考](CLI-Reference.md) -- [Python API](Python-API.md) -- [日常操作](Operations.md) -- [终端与远程访问](Remote-Access.md) -- [故障排查](Troubleshooting.md) -- [架构与库](Architecture.md) - -[下载 v0.6.0](https://github.com/TCXM/openarm-runtime/releases/tag/v0.6.0) · [反馈问题](https://github.com/TCXM/openarm-runtime/issues) diff --git a/docs/workstation.md b/docs/workstation.md index b029fc2..d84abfc 100644 --- a/docs/workstation.md +++ b/docs/workstation.md @@ -50,7 +50,7 @@ uv pip install --no-build-isolation-package openarm-can "${OPENARM_RUNTIME_ROOT} ``` For a wheel, replace the last argument with -`'/path/to/openarm_runtime-0.6.0-py3-none-any.whl[follower]'`. You can also use +`'/path/to/openarm_runtime-0.4.0-py3-none-any.whl[follower]'`. You can also use `'openarm-runtime[follower] @ git+https://github.com/TCXM/openarm-runtime.git@v0.6.0'`. Consumers do not inherit a dependency repository's uv build settings, so retain the explicit build configuration and `--no-build-isolation-package` option. diff --git a/src/openarm_runtime/__main__.py b/src/openarm_runtime/__main__.py index 492497b..50ae887 100644 --- a/src/openarm_runtime/__main__.py +++ b/src/openarm_runtime/__main__.py @@ -27,6 +27,8 @@ def main(): calibration.add_argument("--side", choices=("left", "right"), required=True) calibration.add_argument("--report-root", type=Path, required=True) calibration.add_argument("--allow-unreadable-mode", action="store_true") + calibration.add_argument("--no-write-zero", action="store_true", + help="Run the physical calibration trajectory without rewriting encoder zeros") for name, help_text in (("view", "Read-only live viewer"), ("panel", "User-operated whole-arm control; startup is read-only")): command = commands.add_parser(name, help=help_text) @@ -163,11 +165,12 @@ def shutdown_leader(signum, frame): datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")+"-"+uuid.uuid4().hex+".json"), {"source": "cli_user", "action": "auto_calibrate", "side": args.side, "interface": profile.interface(args.side), - "allow_unreadable_mode": args.allow_unreadable_mode}) - print("Automatic v2 calibration: motion and zero writes. Ctrl+C stops. Report:", report.path, flush=True) + "allow_unreadable_mode": args.allow_unreadable_mode, "write_zero": not args.no_write_zero}) + print("Automatic v2 calibration: " + ("motion only; NO zero writes" if args.no_write_zero else "motion and zero writes") + + ". Ctrl+C stops. Report:", report.path, flush=True) calibrate_arm(profile, args.side, cancelled=cancel.is_set, record=report.record, progress=lambda message: print(message, flush=True), - allow_unreadable_mode=args.allow_unreadable_mode) + allow_unreadable_mode=args.allow_unreadable_mode, write_zero=not args.no_write_zero) except BaseException as exc: if report: report.record({"event": "ended", "error": f"{type(exc).__name__}: {exc}"}) diff --git a/src/openarm_runtime/arm.py b/src/openarm_runtime/arm.py index f3bfbc7..52bab8e 100644 --- a/src/openarm_runtime/arm.py +++ b/src/openarm_runtime/arm.py @@ -1,21 +1,30 @@ """Persistent whole-arm MIT hold, matching the reference follower gain layout.""" from dataclasses import asdict +from collections import deque import math import time from .telemetry import IDS from .config import finite +from .motion import SmoothMotion +from .limits import joint_bounds_deg, manual_velocity_rad_s, MAX_MANUAL_SPEED_DEG_S -# openarm_follower/config_openarm_follower.py: J1..J7, gripper. +# Adapted LeRobot follower gains: J1..J7, gripper. +# J1/J2 were reduced locally to 30/1.5; these are not stock Enactic gains. FOLLOWER_KP = (30.0, 30.0, 240.0, 240.0, 24.0, 31.0, 25.0, 25.0) FOLLOWER_KD = (1.5, 1.5, 3.0, 5.0, 0.3, 0.3, 0.3, 0.3) class ArmHold: - def __init__(self, bus, cancelled, record, publish, *, tracking=False): + def __init__(self, bus, cancelled, record, publish, *, tracking=False, manual_side=None): self.bus, self.cancelled, self.record, self.publish = bus, cancelled, record, publish self.tracking = tracking + self.manual_bounds = joint_bounds_deg(manual_side) if manual_side is not None else None + self.motion = None + if manual_side is not None: + self.motion = SmoothMotion(joint_bounds_deg(manual_side) | {8: (-30, 30)}, relative_gripper=True) + self.trace = deque(maxlen=200) self.attempted = [] self.states = {} self.base = {} @@ -46,6 +55,13 @@ def __enter__(self): self.check_cancelled() state = self.bus.state(mid) self.validate(state, enabled=False) + if self.motion: + self.motion.validate_position(mid, state.position) + if abs(state.velocity) > .08: + raise RuntimeError(f"ID{mid}: follower must be stationary before enable") + if self.manual_bounds is not None and mid in self.manual_bounds: + lower, upper = self.manual_bounds[mid] + finite(math.degrees(state.position), lower-0.5, upper+0.5, "initial_angle_deg") self.bus.command(mid, "position", state.position, 0, 0) for mid in IDS: self.check_cancelled() @@ -64,9 +80,12 @@ def __enter__(self): self.states[mid] = state self.base = {mid: state.position for mid, state in self.states.items()} self.targets = dict(self.base) + if self.motion: + self.motion.initialize(self.base) self.record({"event": "arm_enabled", "base_rad": self.base, "kp": FOLLOWER_KP, "kd": FOLLOWER_KD, - "sdk_version": self.bus.sdk.__version__}) + "sdk_version": self.bus.sdk.__version__, + "motion_policy": self.motion.metadata() if self.motion else None}) # Ramp all gains together while holding freshly read current angles. for step in range(1, 11): self.tick({mid: 0 for mid in IDS}, 0.5, 0.05, gain_scale=step / 10) @@ -74,15 +93,22 @@ def __enter__(self): return self except BaseException as exc: failures = self.disable() + self.flush_trace(exc) if failures: raise RuntimeError(f"{exc}; disable NOT confirmed: {failures}") from exc raise def __exit__(self, exc_type, exc, tb): failures = self.disable() + self.flush_trace(exc) if failures: raise RuntimeError(f"Disable NOT confirmed: {failures}; original={exc}") from exc + def flush_trace(self, exc): + if self.trace: + self.record({"event": "motion_trace", "error": str(exc) if exc else None, + "samples": list(self.trace)}) + def disable(self): errors = [] # Attempt every disable before checking any reply, even after partial enable. @@ -111,7 +137,7 @@ def disable(self): def tick(self, offsets, speed, period, gain_scale=1): self.check_cancelled() - finite(speed, 0.1, 5, "speed_deg_s") + finite(speed, 0.1, MAX_MANUAL_SPEED_DEG_S if self.manual_bounds is not None else 5, "speed_deg_s") finite(period, 0.02, 0.1, "period_s") finite(gain_scale, 0, 1, "gain_scale") if set(offsets) != set(IDS): @@ -120,17 +146,35 @@ def tick(self, offsets, speed, period, gain_scale=1): kd = [gain_scale * x for x in FOLLOWER_KD] step = math.radians(speed) * period targets = {} + goals = {} for mid in IDS: self.validate(self.states[mid]) - goal = self.base[mid] + math.radians(finite(offsets[mid], -30, 30, "offset_deg")) + if self.manual_bounds is not None and mid in self.manual_bounds: + lower, upper = self.manual_bounds[mid] + base_deg = math.degrees(self.base[mid]) + # Zero writes have 0.5-degree tolerance. Holding that freshly + # captured pose must not itself command a move into the range. + if offsets[mid] == 0 and lower-0.5 <= base_deg <= upper+0.5: + offset = 0.0 + else: + offset = finite(offsets[mid], lower-base_deg, upper-base_deg, "offset_deg") + else: + offset = finite(offsets[mid], -30, 30, "offset_deg") + goal = self.base[mid] + math.radians(offset) if abs(goal) >= self.bus.ranges[mid].position: raise ValueError(f"ID{mid}: target outside firmware range") - q = self.targets[mid] + max(-step, min(step, goal - self.targets[mid])) + goals[mid] = goal + joint_step = step + if self.manual_bounds is not None: + joint_step = min(step, manual_velocity_rad_s(mid, self.bus.ranges[mid].velocity) * period) + q = self.targets[mid] + max(-joint_step, min(joint_step, goal - self.targets[mid])) state = self.states[mid] effort = kp[mid - 1] * (q - state.position) - kd[mid - 1] * state.velocity if abs(effort) > 0.9 * self.bus.ranges[mid].torque: raise RuntimeError(f"ID{mid}: predicted effort near firmware range; error={math.degrees(q-state.position):.2f}°") targets[mid] = q + if self.motion: + targets = self.motion.step(goals, speed, period) self._exchange(targets, kp, kd) def track(self, targets): @@ -151,13 +195,34 @@ def track(self, targets): self._exchange(dict(targets), FOLLOWER_KP, FOLLOWER_KD) def _exchange(self, targets, kp, kd): - states = self.bus.exchange(targets, kp, kd) - if set(states) != set(IDS): - raise RuntimeError("Incomplete arm feedback") - for mid, state in states.items(): - if state.motor_id != mid: - raise RuntimeError("Feedback ID mismatch") - self.validate(state) + frame = None + if self.motion: + frame = {"time_monotonic": time.monotonic(), "targets_rad": dict(targets), + "before": {mid: asdict(s) for mid, s in self.states.items()}, + "requested_rad": dict(self.motion.last_goals), + "target_velocity_rad_s": dict(self.motion.velocities), + "issued_kp": kp, "issued_kd": kd} + self.trace.append(frame) + try: + if self.motion: + self.motion.supervise(self.states, targets, self.bus.ranges, kp, kd, time.monotonic()) + states = self.bus.exchange(targets, kp, kd) + if frame is not None: + frame["feedback"] = {mid: asdict(s) for mid, s in states.items()} + if set(states) != set(IDS): + raise RuntimeError("Incomplete arm feedback") + for mid, state in states.items(): + if state.motor_id != mid: + raise RuntimeError("Feedback ID mismatch") + self.validate(state) + if self.motion: + self.motion.supervise(states, targets, self.bus.ranges, kp, kd, time.monotonic(), after=True) + except BaseException as exc: + if frame is not None: + frame["error"] = str(exc) + if hasattr(exc, "feedback"): + frame["partial_feedback"] = {mid: asdict(s) for mid, s in exc.feedback.items()} + raise self.states, self.targets = states, targets self.publish(states) self.cycles += 1 diff --git a/src/openarm_runtime/calibration.py b/src/openarm_runtime/calibration.py index 91afc76..1bcac60 100644 --- a/src/openarm_runtime/calibration.py +++ b/src/openarm_runtime/calibration.py @@ -422,12 +422,15 @@ def check(mid, expected): def calibrate_arm(profile, side, *, cancelled=_running, record=_ignore, - publish=_ignore, progress=_ignore, allow_unreadable_mode=False): + publish=_ignore, progress=_ignore, allow_unreadable_mode=False, + write_zero=True): """Enable, seek stops, reach computed zero, disable, write/verify zeros. This call moves real hardware. The caller must stop its reader first and ensure the v2 stock arm starts approximately at the official reference pose. - No communication baud, mode or persistence/flash parameters are written. + With write_zero=False the same physical stop-seeking trajectory runs, but + encoder zeros are preserved. The computed pose need not read as zero in the + existing coordinates. No communication baud, mode or flash parameters change. """ if not profile.mapping_verified: raise ValueError("Confirm physical left/right mapping before calibration") @@ -458,8 +461,28 @@ def calibrate_arm(profile, side, *, cancelled=_running, record=_ignore, except Exception: pass # Preserve the motion/disable error if report storage fails. raise - progress("已失能,检查姿态并写入零位…") - write_zeros(bus, zeros, cancelled, record, publish) + if write_zero: + progress("已失能,检查姿态并写入零位…") + write_zeros(bus, zeros, cancelled, record, publish) + else: + progress("已失能,验证结束姿态;保留原有电机零位…") + states = {} + for mid in IDS: + if cancelled(): + raise InterruptedError("Calibration motion stopped; zero writes disabled") + state = bus.state(mid) + if (state.motor_id != mid or state.status != 0 or state.frame_format != "classic" + or not state.fresh(time.monotonic()) + or not math.isfinite(state.position) or not math.isfinite(state.velocity) + or abs(state.velocity) > 0.08 + or abs(state.position-zeros[mid]) > math.radians(0.5)): + raise RuntimeError(f"ID{mid}: disabled end pose moved or feedback invalid; no zero writes") + states[mid] = state + publish(states) + record({"event": "calibration_motion_complete", "zero_write_skipped": True, + "zeroed_ids": [], "computed_zero_rad": zeros, + "positions_rad": {mid: state.position for mid, state in states.items()}}) + progress("标定轨迹完成 · 未写入零位,机械臂已失能") return zeros finally: bus.close() diff --git a/src/openarm_runtime/limits.py b/src/openarm_runtime/limits.py new file mode 100644 index 0000000..75629b3 --- /dev/null +++ b/src/openarm_runtime/limits.py @@ -0,0 +1,30 @@ +"""Stock OpenArm v2 motor coordinates after hardware zero calibration. + +Source: enactic/openarm_description assets/robot/openarm_v2.0/urdf/example/v2.urdf +https://docs.openarm.dev/hardware/openarm-2.0/motor/ +Angles use the degree endpoints already used by our stop calibration (URDF +radians are rounded). Velocities are model/no-load ceilings, not measured +loaded performance. Finger-link limits do not specify gripper motor travel. +""" + +import math + +JOINT_VELOCITY_RAD_S = {1: 16.755, 2: 16.755, 3: 5.4454, 4: 5.4454, + 5: 20.944, 6: 20.944, 7: 20.944} +# The URDF/no-load ceiling is not an operating limit for this 20 Hz position +# controller. High-speed operation needs validated trajectory/effort control. +MAX_MANUAL_SPEED_DEG_S = 5.0 + + +def joint_bounds_deg(side): + if side not in ("left", "right"): + raise ValueError("Select left or right") + return {1: (-80.0, 200.0) if side == "right" else (-200.0, 80.0), + 2: (-10.0, 190.0) if side == "right" else (-190.0, 10.0), + 3: (-90.0, 90.0), 4: (0.0, 140.0), 5: (-90.0, 90.0), + 6: (-45.0, 45.0), 7: (-90.0, 90.0)} + + +def manual_velocity_rad_s(mid, firmware_range): + # No calibrated gripper transmission: retain its existing 5 deg/s command cap. + return min(math.radians(MAX_MANUAL_SPEED_DEG_S), firmware_range) diff --git a/src/openarm_runtime/motion.py b/src/openarm_runtime/motion.py new file mode 100644 index 0000000..29e343e --- /dev/null +++ b/src/openarm_runtime/motion.py @@ -0,0 +1,113 @@ +"""Conservative online trajectories and software supervision, no hardware I/O. + +Rated torque: https://docs.openarm.dev/hardware/openarm-2.0/motor/ +DM8009P J1/J2: 20 Nm; DM4340 J3/J4: 9 Nm; DM4310 J5..J8: 3 Nm. +These software checks are not a drive-level current/torque clamp. Initial +5 deg/s and 10 deg/s² limits are commissioning settings, not rated performance. +""" +import math +from .config import finite +from .telemetry import IDS +from .limits import MAX_MANUAL_SPEED_DEG_S + +RATED_TORQUE_NM = (20., 20., 9., 9., 3., 3., 3., 3.) +MAX_SPEED_DEG_S = MAX_MANUAL_SPEED_DEG_S +ACCELERATION_DEG_S2 = 10.0 + + +class SmoothMotion: + def __init__(self, bounds_deg, *, relative_gripper=False): + if set(bounds_deg) != set(IDS): + raise ValueError('Eight joint bounds required') + self.bounds = {mid: tuple(math.radians(v) for v in pair) + for mid, pair in bounds_deg.items()} + self.relative_gripper = relative_gripper + self.positions = {} + self.velocities = dict.fromkeys(IDS, 0.0) + self.stall_since = dict.fromkeys(IDS) + + def metadata(self): + return {"speed_cap_deg_s": MAX_SPEED_DEG_S, + "acceleration_deg_s2": ACCELERATION_DEG_S2, + "rated_torque_nm": RATED_TORQUE_NM, + "tracking_error_deg": 5, "stall_error_deg": 2, + "stall_speed_deg_s": .5, "stall_duration_s": 1, + "bounds_rad": self.bounds} + + def validate_position(self, mid, position): + if self.relative_gripper and mid == 8 and not self.positions: + finite(position, -12.5, 12.5, 'gripper_position') + return + lower, upper = self.bounds[mid] + finite(position, lower-math.radians(.5), upper+math.radians(.5), f'J{mid} initial angle') + + def initialize(self, positions): + for mid in IDS: + self.validate_position(mid, positions[mid]) + if self.relative_gripper: + self.bounds[8] = (positions[8]-math.radians(30), positions[8]+math.radians(30)) + # Retain the freshly captured pose within encoder/zero tolerance without + # a step to a clipped bound at takeover. New goals use original limits. + self.travel_bounds = {mid: (min(lo, positions[mid]), max(hi, positions[mid])) + for mid, (lo, hi) in self.bounds.items()} + self.positions = dict(positions) + self.last_goals = dict(positions) + self.velocities = dict.fromkeys(IDS, 0.0) + + def step(self, goals, speed_deg_s, dt): + finite(speed_deg_s, .1, MAX_SPEED_DEG_S, 'speed_deg_s') + finite(dt, .02, .1, 'period_s') + if set(goals) != set(IDS) or not self.positions: + raise ValueError('Initialized eight-joint trajectory required') + vmax = math.radians(speed_deg_s) + acceleration = math.radians(ACCELERATION_DEG_S2) + positions, velocities = {}, {} + for mid in IDS: + q, v = self.positions[mid], self.velocities[mid] + lo, hi = self.travel_bounds[mid] + goal = finite(goals[mid], lo, hi, f'J{mid} target') + distance = goal-q + # Discrete braking envelope leaves one acceleration step of margin. + braking = max(0., math.sqrt((acceleration*dt)**2 + 2*acceleration*abs(distance)) - acceleration*dt) + wanted = math.copysign(min(vmax, braking), distance) + next_v = v + max(-acceleration*dt, min(acceleration*dt, wanted-v)) + next_q = q + next_v*dt + # A sudden goal reversal may temporarily pass that goal while braking; + # physical joint boundaries must never be crossed. + if not lo-1e-10 <= next_q <= hi+1e-10: + raise RuntimeError(f'J{mid}: trajectory cannot brake within joint bounds') + positions[mid], velocities[mid] = next_q, next_v + self.last_goals = dict(goals) + self.positions, self.velocities = positions, velocities + return dict(positions) + + def supervise(self, states, targets, ranges, kp, kd, now, *, after=False): + if set(states) != set(IDS): + raise RuntimeError('Incomplete protected motion feedback') + for mid in IDS: + state = states[mid] + self.validate_position(mid, state.position) + limit = min(RATED_TORQUE_NM[mid-1], .9*ranges[mid].torque) + error = targets[mid]-state.position + predicted = kp[mid-1]*error-kd[mid-1]*state.velocity + if abs(state.torque) > limit: + raise RuntimeError(f'J{mid}: measured torque {state.torque:.2f} Nm exceeds {limit:g} Nm') + if abs(predicted) > limit: + raise RuntimeError(f'J{mid}: predicted torque {predicted:.2f} Nm exceeds {limit:g} Nm') + if abs(state.velocity) > 2: + raise RuntimeError(f'J{mid}: feedback velocity limit') + if abs(error) > math.radians(5): + raise RuntimeError( + f'J{mid}: tracking error exceeds 5 degrees; ' + f'target={math.degrees(targets[mid]):.2f} deg, ' + f'measured={math.degrees(state.position):.2f} deg, ' + f'error={math.degrees(error):+.2f} deg, ' + f'torque={state.torque:.2f} Nm, kp={kp[mid-1]:g}, kd={kd[mid-1]:g}') + if after: + stalled = abs(error) > math.radians(2) and abs(state.velocity) < math.radians(.5) + if not stalled: + self.stall_since[mid] = None + elif self.stall_since[mid] is None: + self.stall_since[mid] = now + elif now-self.stall_since[mid] >= 1.0: + raise RuntimeError(f'J{mid}: stalled / sustained tracking error for 1 second') diff --git a/src/openarm_runtime/panel.py b/src/openarm_runtime/panel.py index 521f3e5..5dc0c74 100644 --- a/src/openarm_runtime/panel.py +++ b/src/openarm_runtime/panel.py @@ -2,6 +2,7 @@ from datetime import datetime, timezone from pathlib import Path +import math import threading import time import uuid @@ -10,9 +11,10 @@ from .config import bus_lease, finite from .transport import ClassicBus from .arm import ArmHold, FOLLOWER_KP, FOLLOWER_KD -from .report import Report +from .report import QueuedReport from .control import check_modes from .calibration import calibrate_arm +from .limits import joint_bounds_deg, MAX_MANUAL_SPEED_DEG_S class MotionSession: @@ -29,13 +31,14 @@ def __init__(self, profile, connections, report_root): self.closed = False self.offsets = dict.fromkeys(IDS, 0.0) self.speed = 5.0 + self.base = {} self.message = "待机 · 请选择机械臂和操作" @property def busy(self): return self.lock.locked() - def start(self, owner, side, supported, allow_unreadable, *, calibration=False): + def start(self, owner, side, supported, allow_unreadable, *, calibration=False, write_zero=True): if not supported: raise ValueError("请先确认机械臂可进入使能保持") if not self.profile.mapping_verified: @@ -49,19 +52,30 @@ def start(self, owner, side, supported, allow_unreadable, *, calibration=False): self.offsets = dict.fromkeys(IDS, 0.0) self.message = f"{'左臂' if side == 'left' else '右臂'} · 正在检查…" self.worker = threading.Thread(target=self._run, - args=(interface, allow_unreadable, calibration), daemon=True) + args=(interface, allow_unreadable, calibration, write_zero), daemon=True) try: self.worker.start() except BaseException: self.lock.release() raise - def set_target(self, owner, side, mid, offset): - finite(offset, -30, 30, "offset_deg") + def set_target(self, owner, side, mid, angle): if not self.ready or owner != self.owner or side != self.side or mid not in IDS: raise RuntimeError("请由使能该臂的浏览器操作滑条") with self.target_lock: - self.offsets[mid] = float(offset) + if mid < 8: + lower, upper = joint_bounds_deg(side)[mid] + angle = finite(angle, lower, upper, "angle_deg") + self.offsets[mid] = angle - math.degrees(self.base[mid]) + else: + self.offsets[mid] = finite(angle, -30, 30, "offset_deg") + + def set_speed(self, owner, speed): + speed = finite(speed, 0.1, MAX_MANUAL_SPEED_DEG_S, "speed_deg_s") + if self.busy and owner != self.owner: + raise RuntimeError("请由使能该臂的浏览器调整速度") + with self.target_lock: + self.speed = speed def stop(self, owner=None): if owner is None or owner == self.owner: @@ -75,14 +89,15 @@ def close(self): if self.worker.is_alive(): raise RuntimeError("Control worker shutdown timed out") - def _run(self, interface, allow_unreadable, calibration=False): + def _run(self, interface, allow_unreadable, calibration=False, write_zero=True): connection = self.connections[interface] report = None try: - report = Report(self.report_root / ( + report = QueuedReport(self.report_root / ( datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + uuid.uuid4().hex + ".json"), {"source": "viser_user", "action": "auto_calibrate" if calibration else "arm_hold", "interface": interface, - "kp": FOLLOWER_KP, "kd": FOLLOWER_KD, "allow_unreadable_mode": allow_unreadable}) + "kp": FOLLOWER_KP, "kd": FOLLOWER_KD, "allow_unreadable_mode": allow_unreadable, + "write_zero": write_zero if calibration else None}) connection.close() def publish(states): @@ -98,8 +113,9 @@ def progress(message): self.message = f"{interface} 自动标定:{message}" calibrate_arm(self.profile, self.side, cancelled=self.cancel.is_set, record=report.record, publish=publish, progress=progress, - allow_unreadable_mode=allow_unreadable) - self.message = "标定完成 · 零位已写入并验证,机械臂已失能" + allow_unreadable_mode=allow_unreadable, write_zero=write_zero) + self.message = ("标定完成 · 零位已写入并验证,机械臂已失能" if write_zero else + "标定轨迹完成 · 未写入零位,机械臂已失能") return with bus_lease(interface, exclusive=True): bus = ClassicBus(interface, self.profile.feedback_timeout_s) @@ -108,12 +124,14 @@ def progress(message): modes = check_modes(bus, allow_unreadable, self.cancel.is_set) report.record({"event": "modes", "readback": modes}) - with ArmHold(bus, self.cancel.is_set, report.record, publish) as control: + with ArmHold(bus, self.cancel.is_set, report.record, publish, manual_side=self.side) as control: + self.base = dict(control.base) self.ready = True self.message = f"{interface} 整臂已使能并保持;拖动该臂滑条即可移动。" period = 1 / self.profile.rate_hz previous = time.monotonic() while not self.cancel.is_set(): + report.check() now = time.monotonic() if now - previous > max(0.25, 3 * period): raise RuntimeError("Whole-arm control deadline missed") @@ -140,6 +158,11 @@ def progress(message): connection.restart() except Exception as exc: self.message += f";重新读取失败:{exc}" + if report: + try: + report.close() + except Exception as exc: + self.message += f";日志保存失败:{exc}" self.owner, self.side = None, None self.lock.release() @@ -150,24 +173,26 @@ def attach(server, profile, connections, report_root): status = server.gui.add_markdown(session.message) health = server.gui.add_markdown("正在连接…") side_choice = server.gui.add_dropdown("机械臂", ("右臂", "左臂")) - mode = server.gui.add_dropdown("操作", ("自动标定", "手动控制")) + mode = server.gui.add_dropdown("操作", ("自动标定", "自动标定(不写零位)", "手动控制")) with server.gui.add_folder("标定") as calibration_folder: server.gui.add_markdown( "1. 将选中臂摆到[参考姿态](https://docs.openarm.dev/setup/openarm-setup/motor-config/#step-2-zero-position-calibration)。\n" "2. 清空运动范围,准备在失能时支撑机械臂。\n" "3. 勾选就绪,再点开始。\n\n" - "会自动运动并写入零位。") + "会自动运动并寻找机械限位。选择「自动标定(不写零位)」仅执行轨迹,保留原电机零位;结束位置不保证在原坐标中读作 0°。") calibration_ready = server.gui.add_checkbox("姿态已摆好,运动范围已清空", initial_value=False) calibrate = server.gui.add_button("开始标定", disabled=True) with server.gui.add_folder("手动控制", visible=False) as manual_folder: - server.gui.add_markdown("使能后保持当前位置;滑条调整相对角度。停止或断开操作页面会失能。") - supported = server.gui.add_checkbox("机械臂已就绪", initial_value=False) + server.gui.add_markdown("使能后保持当前位置;J1–J7 使用标定零位下的绝对角度,夹爪为相对偏移。停止或断开操作页面会失能。\n速度暂限 5°/s;高速功能已撤回,过载故障需先排查。") + supported = server.gui.add_checkbox("已完成零位标定,机械臂已就绪", initial_value=False) enable = server.gui.add_button("使能并保持", disabled=True) - speed = server.gui.add_slider("速度 (°/s)", min=0.1, max=5, step=0.1, initial_value=5.0) + speed = server.gui.add_slider("速度 (°/s)", min=0.1, max=MAX_MANUAL_SPEED_DEG_S, step=0.1, initial_value=5.0) sliders = {} for mid in IDS: name = f"J{mid}" if mid < 8 else "夹爪" - slider = server.gui.add_slider(f"{name} 偏移 (°)", min=-30, max=30, step=0.1, + lower, upper = joint_bounds_deg("right").get(mid, (-30, 30)) + label = f"{name} 角度 (°)" if mid < 8 else f"{name} 偏移 (°)" + slider = server.gui.add_slider(label, min=lower, max=upper, step=0.1, initial_value=0.0, disabled=True) sliders[mid] = slider @slider.on_update @@ -181,17 +206,23 @@ def target(event, mid=mid, slider=slider): def selected_side(): return "left" if side_choice.value == "左臂" else "right" + displayed_base = None + @side_choice.on_update @mode.on_update def selection_changed(_event): calibration_ready.value = supported.value = False + for mid, slider in sliders.items(): + if mid < 8: + slider.value = 0.0 + slider.min, slider.max = joint_bounds_deg(selected_side())[mid] @calibrate.on_click def begin_calibration(event): - if event.client is not None and mode.value == "自动标定": + if event.client is not None and mode.value in ("自动标定", "自动标定(不写零位)"): try: session.start(event.client.client_id, selected_side(), calibration_ready.value, - True, calibration=True) + True, calibration=True, write_zero=mode.value == "自动标定") except Exception as exc: session.message = str(exc) @@ -208,8 +239,10 @@ def begin(event): @speed.on_update def speed_changed(event): if event.client is not None and (not session.busy or event.client.client_id == session.owner): - with session.target_lock: - session.speed = float(speed.value) + try: + session.set_speed(event.client.client_id, speed.value) + except Exception as exc: + session.message = str(exc) @stop.on_click def cancel(_event): @@ -220,12 +253,19 @@ def disconnect(client): session.stop(client.client_id) def refresh(): + nonlocal displayed_base + if session.ready and displayed_base is not session.base: + for mid, slider in sliders.items(): + if mid < 8: + lower, upper = joint_bounds_deg(session.side)[mid] + slider.value = max(lower, min(upper, math.degrees(session.base[mid]))) + displayed_base = session.base status.content = session.message for handle in (side_choice, mode, supported, calibration_ready): handle.disabled = session.busy calibrate.disabled = session.busy or not calibration_ready.value enable.disabled = session.busy or not supported.value - calibration_folder.visible = mode.value == "自动标定" + calibration_folder.visible = mode.value in ("自动标定", "自动标定(不写零位)") manual_folder.visible = mode.value == "手动控制" now = time.monotonic() summaries = [] diff --git a/src/openarm_runtime/report.py b/src/openarm_runtime/report.py index bb33427..79646c9 100644 --- a/src/openarm_runtime/report.py +++ b/src/openarm_runtime/report.py @@ -17,10 +17,66 @@ def __init__(self, path, data): json.dump(self.data, handle, indent=2) def record(self, event): - self.data["events"].append({"elapsed_s": time.monotonic() - self.started, **event}) + self.record_at(event, time.monotonic() - self.started) + + def record_at(self, event, elapsed): + self.data["events"].append({"elapsed_s": elapsed, **event}) tmp = self.path.with_suffix(self.path.suffix + ".tmp") with tmp.open("w") as handle: json.dump(self.data, handle, indent=2, allow_nan=False) handle.flush() os.fsync(handle.fileno()) os.replace(tmp, self.path) + + +class QueuedReport: + """Bounded, ordered reporting without disk I/O on a motion thread. + + Capture event time at enqueue, surface writer errors to the controller, and + drain after disable. Queue saturation raises rather than losing evidence. + """ + + def __init__(self, path, data): + import queue + import threading + self.report = Report(path, data) + self.queue = queue.Queue(maxsize=128) + self.stop = threading.Event() + self.error = None + self.worker = threading.Thread(target=self._write, daemon=True, name="openarm-report") + self.worker.start() + + def check(self): + if self.error is not None: + raise RuntimeError(f"Report writer failed: {self.error}") from self.error + + def record(self, event): + import copy + import queue + self.check() + if self.stop.is_set(): + raise RuntimeError("Report is closed") + elapsed = time.monotonic() - self.report.started + try: + self.queue.put_nowait((copy.deepcopy(event), elapsed)) + except queue.Full: + raise RuntimeError("Report queue full; stopping instead of dropping evidence") from None + + def _write(self): + import queue + try: + while not self.stop.is_set() or not self.queue.empty(): + try: + event, elapsed = self.queue.get(timeout=0.1) + except queue.Empty: + continue + self.report.record_at(event, elapsed) + except BaseException as exc: + self.error = exc + + def close(self): + self.stop.set() + self.worker.join(timeout=10) + if self.worker.is_alive(): + raise RuntimeError("Report flush timed out") + self.check() diff --git a/src/openarm_runtime/transport.py b/src/openarm_runtime/transport.py index 0ed9407..a401e59 100644 --- a/src/openarm_runtime/transport.py +++ b/src/openarm_runtime/transport.py @@ -126,7 +126,10 @@ def preflight(self): self.ranges[mid] = MotorRange(*(self.parameter(mid, rid) for rid in (21, 22, 23))) state = self.state(mid) if state.status != 0: - raise RuntimeError(f"ID{mid} must be disabled; status={state.status}") + raise RuntimeError( + f"ID{mid} must be disabled; status={state.status}" + + (" (OVERLOAD/过载;不是零点问题,请排查负载和碰撞,勿重复使能或标定)" + if state.status == 14 else "")) report[mid] = {"baud_code": code, "range": asdict(self.ranges[mid]), "state": asdict(state)} require_classic_link(inspect_link(self.interface)) return report @@ -150,8 +153,10 @@ def collect(cid, data): return states if len(states) == len(IDS) else None try: return self.receive(collect) - except TimeoutError: - raise TimeoutError(f"Missing control feedback IDs {sorted(set(IDS) - set(states))}") from None + except TimeoutError as exc: + failure = TimeoutError(f"Missing control feedback IDs {sorted(set(IDS) - set(states))}") + failure.feedback = dict(states) + raise failure from exc def prepare_encoder(self, ids): import openarm_can as oa diff --git a/tests/test_arm.py b/tests/test_arm.py index d2a3edd..d27145e 100644 --- a/tests/test_arm.py +++ b/tests/test_arm.py @@ -109,6 +109,7 @@ def test_missing_feedback_ends_hold_and_disables_all(self): def test_other_browser_cannot_change_target(self): session = MotionSession(Profile("can1", "can0"), {}, "/unused") session.ready, session.owner, session.side = True, 1, "right" + session.base = dict.fromkeys(IDS, 0.0) for owner, side in ((2, "right"), (1, "left")): with self.assertRaises(RuntimeError): session.set_target(owner, side, 1, 30) diff --git a/tests/test_calibration.py b/tests/test_calibration.py index c2e127b..43ffef9 100644 --- a/tests/test_calibration.py +++ b/tests/test_calibration.py @@ -113,6 +113,38 @@ def test_both_sides_recover_nonzero_offsets_and_write_only_after_disable(self): self.assertFalse(bus.enabled) self.assertLess(self.clock.now, 1000) + def test_motion_only_both_sides_preserve_encoder_coordinates_and_disable(self): + for side in ('left', 'right'): + with self.subTest(side=side): + bus = MechanicalBus(side, self.clock) + bus.set_zero = Mock(side_effect=AssertionError('Must never write zero')) + with patch('openarm_runtime.calibration.bus_lease', return_value=nullcontext()), \ + patch('openarm_runtime.calibration.ClassicBus', return_value=bus), \ + patch('openarm_runtime.calibration.write_zeros') as write: + zeros = calibrate_arm(Profile('can1', 'can0', True), side, + record=self.events.append, write_zero=False) + write.assert_not_called() + bus.set_zero.assert_not_called() + self.assertFalse(bus.enabled) + self.assertTrue(bus.closed) + for mid in IDS: + self.assertAlmostEqual(zeros[mid], bus.zeros[mid]) + self.assertAlmostEqual(bus.positions[mid], bus.zeros[mid]) + self.assertTrue(self.events[-1]['zero_write_skipped']) + self.assertEqual(self.events[-1]['zeroed_ids'], []) + + def test_motion_only_cancel_still_disables_and_never_writes(self): + bus = MechanicalBus('left', self.clock) + bus.set_zero = Mock(side_effect=AssertionError('Must never write zero')) + with patch('openarm_runtime.calibration.bus_lease', return_value=nullcontext()), \ + patch('openarm_runtime.calibration.ClassicBus', return_value=bus): + with self.assertRaises(InterruptedError): + calibrate_arm(Profile('can1', 'can0', True), 'left', write_zero=False, + cancelled=lambda: self.clock.now > 103, record=self.events.append) + self.assertFalse(bus.enabled) + self.assertTrue(bus.closed) + bus.set_zero.assert_not_called() + def test_unsuccessful_seek_is_bounded_and_disables(self): bus = MechanicalBus("right", self.clock) bus.stops[8] = (1, 10) diff --git a/tests/test_manual_limits.py b/tests/test_manual_limits.py new file mode 100644 index 0000000..91c1e4d --- /dev/null +++ b/tests/test_manual_limits.py @@ -0,0 +1,102 @@ +"""Offline motor-limit regressions; never opens real hardware.""" +import math +import unittest +from dataclasses import replace +from unittest.mock import Mock, patch + +from test_arm import FakeBus +from openarm_runtime.arm import ArmHold +from openarm_runtime.config import Profile +from openarm_runtime.limits import joint_bounds_deg, JOINT_VELOCITY_RAD_S +from openarm_runtime.panel import MotionSession +from openarm_runtime.telemetry import IDS, MotorRange + + +class ManualLimitTests(unittest.TestCase): + def arm(self, bus, side='right'): + return ArmHold(bus, lambda: False, Mock(), Mock(), manual_side=side) + + def test_full_range_targets_are_allowed_and_outside_rejected(self): + for side in ('left', 'right'): + bus = FakeBus() + with patch('openarm_runtime.arm.time.sleep'), self.arm(bus, side) as arm: + for mid, bounds in joint_bounds_deg(side).items(): + for angle in bounds: + offsets = dict.fromkeys(IDS, 0.0) | {mid: angle} + arm.tick(offsets, 5, 0.05) + beyond = angle + (-0.01 if angle == bounds[0] else 0.01) + before = dict(bus.last_targets) + with self.assertRaises(ValueError): + arm.tick(offsets | {mid: beyond}, 5, 0.05) + self.assertEqual(bus.last_targets, before) + self.assertFalse(bus.enabled) + + def test_absolute_target_uses_fresh_enable_pose(self): + session = MotionSession(Profile('can1', 'can0'), {}, '/unused') + session.ready, session.owner, session.side = True, 1, 'right' + session.base = dict.fromkeys(IDS, 0.0) | {1: math.radians(150)} + session.set_target(1, 'right', 1, -80) + self.assertAlmostEqual(session.offsets[1], -230) + session.set_target(1, 'right', 1, 200) + self.assertAlmostEqual(session.offsets[1], 50) + for invalid in (-80.1, 200.1, float('nan'), float('inf')): + with self.assertRaises(ValueError): + session.set_target(1, 'right', 1, invalid) + + def test_no_load_speed_cannot_be_requested_by_manual_controller(self): + bus = FakeBus() + with patch('openarm_runtime.arm.time.sleep'), self.arm(bus) as arm: + before = dict(bus.last_targets) + for speed in (5.1, 312, 960, 1200): + with self.assertRaises(ValueError): + arm.tick(dict.fromkeys(IDS, 0.0) | {2: 190}, speed, 0.05) + self.assertEqual(bus.last_targets, before) + arm.tick(dict.fromkeys(IDS, 0.0) | {2: 190}, 5, 0.05) + self.assertAlmostEqual(bus.last_targets[2], math.radians(0.025)) + + def test_manual_feedback_keeps_original_velocity_protection(self): + bus = FakeBus() + with patch('openarm_runtime.arm.time.sleep'), self.arm(bus) as arm: + for mid in IDS: + with self.assertRaisesRegex(RuntimeError, 'velocity limit'): + arm.validate(replace(arm.states[mid], velocity=2.01)) + + def test_out_of_range_start_rejected_before_enable(self): + bus = FakeBus() + bus.positions[1] = math.radians(201) + with patch('openarm_runtime.arm.time.sleep'), self.assertRaises(ValueError): + with self.arm(bus): + pass + self.assertFalse(any(action == 'enable' for _, action in bus.commands)) + + def test_zero_tolerance_holds_without_forcing_movement(self): + bus = FakeBus() + bus.positions[4] = math.radians(-0.01) + with patch('openarm_runtime.arm.time.sleep'), self.arm(bus) as arm: + self.assertEqual(arm.targets[4], bus.positions[4]) + arm.tick(dict.fromkeys(IDS, 0.0), 5, 0.05) + self.assertAlmostEqual(bus.positions[4], math.radians(-0.01)) + + def test_limits_cannot_bypass_firmware_or_gripper_envelope(self): + bus = FakeBus() + with patch('openarm_runtime.arm.time.sleep'), self.arm(bus) as arm: + bus.ranges[1] = MotorRange(1, 30, 28) + for offsets in (dict.fromkeys(IDS, 0.0) | {1: 100}, + dict.fromkeys(IDS, 0.0) | {8: 31}): + with self.assertRaises(ValueError): + arm.tick(offsets, 5, 0.05) + for speed in (0, 1201, float('nan'), float('inf')): + with self.assertRaises(ValueError): + arm.tick(dict.fromkeys(IDS, 0.0), speed, 0.05) + + def test_speed_owner_and_validation(self): + session = MotionSession(Profile('can1', 'can0'), {}, '/unused') + session.set_speed(1, 5) + self.assertEqual(session.speed, 5) + session.owner = 1 + with session.lock: + with self.assertRaises(RuntimeError): + session.set_speed(2, 4) + session.set_speed(1, 4) + with self.assertRaises(ValueError): + session.set_speed(1, float('nan')) diff --git a/tests/test_motion.py b/tests/test_motion.py new file mode 100644 index 0000000..1cd23c7 --- /dev/null +++ b/tests/test_motion.py @@ -0,0 +1,122 @@ +"""Offline manual trajectory and supervision tests; no physical transport.""" +import math +import random +import unittest +from dataclasses import replace +from unittest.mock import Mock, patch + +from test_arm import FakeBus +from openarm_runtime.arm import ArmHold, FOLLOWER_KP, FOLLOWER_KD +from openarm_runtime.motion import SmoothMotion +from openarm_runtime.telemetry import IDS + + +class MotionTests(unittest.TestCase): + def motion(self, base=None): + motion = SmoothMotion(dict.fromkeys(IDS, (-90, 90))) + motion.initialize(base or dict.fromkeys(IDS, 0.0)) + return motion + + def test_step_target_has_bounded_velocity_acceleration_and_settles(self): + m = self.motion() + goals = dict.fromkeys(IDS, math.radians(20)) + last_q = dict(m.positions) + last_v = dict(m.velocities) + for _ in range(180): + q = m.step(goals, 5, .05) + for mid in IDS: + v = (q[mid]-last_q[mid])/.05 + self.assertLessEqual(abs(v), math.radians(5)+1e-10) + self.assertLessEqual(abs(v-last_v[mid]), math.radians(10)*.05+1e-10) + self.assertLessEqual(q[mid], goals[mid]+1e-10) + last_v[mid] = v + last_q = q + self.assertAlmostEqual(q[1], goals[1], places=6) + self.assertLess(abs(m.velocities[1]), 1e-6) + + def test_reversals_and_lower_speed_brake_without_position_jump(self): + m = self.motion() + random.seed(17) + for i in range(2000): + goal = math.radians(random.choice((-90, -10, 0, 10, 90))) if i % 10 == 0 else goal + previous_q, previous_v = dict(m.positions), dict(m.velocities) + q = m.step(dict.fromkeys(IDS, goal), 5 if i % 100 < 50 else .1, .05) + for mid in IDS: + self.assertLessEqual(abs(q[mid]-previous_q[mid]), math.radians(5)*.05+1e-10) + self.assertLessEqual(abs(m.velocities[mid]-previous_v[mid]), math.radians(10)*.05+1e-10) + self.assertTrue(-math.pi/2 <= q[mid] <= math.pi/2) + + def test_braking_at_both_joint_boundaries(self): + m = self.motion(dict.fromkeys(IDS, math.radians(89))) + for angle in (90, -90, 90): + for _ in range(850): + q = m.step(dict.fromkeys(IDS, math.radians(angle)), 5, .05) + self.assertTrue(all(-math.pi/2-1e-10 <= v <= math.pi/2+1e-10 for v in q.values())) + self.assertAlmostEqual(q[1], math.radians(angle), places=6) + + def test_nonstationary_manual_arm_is_not_enabled(self): + bus = FakeBus() + original = bus.state + bus.state = lambda mid: replace(original(mid), velocity=.2) + with patch('openarm_runtime.arm.time.sleep'), self.assertRaisesRegex(RuntimeError, 'stationary'): + with ArmHold(bus, lambda: False, Mock(), Mock(), manual_side='right'): + pass + self.assertFalse(any(action=='enable' for _, action in bus.commands)) + + def test_initial_pose_and_nonfinite_target_rejected(self): + m = self.motion() + for value in (float('nan'), float('inf'), math.radians(91)): + with self.assertRaises(ValueError): + m.step(dict.fromkeys(IDS, value), 5, .05) + with self.assertRaises(ValueError): + m.initialize(dict.fromkeys(IDS, math.radians(91))) + + def test_torque_uses_motor_rating_not_firmware_encoding(self): + bus = FakeBus() + m = self.motion() + states = {mid: bus.state(mid) for mid in IDS} + for mid, torque in ((1, 20.1), (3, 9.1), (5, 3.1)): + with self.assertRaisesRegex(RuntimeError, 'measured torque'): + m.supervise(states | {mid: replace(states[mid], torque=torque)}, + dict.fromkeys(IDS, 0.), bus.ranges, FOLLOWER_KP, FOLLOWER_KD, 0) + # 4 deg tracking error on J3: below tracking threshold, above 9 Nm rated. + with self.assertRaisesRegex(RuntimeError, 'predicted torque'): + m.supervise(states, dict.fromkeys(IDS, 0.) | {3: math.radians(4)}, + bus.ranges, FOLLOWER_KP, FOLLOWER_KD, 0) + + def test_tracking_and_sustained_stall_are_distinct_and_stop(self): + bus, m = FakeBus(), self.motion() + states = {mid: bus.state(mid) for mid in IDS} + targets = dict.fromkeys(IDS, 0.) | {1: math.radians(6)} + with self.assertRaisesRegex(RuntimeError, 'tracking error'): + m.supervise(states, targets, bus.ranges, FOLLOWER_KP, FOLLOWER_KD, 0) + targets[1] = math.radians(3) + m.supervise(states, targets, bus.ranges, FOLLOWER_KP, FOLLOWER_KD, 10, after=True) + m.supervise(states, targets, bus.ranges, FOLLOWER_KP, FOLLOWER_KD, 10.9, after=True) + with self.assertRaisesRegex(RuntimeError, 'stalled'): + m.supervise(states, targets, bus.ranges, FOLLOWER_KP, FOLLOWER_KD, 11.1, after=True) + states[1] = replace(states[1], position=targets[1]) + m.supervise(states, targets, bus.ranges, FOLLOWER_KP, FOLLOWER_KD, 12, after=True) + self.assertIsNone(m.stall_since[1]) + + def test_trace_contains_fault_frame_and_is_written_after_disable(self): + bus = FakeBus() + events = [] + def record(event): + if event['event'] == 'motion_trace': + self.assertFalse(bus.enabled) + events.append(event) + with patch('openarm_runtime.arm.time.sleep'): + with self.assertRaisesRegex(RuntimeError, 'status=14'): + with ArmHold(bus, lambda: False, record, Mock(), manual_side='right') as arm: + original = bus.exchange + def fail(*args): + states = original(*args) + states[2] = replace(states[2], status=14) + return states + bus.exchange = fail + arm.tick(dict.fromkeys(IDS, 0.), 5, .05) + trace = next(e for e in events if e['event']=='motion_trace') + self.assertEqual(trace['samples'][-1]['feedback'][2]['status'], 14) + self.assertIn('status=14', trace['samples'][-1]['error']) + self.assertFalse(bus.enabled) diff --git a/tests/test_queued_report.py b/tests/test_queued_report.py new file mode 100644 index 0000000..e09578e --- /dev/null +++ b/tests/test_queued_report.py @@ -0,0 +1,66 @@ +import json +from pathlib import Path +import tempfile +import threading +import unittest +from unittest.mock import patch + +from openarm_runtime.report import QueuedReport, Report + + +class QueuedReportTests(unittest.TestCase): + def test_slow_disk_does_not_block_producer_and_flush_preserves_order(self): + entered, release = threading.Event(), threading.Event() + original = Report.record_at + def slow(report, event, elapsed): + entered.set() + if not release.wait(3): + raise TimeoutError('test writer was not released') + original(report, event, elapsed) + with tempfile.TemporaryDirectory() as root, patch.object(Report, 'record_at', slow): + path = Path(root)/'report.json' + report = QueuedReport(path, {}) + try: + report.record({'event': 'first'}) + self.assertTrue(entered.wait(1)) + sample = {'event': 'sample', 'values': [1]} + report.record(sample) # Must complete while disk writer is blocked. + sample['values'][0] = 99 + self.assertEqual(report.queue.qsize(), 1) + finally: + release.set() + report.close() + events = json.loads(path.read_text())['events'] + self.assertEqual([e['event'] for e in events], ['first', 'sample']) + self.assertEqual(events[1]['values'], [1]) + self.assertLessEqual(events[0]['elapsed_s'], events[1]['elapsed_s']) + + def test_writer_failure_is_reported_in_control_check_and_close(self): + with tempfile.TemporaryDirectory() as root, patch.object(Report, 'record_at', side_effect=OSError('disk full')): + report = QueuedReport(Path(root)/'report.json', {}) + report.record({'event': 'sample'}) + report.worker.join(1) + self.assertFalse(report.worker.is_alive()) + for call in (report.check, report.close): + with self.assertRaisesRegex(RuntimeError, 'disk full'): + call() + + def test_queue_is_bounded_and_cannot_silently_drop_events(self): + entered, release = threading.Event(), threading.Event() + def slow(*args): + entered.set() + release.wait(3) + with tempfile.TemporaryDirectory() as root, patch.object(Report, 'record_at', slow): + report = QueuedReport(Path(root)/'report.json', {}) + try: + report.record({'event': 'first'}) + self.assertTrue(entered.wait(1)) + for _ in range(128): + report.record({'event': 'queued'}) + with self.assertRaisesRegex(RuntimeError, 'queue full'): + report.record({'event': 'overflow'}) + finally: + release.set() + report.close() + with self.assertRaisesRegex(RuntimeError, 'closed'): + report.record({'event': 'late'}) diff --git a/tests/test_runtime.py b/tests/test_runtime.py index 4c301f3..842297e 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -131,13 +131,16 @@ def on_click(self, callback): SimpleNamespace(client=SimpleNamespace(client_id=42))) self.assertEqual(session.start.call_args.args[:2], (42, side)) self.assertIs(session.start.call_args.args[3], True) - self.assertEqual(session.start.call_args.kwargs, {"calibration": True}) + self.assertEqual(session.start.call_args.kwargs, {"calibration": True, "write_zero": True}) + handles["操作"].value = "自动标定(不写零位)" + handles["开始标定"].callback(SimpleNamespace(client=SimpleNamespace(client_id=42))) + self.assertEqual(session.start.call_args.kwargs, {"calibration": True, "write_zero": False}) session.start.reset_mock() for side, label in (("right", "右臂"), ("left", "左臂")): handles["机械臂"].value = label for mid in range(1, 9): name = f"J{mid}" if mid < 8 else "夹爪" - slider = handles[f"{name} 偏移 (°)"] + slider = handles[f"{name} 角度 (°)" if mid < 8 else f"{name} 偏移 (°)"] slider.value = 1.2 slider.callback(SimpleNamespace(client=SimpleNamespace(client_id=42))) self.assertEqual(session.set_target.call_args.args, (42, side, mid, 1.2)) From b63240775e20d3896987b1971cbcaec93512e6a5 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 1 Nov 2026 17:01:36 +0800 Subject: [PATCH 3/6] feat: integrate policy visualization into the platform --- CHANGELOG.md | 8 + README.md | 7 + docs/platform.md | 32 +++- src/openarm_platform/app.py | 40 +++-- src/openarm_platform/config.py | 16 +- src/openarm_platform/dashboard.py | 14 +- src/openarm_platform/policy.py | 232 ++++++++++++++++++++++++++++ src/openarm_platform/policy_view.py | 212 +++++++++++++++++++++++++ src/openarm_platform/proxy.py | 2 + tests/test_platform.py | 16 +- tests/test_platform_dashboard.py | 14 +- tests/test_policy_preview.py | 185 ++++++++++++++++++++++ 12 files changed, 750 insertions(+), 28 deletions(-) create mode 100644 src/openarm_platform/policy.py create mode 100644 src/openarm_platform/policy_view.py create mode 100644 tests/test_policy_preview.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b2344ab..0fb3841 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## Unreleased — local v0.7.0 integration + +- Merge v0.7.0 policy/gravity support with retained motor-control calibration, + absolute manual targets, queued reporting and read-only CAN recovery. +- Add same-origin policy visualization, simulated sessions and bounded recording + replay to the platform, including attach-only mode. + + ## 0.7.0 — 2026-11-01 - Add optional Pinocchio gravity feedforward shared by hold, panel, teleoperation diff --git a/README.md b/README.md index 9b2ba87..cad1003 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,13 @@ Python 3.12 · MIT · Linux SocketCAN for followers · Independent community pro ## Policy execution and gravity compensation +This integration branch adds **策略可视化** to the platform at `/#policy` +(standalone same-origin page: `/policy`). It displays submitted targets and +recorded feedback separately, inference latency and a joint timeline. Built-in +simulated policies and episode replay work in `--attach-only` mode. This page +uses the v0.7.0 policy contracts; it does not launch the Classic motor backend. +See [platform policy visualization](docs/platform.md#policy-visualization). + Optional [physical gravity compensation](docs/gravity.md) adds shared model-based feedforward to hold, teleoperation and policy control, with shadow diagnostics and per-machine configuration. Install the `gravity` extra; active physical validation diff --git a/docs/platform.md b/docs/platform.md index 06ce40f..6ff09eb 100644 --- a/docs/platform.md +++ b/docs/platform.md @@ -1,7 +1,7 @@ # OpenArm Platform `openarm-runtime platform` brings motor control, teleoperation, tactile and -vision into one local workspace at **http://127.0.0.1:8888**. Use the sidebar to +vision and policy visualization into one local workspace at **http://127.0.0.1:8888**. Use the sidebar to open each module; all pages, images and WebSocket connections pass through this one address. The dashboard uses NiceGUI components on FastAPI/Uvicorn, and aiohttp handles upstream HTTP, streaming responses and WebSocket connections. @@ -172,3 +172,33 @@ Tactile's nested viewers use `/apps/tactile/_extra/0/` and are forwarded through these paths without requiring client access to the internal ports. `/api/status` reports page service availability; it does not report synchronized hardware data or certify that a motor is disabled. + +## Policy visualization + +This integration branch adds an internal **策略可视化** module at +`http://127.0.0.1:8888/#policy`; `/policy` opens it without the dashboard shell. +It uses the same NiceGUI server and needs no extra port or device service. +Existing platform profiles continue to work. The page is also available in +`--attach-only` mode and does not switch or stop a hardware module. + +- Start the built-in J1 sine or hold-pose simulation (1–60 seconds). The page + runs a v0.7.0 `PolicySession`, process-isolated inference and `SimulatedRobot`. + Simulation is an ideal position plant, not measured hardware performance. +- Choose a joint to compare submitted targets with timestamped feedback + observations. The page also shows the latest inference latency and command + count. After the session, play or drag the timeline to inspect joint values. +- Open a CLI recording from a child directory of `~/openarm-episodes`. Set the + optional top-level `policy_record_root` in the external platform JSON to use + another location. Relative paths resolve beside that JSON file. The loader + reads `events.jsonl` and only robot-state array sidecars, never image arrays + or policy plugins. Recordings with no ending event are marked incomplete. + +The view retains the latest 2,000 sampling events and limits recording files +to 64 MiB. Curves are sampled to at most 701 points per series for rendering; +the timeline table uses the retained samples. Recorded feedback is historical, +not the current robot pose. Replay does not resubmit commands to hardware. + +One simulated session is shared by all browser views. Closing a tab leaves the +bounded simulation running; Stop or server shutdown cancels it and closes the +inference worker. Physical policy execution remains an explicit CLI/API operation +as documented in [policy.md](policy.md). diff --git a/src/openarm_platform/app.py b/src/openarm_platform/app.py index 2c7e22a..cfa1a04 100644 --- a/src/openarm_platform/app.py +++ b/src/openarm_platform/app.py @@ -18,8 +18,9 @@ class Coordinator: waits for those operations before the manager performs its final cleanup. """ - def __init__(self, manager, *, attach_only=False): + def __init__(self, manager, *, attach_only=False, builtin_pages=()): self.manager = manager + self.builtin_pages = tuple(builtin_pages) self.attach_only = attach_only self.closing = False self._operations = set() @@ -40,13 +41,17 @@ async def start(self): if not self.attach_only: await self._call(self.manager.start) + def with_builtin(self, states): + return {**states, **{name: dict(reachable=True, state='running', managed=False, generation=0) + for name in self.builtin_pages}} + async def status(self): - return await self._call(self.manager.status) + return self.with_builtin(await self._call(self.manager.status)) async def activate(self, name): - if self.attach_only: + if self.attach_only or name in self.builtin_pages: return await self.status() - return await self._call(self.manager.activate, name) + return self.with_builtin(await self._call(self.manager.activate, name)) def begin_shutdown(self): self.closing = True @@ -120,8 +125,11 @@ def create_app(config, manager=None, *, attach_only=False, with_ui=True): if manager is None: manager = ServiceManager(config.services, config.log_dir) - coordinator = Coordinator(manager, attach_only=attach_only) + coordinator = Coordinator(manager, attach_only=attach_only, + builtin_pages=(p.id for p in config.pages if p.path)) gateway = Gateway(config) + from .policy import PolicyPreview + preview = PolicyPreview(config.policy_record_root) @asynccontextmanager async def lifespan(app): @@ -132,16 +140,20 @@ async def lifespan(app): finally: coordinator.begin_shutdown() try: - await gateway.close() - finally: try: - await coordinator.close() - except BaseException as exc: - app.state.shutdown_error = exc - raise + await asyncio.to_thread(preview.close) + finally: + try: + await gateway.close() + finally: + await coordinator.close() + except BaseException as exc: + app.state.shutdown_error = exc + raise app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None) app.state.gateway = gateway + app.state.policy_preview = preview app.state.coordinator = coordinator app.state.shutdown_error = None app.add_middleware(LocalBoundary) @@ -180,6 +192,12 @@ async def select(request: Request): gateway.install(app) if with_ui: + from .policy_view import build_policy_view + + @ui.page('/policy', title='策略可视化 · OpenArm') + async def policy_page(): + build_policy_view(preview) + async def dashboard(): await build_dashboard(config, coordinator, attach_only=attach_only) ui.run_with(app, root=dashboard, title=config.title, language='zh-CN', diff --git a/src/openarm_platform/config.py b/src/openarm_platform/config.py index 8fa9265..f1871d8 100644 --- a/src/openarm_platform/config.py +++ b/src/openarm_platform/config.py @@ -1,5 +1,5 @@ """External launch configuration for the local platform; no hardware imports.""" -from dataclasses import dataclass, replace +from dataclasses import dataclass, field, replace import json from pathlib import Path import sys @@ -22,17 +22,19 @@ def valid_port(value): class Page: id: str label: str - port: int + port: int | None description: str = '' command: tuple[str, ...] = () cwd: Path | None = None exclusive_group: str | None = None extra_ports: tuple[int, ...] = () + path: str | None = None + def public(self): return dict(id=self.id, label=self.label, port=self.port, description=self.description, exclusive_group=self.exclusive_group, - extra_ports=list(self.extra_ports)) + extra_ports=list(self.extra_ports), path=self.path) @dataclass(frozen=True) @@ -42,10 +44,11 @@ class PlatformConfig: log_dir: Path support: tuple[Page, ...] = () title: str = 'OpenArm Platform' + policy_record_root: Path = field(default_factory=lambda: Path.home() / 'openarm-episodes') @property def services(self): - return self.support + self.pages + return self.support + tuple(page for page in self.pages if page.path is None) def with_port(self, port): return validate(replace(self, port=valid_port(port))) @@ -64,7 +67,7 @@ def validate(config): def load_config(path=None): data = {} if path is None else json.loads(Path(path).expanduser().read_text()) - if not isinstance(data, dict) or set(data) - {'title', 'port', 'services', 'support', 'log_dir'}: + if not isinstance(data, dict) or set(data) - {'title', 'port', 'services', 'support', 'log_dir', 'policy_record_root'}: raise ValueError('Invalid platform configuration fields') base = Path.cwd() if path is None else Path(path).expanduser().resolve().parent entries = data.get('services', {}) @@ -110,6 +113,7 @@ def page_from(entry, identity, label, port, description='', group=None): title = data.get('title', 'OpenArm Platform') if not isinstance(title, str) or not title.strip(): raise ValueError('title must be a nonempty string') + pages.append(Page('policy', '策略可视化', None, '策略仿真、目标与反馈轨迹、记录回放', path='/policy')) return validate(PlatformConfig(valid_port(data.get('port', 8888)), tuple(pages), path_value(data.get('log_dir', '~/.local/state/openarm-platform')), - tuple(auxiliary), title)) + tuple(auxiliary), title, path_value(data.get('policy_record_root', '~/openarm-episodes')))) diff --git a/src/openarm_platform/dashboard.py b/src/openarm_platform/dashboard.py index 2879788..f7e35cd 100644 --- a/src/openarm_platform/dashboard.py +++ b/src/openarm_platform/dashboard.py @@ -9,7 +9,7 @@ ICONS = {'control': 'tune', 'teleop': 'precision_manufacturing', - 'tactile': 'touch_app', 'vision': 'videocam'} + 'tactile': 'touch_app', 'vision': 'videocam', 'policy': 'timeline'} STATUS_LABELS = {'running': '服务可达', 'external': '服务可达', 'starting': '启动中', 'standby': '待切换', 'stopped': '已停止', 'unconfigured': '未配置', 'error': '服务异常'} @@ -99,7 +99,7 @@ def _build(self): with tag(ui.column().classes('platform-overview'), 'overview') as self.overview_panel: ui.label('YOUR ROBOTICS WORKSPACE').classes('eyebrow') tag(ui.label(config_title).classes('overview-title'), 'overview-title') - ui.label('电机控制、遥操、触觉与视觉,一个地址即可使用。').classes('overview-description') + ui.label('电机控制、遥操、感知与策略可视化,一个地址即可使用。').classes('overview-description') with tag(ui.grid(columns=2).classes('module-grid'), 'module-grid'): for index, page in enumerate(self.pages.values(), 1): with ui.card().classes('module-card'): @@ -121,7 +121,7 @@ def _build(self): ui.label('服务就绪后自动显示模块。').classes('waiting-description') self.views.set_visibility(False) with ui.row().classes('platform-footer'): - self.footer = tag(ui.label('四个模块 · 同一个工作空间'), 'footer-caption') + self.footer = tag(ui.label('五个模块 · 同一个工作空间'), 'footer-caption') tag(ui.button('连接帮助', icon='north_east', on_click=self.show_connection) .props('flat dense no-caps').classes('footer-help'), 'footer-connection') with tag(ui.dialog(), 'connection-dialog') as self.connection_dialog: @@ -271,7 +271,7 @@ def _sync_frames(self): if self.active not in self.frames: with self.views: element = self.ui.element('iframe').props( - f'src=/apps/{page.id}/ title="{page.label} · OpenArm" allowfullscreen' + f'src={page.path or f"/apps/{page.id}/"} title="{page.label} · OpenArm" allowfullscreen' ).classes('module-frame') self.identify(element, f'frame-{page.id}') self.frames[self.active] = FrameView(element, generation) @@ -309,7 +309,7 @@ def _render(self): self.current_label.set_text(page.label) self.current_status.set_text('状态未知' if self.status_error else '服务可达' if ready else STATUS_LABELS.get(state.get('state'), '状态未知')) self.reload.set_enabled(ready and not self.busy) - self.external.props(f'href=/apps/{page.id}/ aria-disabled={str(not ready or self.busy).lower()} tabindex={-1 if not ready or self.busy else 0}') + self.external.props(f'href={page.path or f"/apps/{page.id}/"} aria-disabled={str(not ready or self.busy).lower()} tabindex={-1 if not ready or self.busy else 0}') self.external.classes(add='disabled-link' if not ready or self.busy else '', remove='' if not ready or self.busy else 'disabled-link') if not message: if self.status_error: @@ -325,10 +325,10 @@ def _render(self): }.get(state.get('state'), f'{page.label}暂时不可达,请检查模块连接。') self.waiting_title.set_text(('正在启动' if state.get('state') == 'starting' else '等待') + page.label) self.footer.set_text('控制与遥操共享电机连接 · 切换模式会执行原有停止流程' if page.exclusive_group - else '切换到感知页面会保留当前控制或遥操连接') + else '策略页支持仿真和记录回放 · 当前设备连接保持不变' if page.path else '切换到感知页面会保留当前控制或遥操连接') else: self.current_label.set_text('概览') - self.footer.set_text('四个模块 · 同一个工作空间') + self.footer.set_text('五个模块 · 同一个工作空间') self.notice.set_text(message) self.notice.set_visibility(bool(message)) self._sync_frames() diff --git a/src/openarm_platform/policy.py b/src/openarm_platform/policy.py new file mode 100644 index 0000000..2e180a7 --- /dev/null +++ b/src/openarm_platform/policy.py @@ -0,0 +1,232 @@ +"""Bounded policy traces and simulated previews; no physical robot backend.""" +from collections import deque +import copy +from dataclasses import asdict, is_dataclass +import json +import math +from pathlib import Path +import threading + +from openarm_policy.adapters import HoldPolicy +from openarm_policy.contracts import ActionChunk + + +class PreviewSinePolicy(HoldPolicy): + """Small deterministic demo, used only with SimulatedRobot by this page.""" + def reset(self, context): + super().reset(context) + self.base = self.origin = None + + def infer(self, observation): + if self.base is None: + self.base = super().infer(observation).steps[0] + self.origin = observation.captured_at + steps = tuple(tuple(q + math.radians(3) * math.sin(2 * math.pi * + (observation.captured_at - self.origin + i * .05) / 4) + if name.endswith('.joint1') else q + for name, q in zip(self.context.action.names, self.base)) + for i in range(20)) + for values in steps: + self.context.action.validate(values) + return ActionChunk(observation.sequence, observation.captured_at, .05, + steps, self.context.action.names) + + +def number(value): + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise ValueError('记录包含无效数值') + return float(value) + + +class PolicyTrace: + """Retain the latest 2,000 sampling events, without images or tactile arrays.""" + def __init__(self, source='等待策略'): + self.lock = threading.Lock() + self.points = deque(maxlen=2000) + self.names = [] + self.origin = None + self.source = source + self.state = 'idle' + self.error = '' + self.commands = self.chunks = self.revision = 0 + self.latency_ms = None + self.task = '' + + def record(self, event): + with self.lock: + kind = event.get('event') + if kind not in ('context', 'observation', 'command', 'chunk', 'ended'): + return + timestamp = number(event.get('time', self.origin or 0)) + if self.origin is None: + self.origin = timestamp + self.revision += 1 + if kind == 'context': + context = event['context'] + if is_dataclass(context): + context = asdict(context) + names = context['action']['names'] + if (context.get('version', 1) != 1 or context['action'].get('version', 1) != 1 + or context['action'].get('kind', 'joint_position_rad') != 'joint_position_rad' + or not names or len(names) > 16 or len(set(names)) != len(names)): + raise ValueError('记录的动作协议或关节顺序无效') + for name in names: + side, joint = name.split('.') + if side not in ('left', 'right') or joint not in (*[f'joint{i}' for i in range(1, 8)], 'gripper_motor'): + raise ValueError('记录包含未知关节') + self.names = list(names) + self.task = str(context.get('task', '')) + self.state = 'starting' + elif kind == 'observation': + obs = event['observation'] + streams = obs.streams if hasattr(obs, 'streams') else obs['streams'] + captured = obs.captured_at if hasattr(obs, 'captured_at') else obs['captured_at'] + values = [] + for name in self.names: + side, joint = name.split('.') + history = streams.get(f'robot/{side}', ()) + sample = history[-1] if history else None + if sample is None: + values.append(None) + continue + valid = sample.valid if hasattr(sample, 'valid') else sample.get('valid', True) + data = sample.data if hasattr(sample, 'data') else sample['data'] + index = 7 if joint == 'gripper_motor' else int(joint[5:]) - 1 + values.append(number(data[index][0]) if valid else None) + self.points.append(dict(time=number(captured)-self.origin, kind='feedback', values=values)) + self.state = 'running' + elif kind == 'command': + values = list(map(number, event['values'])) + if len(values) != len(self.names): + raise ValueError('记录的目标数量与关节顺序不符') + self.commands += 1 + self.points.append(dict(time=timestamp-self.origin, kind='target', values=values)) + elif kind == 'chunk': + self.chunks += 1 + self.latency_ms = number(event.get('latency_s', 0)) * 1000 + elif kind == 'ended': + self.state = str(event.get('state', 'stopped')) + self.error = '; '.join(filter(None, [str(event.get('error', '')), *map(str, event.get('cleanup_errors', ())) ])) + + def snapshot(self): + with self.lock: + return dict(source=self.source, state=self.state, error=self.error, names=list(self.names), + points=copy.deepcopy(list(self.points)), commands=self.commands, chunks=self.chunks, + latency_ms=self.latency_ms, task=self.task, revision=self.revision) + + +class PolicyPreview: + """Shared simulation lifetime; opening a page only reads this state.""" + def __init__(self, record_root): + self.record_root = Path(record_root).expanduser().resolve() + self.lock = threading.Lock() + self.trace = PolicyTrace() + self.session = self.worker = None + self.loading = self.closed = False + self.generation = 0 + + def _require_idle(self): + if self.closed or self.loading or self.worker is not None and self.worker.is_alive(): + raise RuntimeError('请先停止当前仿真,等待结束后再操作') + + def start(self, policy='sine', duration=10): + if policy not in ('sine', 'hold') or not 1 <= number(duration) <= 60: + raise ValueError('请选择内置仿真策略,时长为 1–60 秒') + from openarm_policy.robots import SimulatedRobot + from openarm_policy.session import PolicySession, SessionConfig + with self.lock: + self._require_idle() + self.generation += 1 + self.trace = PolicyTrace('仿真 · J1 正弦' if policy == 'sine' else '仿真 · 保持姿态') + self.session = PolicySession(SimulatedRobot(), PreviewSinePolicy() if policy == 'sine' else HoldPolicy(), + config=SessionConfig(reset_timeout_s=5), recorder=self.trace) + session, trace = self.session, self.trace + def run(): + try: + session.run(duration) + except Exception as exc: + trace.record(dict(event='ended', state='failed', error=str(exc))) + self.worker = threading.Thread(target=run, name='openarm-policy-preview', daemon=True) + self.worker.start() + + def stop(self): + with self.lock: + if self.session is not None: + self.session.stop() + + def close(self): + with self.lock: + self.closed = True + if self.session is not None: + self.session.stop() + worker = self.worker + if worker is not None: + worker.join(timeout=10) + if worker.is_alive(): + raise RuntimeError('仿真退出超时') + + def snapshot(self): + with self.lock: + trace = self.trace + generation = self.generation + busy = self.loading or self.worker is not None and self.worker.is_alive() + return dict(trace.snapshot(), busy=bool(busy), generation=generation) + + def episodes(self): + if not self.record_root.is_dir(): + return [] + return sorted(p.name for p in self.record_root.iterdir() + if p.is_dir() and not p.is_symlink() and (p/'events.jsonl').is_file()) + + def load(self, name): + with self.lock: + self._require_idle() + self.loading = True + try: + root = (self.record_root / name).resolve() + if not name or root.parent != self.record_root or name != root.name: + raise ValueError('请选择记录目录中的一个会话') + path = (root/'events.jsonl').resolve() + if path.parent != root or not path.is_file() or path.stat().st_size > 64 * 1024 * 1024: + raise ValueError('记录路径无效,或超过 64 MiB 预览上限') + trace = PolicyTrace('记录回放 · ' + name) + size = 0 + with path.open() as handle: + for line in handle: + size += len(line.encode()) + if size > 64 * 1024 * 1024: + raise ValueError('记录超过 64 MiB 预览上限') + if len(line) > 2 * 1024 * 1024: + raise ValueError('单条记录过大') + event = json.loads(line) + if event.get('event') == 'observation': + for key, history in event['observation']['streams'].items(): + if not key.startswith('robot/'): + continue + # Load only robot state matrices, never camera/tactile arrays. + for sample in history[-1:]: + data = sample['data'] + if isinstance(data, dict) and set(data) == {'array'}: + array = (root/data['array']).resolve() + if array.parent != root or array.stat().st_size > 4096: + raise ValueError('关节状态数组路径或大小无效') + import numpy as np + values = np.load(array, allow_pickle=False) + if values.shape != (8, 3): + raise ValueError('关节状态数组必须为 8 × 3') + sample['data'] = values.tolist() + trace.record(event) + if not trace.names or not trace.points: + raise ValueError('记录缺少动作上下文或关节采样') + if trace.state in ('starting', 'running'): + trace.state = 'incomplete' + with self.lock: + if self.closed: + raise RuntimeError('页面服务已关闭') + self.trace = trace + self.generation += 1 + except (KeyError, TypeError, IndexError) as exc: + raise ValueError(f'记录结构无效:{exc}') from exc + finally: + with self.lock: + self.loading = False diff --git a/src/openarm_platform/policy_view.py b/src/openarm_platform/policy_view.py new file mode 100644 index 0000000..912b699 --- /dev/null +++ b/src/openarm_platform/policy_view.py @@ -0,0 +1,212 @@ +"""Native NiceGUI policy visualization inside the existing platform origin.""" +import asyncio +import math +import time + +STATES = {'idle': '等待策略', 'starting': '初始化', 'running': '运行中', + 'stopped': '已结束', 'failed': '已停止 · 异常', 'incomplete': '记录未结束'} + + +def joint_label(name): + side, joint = name.split('.') + return ('左臂' if side == 'left' else '右臂') + ' · ' + ('夹爪 J8' if joint == 'gripper_motor' else 'J' + joint[5:]) + + +def chart_data(snapshot, name): + if name not in snapshot['names']: + return [], [] + index = snapshot['names'].index(name) + def series(kind): + points = [[p['time'], None if p['values'][index] is None else math.degrees(p['values'][index])] + for p in snapshot['points'] if p['kind'] == kind] + stride = max(1, math.ceil(len(points) / 700)) + result = points[::stride] + if points and result[-1] != points[-1]: + result.append(points[-1]) + return result + return series('target'), series('feedback') + + +def joint_rows(snapshot, cursor): + latest = {} + for point in snapshot['points']: + if point['time'] <= cursor: + latest[point['kind']] = point['values'] + result = [] + for i, name in enumerate(snapshot['names']): + target = latest.get('target', [None]*len(snapshot['names']))[i] + measured = latest.get('feedback', [None]*len(snapshot['names']))[i] + delta = None if target is None or measured is None else target-measured + result.append(dict(name=name, joint=joint_label(name), + **{key: '—' if v is None else f'{math.degrees(v):+.2f}' + for key, v in [('target', target), ('feedback', measured), ('error', delta)]})) + return result + + +class PolicyView: + def __init__(self, preview): + from nicegui import ui + self.ui, self.preview = ui, preview + self.playing = self.updating = False + self.cursor = self.last_tick = 0.0 + self.signature = None + self.was_busy = False + self.render_key = None + ui.colors(primary='#36735a') + ui.add_css(''' + body { background: #f6f8f5; color: #263d32; } + .policy-workspace { width:100%; max-width:1280px; margin:auto; padding:24px; gap:18px; } + .policy-toolbar { width:100%; align-items:center; gap:16px; flex-wrap:wrap; } + .policy-metrics { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); width:100%; gap:12px; } + .policy-metric { padding:16px; background:white; border:1px solid #dfe7df; border-radius:12px; } + .policy-metric-caption { font-size:12px; color:#6f8074; } + .policy-metric-value { font-size:22px; font-weight:600; margin-top:6px; } + .policy-card { width:100%; box-shadow:none!important; border:1px solid #dfe7df; border-radius:12px; } + @media(max-width:650px) { .policy-workspace {padding:14px;} .policy-metrics {grid-template-columns:repeat(2,minmax(0,1fr));} } + ''') + with ui.column().classes('policy-workspace'): + with ui.row().classes('policy-toolbar'): + with ui.column().classes('gap-1 grow'): + ui.label('策略可视化').classes('text-2xl font-semibold') + ui.label('OpenArm 0.7.0 · 仿真与记录回放').classes('text-sm text-grey-7') + self.source = ui.badge('等待策略', color='primary').props('data-testid=policy-source') + with ui.row().classes('policy-metrics'): + self.metrics = {} + for key, label in [('state', '会话状态'), ('duration', '采样时间'), ('commands', '已提交指令'), ('latency', '最近推理延迟')]: + with ui.column().classes('policy-metric gap-0'): + ui.label(label).classes('policy-metric-caption') + self.metrics[key] = ui.label('—').classes('policy-metric-value').props(f'data-testid=policy-{key}') + with ui.card().classes('policy-card'): + with ui.row().classes('policy-toolbar'): + self.policy = ui.select({'sine': 'J1 正弦演示', 'hold': '保持姿态'}, value='sine', label='仿真策略').classes('w-48') + self.duration = ui.number('时长(秒)', value=10, min=1, max=60, step=1).classes('w-28') + self.start_button = ui.button('开始仿真', icon='play_arrow', on_click=self.start).props('data-testid=policy-start') + self.stop_button = ui.button('停止仿真', icon='stop', on_click=preview.stop).props('outline data-testid=policy-stop') + ui.label('仿真使用理想位置模型;指令与反馈分别显示。').classes('text-xs text-grey-7') + with ui.expansion('打开策略记录', icon='folder_open').classes('w-full'): + ui.label(str(preview.record_root)).classes('text-xs text-grey-7 break-all') + with ui.row().classes('policy-toolbar'): + self.episode = ui.select(preview.episodes(), label='会话目录').classes('grow').props('data-testid=policy-episode') + ui.button('刷新列表', icon='refresh', on_click=self.refresh_episodes).props('flat') + self.load_button = ui.button('加载回放', on_click=self.load).props('outline data-testid=policy-load') + ui.label('读取会话中的 events.jsonl;回放显示记录时的反馈。').classes('text-xs text-grey-7') + self.error = ui.label('').classes('text-red-8 whitespace-pre-wrap').props('role=alert data-testid=policy-error') + with ui.card().classes('policy-card'): + with ui.row().classes('policy-toolbar'): + ui.label('目标与反馈轨迹').classes('text-lg font-medium grow') + self.joint = ui.select({}, label='关节', on_change=lambda _: self.render()).classes('w-44').props('data-testid=policy-joint') + self.chart = ui.echart({ + 'animation': False, 'tooltip': {'trigger': 'axis'}, + 'legend': {'data': ['提交目标', '反馈采样']}, + 'grid': {'left': 60, 'right': 28, 'top': 44, 'bottom': 48}, + 'xAxis': {'type': 'value', 'name': '秒'}, 'yAxis': {'type': 'value', 'name': '角度(°)', 'scale': True}, + 'series': [ + {'name': '提交目标', 'type': 'line', 'step': 'end', 'showSymbol': False, 'data': [], 'color': '#b58b48'}, + {'name': '反馈采样', 'type': 'line', 'showSymbol': False, 'connectNulls': False, 'data': [], 'color': '#36735a'}, + ], + }).classes('w-full h-80').props('data-testid=policy-chart') + with ui.row().classes('policy-toolbar'): + self.play_button = ui.button('播放回放', icon='play_arrow', on_click=self.toggle_play).props('flat data-testid=policy-play') + self.slider = ui.slider(min=0, max=1, step=.01, value=0, on_change=self.seek).classes('grow').props('data-testid=policy-time') + self.time_label = ui.label('0.00 s').classes('text-sm') + ui.label('图表保留最近 2,000 个采样事件;拖动时间轴查看对应关节值。').classes('text-xs text-grey-7') + columns = [dict(name=key, label=label, field=key, align='left') for key, label in + [('joint', '关节'), ('target', '提交目标(°)'), ('feedback', '反馈采样(°)'), ('error', '目标 − 反馈(°)')]] + self.table = ui.table(columns=columns, rows=[], row_key='name').classes('policy-card').props('flat dense data-testid=policy-joints') + self.render() + ui.timer(.25, self.render) + + async def start(self): + try: + self.preview.start(self.policy.value, self.duration.value) + self.playing = False + self.signature = None + self.render() + except (ValueError, RuntimeError) as exc: + self.ui.notify(str(exc), type='negative') + + def refresh_episodes(self): + try: + self.episode.set_options(self.preview.episodes()) + except OSError as exc: + self.ui.notify(str(exc), type='negative') + + async def load(self): + try: + if not self.episode.value: + raise ValueError('请先选择一个记录会话') + await asyncio.to_thread(self.preview.load, self.episode.value) + self.playing = False + self.signature = None + self.render() + except (OSError, ValueError, RuntimeError, KeyError, TypeError, ImportError) as exc: + self.ui.notify(str(exc), type='negative') + + def seek(self, event): + if not self.updating: + self.cursor = float(event.value) + self.playing = False + self.render() + + def toggle_play(self): + self.playing = not self.playing + if self.playing and self.cursor >= self.slider._props['max']: + self.cursor = self.slider._props['min'] + self.last_tick = time.monotonic() + self.render() + + def render(self): + snapshot = self.preview.snapshot() + points, busy = snapshot['points'], snapshot['busy'] + start = min((p['time'] for p in points), default=0.0) + end = max((p['time'] for p in points), default=0.0) + signature = (snapshot['generation'], snapshot['source'], tuple(snapshot['names'])) + now = time.monotonic() + if signature != self.signature: + self.signature = signature + self.cursor = end + options = {n: joint_label(n) for n in snapshot['names']} + self.joint.set_options(options, value=next(iter(options), None)) + if busy or self.was_busy: + self.cursor, self.playing = end, False + elif self.playing: + self.cursor = min(end, self.cursor + max(0, now-self.last_tick)) + if self.cursor >= end: + self.playing = False + self.was_busy = busy + self.last_tick = now + self.cursor = max(start, min(end, self.cursor)) + key = (signature, snapshot['revision'], busy, self.cursor, self.playing, self.joint.value) + if key == self.render_key: + return + self.render_key = key + self.updating = True + self.slider._props.update(min=start, max=max(start+.01, end)) + self.slider.value = self.cursor + self.slider.update() + self.updating = False + self.slider.set_enabled(bool(points) and not busy) + self.play_button.set_enabled(bool(points) and not busy) + self.play_button.set_text('暂停回放' if self.playing else '播放回放') + self.start_button.set_enabled(not busy) + self.stop_button.set_enabled(busy and not self.preview.loading) + self.load_button.set_enabled(not busy) + self.source.set_text(snapshot['source']) + self.metrics['state'].set_text(STATES.get(snapshot['state'], snapshot['state'])) + self.metrics['duration'].set_text(f'{end:.1f} s') + self.metrics['commands'].set_text(str(snapshot['commands'])) + self.metrics['latency'].set_text('—' if snapshot['latency_ms'] is None else f"{snapshot['latency_ms']:.1f} ms") + self.error.set_text(snapshot['error']) + self.time_label.set_text(f'{self.cursor:.2f} s') + target, feedback = chart_data(snapshot, self.joint.value) + for series, data in zip(self.chart.options['series'], (target, feedback)): + series['data'] = data + self.chart.options['series'][0]['markLine'] = {'silent': True, 'symbol': 'none', + 'label': {'show': False}, 'data': [{'xAxis': self.cursor}]} + self.chart.update() + self.table.rows = joint_rows(snapshot, self.cursor) + self.table.update() + + +def build_policy_view(preview): + return PolicyView(preview) diff --git a/src/openarm_platform/proxy.py b/src/openarm_platform/proxy.py index 945293e..3533b08 100644 --- a/src/openarm_platform/proxy.py +++ b/src/openarm_platform/proxy.py @@ -17,6 +17,8 @@ def routes(config): result = {} for page in config.pages: + if page.path is not None: + continue prefix = f'/apps/{page.id}' result[prefix] = page.port for index, port in enumerate(page.extra_ports): diff --git a/tests/test_platform.py b/tests/test_platform.py index e706358..c104e0b 100644 --- a/tests/test_platform.py +++ b/tests/test_platform.py @@ -81,6 +81,18 @@ def client(self, manager, *, attach_only=False): return TestClient(create_app(load_config(), manager, attach_only=attach_only, with_ui=False), base_url='http://127.0.0.1:8888') + def test_policy_page_is_available_in_attach_only_without_activating_hardware(self): + manager = Mock() + manager.status.return_value = {} + with self.client(manager, attach_only=True) as client: + response = client.post('/api/select', json={'id': 'policy'}, + headers={'Origin': 'http://127.0.0.1:8888'}) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.json()['services']['policy']['reachable']) + manager.start.assert_not_called() + manager.activate.assert_not_called() + self.assertIsNone(client.app.state.policy_preview.worker) + def test_http_status_selection_and_origin_boundary(self): manager = Mock() manager.status.return_value = {'control': {'state': 'external', 'reachable': True}} @@ -89,10 +101,10 @@ def test_http_status_selection_and_origin_boundary(self): manager.start.assert_called_once() response = client.get('/api/config') self.assertEqual(response.status_code, 200) - self.assertEqual(len(response.json()['pages']), 4) + self.assertEqual(len(response.json()['pages']), 5) self.assertNotIn('command', response.text) self.assertNotIn('cwd', response.text) - self.assertEqual(client.get('/api/status').json()['services'], manager.status.return_value) + self.assertEqual(client.get('/api/status').json()['services'], client.app.state.coordinator.with_builtin(manager.status.return_value)) self.assertEqual(client.get('/api/status').headers['x-frame-options'], 'SAMEORIGIN') self.assertEqual(client.get('/api/status', headers={'Host': 'evil.invalid'}).status_code, 403) self.assertEqual(client.get('/_nicegui_ws/socket.io/?EIO=4&transport=polling', diff --git a/tests/test_platform_dashboard.py b/tests/test_platform_dashboard.py index 21211b4..e6e8187 100644 --- a/tests/test_platform_dashboard.py +++ b/tests/test_platform_dashboard.py @@ -15,7 +15,8 @@ def running(): return {name: dict(state='standby' if name == 'teleop' else 'running', reachable=name != 'teleop', managed=name != 'teleop', generation=1) - for name in ('control', 'teleop', 'tactile', 'vision')} + for name in ('control', 'teleop', 'tactile', 'vision')} | { + 'policy': dict(state='running', reachable=True, managed=False, generation=0)} @unittest.skipUnless(HAS_PLATFORM, 'NiceGUI platform extra required') @@ -56,6 +57,17 @@ async def test_sensing_navigation_preserves_controller_element_and_origin(self): self.assertIn('active', d.nav['control'].classes) self.assertNotIn('active', d.nav['vision'].classes) + async def test_policy_uses_same_origin_and_preserves_control_frame(self): + d = self.dashboard + with self.client: + await d.select('control') + controller = d.frames['control'].element + await d.select('policy') + self.assertIs(d.frames['control'].element, controller) + self.assertEqual(d.frames['policy'].element.props['src'], '/policy') + self.assertEqual(d.external.props['href'], '/policy') + self.assertFalse(d.confirm_dialog.value) + async def test_cancel_and_failed_switch_preserve_current_controller(self): d = self.dashboard with self.client: diff --git a/tests/test_policy_preview.py b/tests/test_policy_preview.py new file mode 100644 index 0000000..7509434 --- /dev/null +++ b/tests/test_policy_preview.py @@ -0,0 +1,185 @@ +"""Real simulated sessions and record/UI boundaries; never access physical devices.""" +from dataclasses import asdict +import importlib.util +import json +import math +from pathlib import Path +import tempfile +import time +import unittest +from unittest.mock import Mock, patch + +from openarm_platform.config import load_config +from openarm_platform.policy import PolicyPreview, PolicyTrace +from openarm_platform.policy_view import chart_data, joint_rows +from openarm_platform.proxy import routes +from openarm_policy.contracts import Context +from openarm_policy.robots import joint_spec, state_specs + + +def context(): + return asdict(Context(joint_spec(('right',)), state_specs(('right',)), 20)) + + +def events(): + return [dict(event='context', time=100., context=context()), + dict(event='observation', time=101., observation=dict(captured_at=101., streams={ + 'robot/right': [dict(data=[[.1, 0, 0]]*8, received_at=101., sequence=1)]})), + dict(event='command', time=101.1, values=[.2]*8), + dict(event='chunk', time=101.1, latency_s=.025), + dict(event='ended', time=102., state='stopped', error='', cleanup_errors=[])] + + +class PreviewTests(unittest.TestCase): + def test_internal_page_is_not_a_hardware_service_or_proxy(self): + config = load_config() + page = next(p for p in config.pages if p.id == 'policy') + self.assertEqual(page.path, '/policy') + self.assertIsNone(page.port) + self.assertNotIn(page, config.services) + self.assertNotIn('/apps/policy', routes(config)) + + def test_recorded_feedback_never_substitutes_submitted_target(self): + trace = PolicyTrace() + for event in events(): + trace.record(event) + snapshot = trace.snapshot() + target, feedback = chart_data(snapshot, 'right.joint1') + self.assertEqual(len(target), 1) + self.assertAlmostEqual(target[0][0], 1.1) + self.assertAlmostEqual(target[0][1], math.degrees(.2)) + self.assertEqual(feedback, [[1., math.degrees(.1)]]) + self.assertEqual(snapshot['latency_ms'], 25) + self.assertEqual(joint_rows(snapshot, 1.)[0]['target'], '—') + row = joint_rows(snapshot, 2.)[0] + self.assertEqual(row['feedback'], '+5.73') + self.assertEqual(row['target'], '+11.46') + self.assertEqual(row['error'], '+5.73') + + def test_nonposition_actions_are_not_mislabelled_as_joint_angles(self): + event = events()[0] + event['context']['action']['kind'] = 'joint_torque_nm' + with self.assertRaises(ValueError): + PolicyTrace().record(event) + + def test_replay_does_not_open_devices_or_inference(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + episode = root/'trial' + episode.mkdir() + (episode/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events())) + preview = PolicyPreview(root) + with patch('openarm_policy.robots.ClassicRobot', side_effect=AssertionError('physical')), \ + patch('openarm_policy.inference.InferenceWorker', side_effect=AssertionError('inference')): + preview.load('trial') + self.assertEqual(preview.episodes(), ['trial']) + self.assertEqual(preview.snapshot()['commands'], 1) + self.assertEqual(preview.snapshot()['state'], 'stopped') + self.assertIsNone(preview.worker) + preview.close() + + def test_malformed_and_escaped_records_keep_previous_view(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + preview = PolicyPreview(root) + (root/'bad').mkdir() + (root/'bad/events.jsonl').write_text('{bad json') + for name in ('../outside', '/tmp', 'bad'): + with self.subTest(name=name), self.assertRaises(ValueError): + preview.load(name) + self.assertFalse(preview.loading) + self.assertEqual(preview.snapshot()['source'], '等待策略') + (root/'alias').symlink_to('/tmp', target_is_directory=True) + self.assertNotIn('alias', preview.episodes()) + + def test_array_reference_cannot_escape_episode(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root/'trial').mkdir() + data = events() + data[1]['observation']['streams']['robot/right'][0]['data'] = {'array': '../outside.npy'} + (root/'trial/events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in data)) + with self.assertRaisesRegex(ValueError, '数组路径'): + PolicyPreview(root).load('trial') + + def test_incomplete_episode_is_labelled_and_samples_are_bounded(self): + trace = PolicyTrace() + trace.record(events()[0]) + for i in range(2100): + trace.record(dict(event='command', time=100+i/20, values=[0]*8)) + self.assertEqual(len(trace.snapshot()['points']), 2000) + self.assertEqual(trace.snapshot()['commands'], 2100) + with tempfile.TemporaryDirectory() as directory: + p = Path(directory)/'partial' + p.mkdir() + (p/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events()[:-1])) + preview = PolicyPreview(directory) + preview.load('partial') + self.assertEqual(preview.snapshot()['state'], 'incomplete') + + def test_real_simulation_emits_chunks_and_stops_without_physical_backend(self): + with tempfile.TemporaryDirectory() as directory: + preview = PolicyPreview(directory) + try: + with patch('openarm_policy.robots.ClassicRobot', side_effect=AssertionError('physical')): + preview.start('sine', 1) + with self.assertRaises(RuntimeError): + preview.start('hold', 1) + preview.worker.join(timeout=8) + snapshot = preview.snapshot() + self.assertFalse(snapshot['busy']) + self.assertEqual(snapshot['state'], 'stopped', snapshot['error']) + self.assertGreater(snapshot['chunks'], 0) + self.assertGreater(snapshot['commands'], 0) + self.assertTrue(chart_data(snapshot, 'left.joint1')[0]) + finally: + preview.close() + + def test_shutdown_cancels_a_running_simulation(self): + with tempfile.TemporaryDirectory() as directory: + preview = PolicyPreview(directory) + preview.start('hold', 60) + preview.close() + self.assertFalse(preview.worker.is_alive()) + self.assertTrue(preview.session.cancel.is_set()) + with self.assertRaises(RuntimeError): + preview.start() + + def test_manual_gravity_combines_with_existing_rated_effort_guard(self): + from test_arm import FakeBus + from openarm_runtime.arm import ArmHold + from openarm_runtime.telemetry import IDS + gravity = Mock() + gravity.metadata.return_value = {} + gravity.last = {} + gravity.update.return_value = dict.fromkeys(IDS, 0.) | {5: 3.1} + bus = FakeBus() + with patch('openarm_runtime.arm.time.sleep'), self.assertRaisesRegex(RuntimeError, 'predicted torque'): + with ArmHold(bus, lambda: False, Mock(), Mock(), manual_side='right', gravity=gravity): + pass + self.assertFalse(bus.enabled) + gravity.preflight.assert_called_once() + + +@unittest.skipUnless(importlib.util.find_spec('nicegui'), 'Requires platform extra') +class PreviewGuiTests(unittest.TestCase): + def test_view_loads_empty_and_renders_trace_with_separate_target_feedback(self): + from nicegui import Client, ui + from openarm_platform.policy_view import PolicyView + with tempfile.TemporaryDirectory() as directory: + preview = PolicyPreview(directory) + client = Client(ui.page('/policy-test')) + try: + with client: + view = PolicyView(preview) + for event in events(): + preview.trace.record(event) + view.render() + self.assertEqual(view.joint.value, 'right.joint1') + self.assertEqual(len(view.table.rows), 8) + self.assertNotEqual(view.chart.options['series'][0]['data'], view.chart.options['series'][1]['data']) + self.assertTrue(view.start_button.enabled) + self.assertFalse(view.stop_button.enabled) + finally: + client.delete() + preview.close() From 21272dc5b6b6630ec260812953521efcb4ca9ab7 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 1 Nov 2026 17:41:05 +0800 Subject: [PATCH 4/6] Normalize temporary paths in collection configuration test --- tests/test_platform.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_platform.py b/tests/test_platform.py index 2e61fd3..89160fa 100644 --- a/tests/test_platform.py +++ b/tests/test_platform.py @@ -39,7 +39,8 @@ def test_configuration_keeps_commands_private_and_expands_paths(self): def test_collection_root_follows_teleop_profile_or_explicit_override(self): with tempfile.TemporaryDirectory() as directory: - root = Path(directory) + # macOS temporary directories can be reached through /var symlinks. + root = Path(directory).resolve() (root/'collection.json').write_text(json.dumps({'root': 'episodes'})) data = {'services': {'teleop': {'command': ['python', 'leader', '--collection-profile', 'collection.json']}}} config = self.profile(directory, data) From 11a70ecd01a32fdf1d01d0ae8c35500a7e3255e8 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 1 Nov 2026 17:43:32 +0800 Subject: [PATCH 5/6] Give policy shape fixtures matching action horizons --- tests/test_policy.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_policy.py b/tests/test_policy.py index 40a152b..b3188b7 100644 --- a/tests/test_policy.py +++ b/tests/test_policy.py @@ -33,7 +33,9 @@ def infer(self, observation): class SinglePolicy(HoldPolicy): def infer(self, observation): chunk = super().infer(observation) - return replace(chunk, steps=chunk.steps[:1], period_s=0.2) + # Match HoldPolicy's one-second horizon when comparing action shapes. + # Expiry itself is covered with explicit timestamps in the contract tests. + return replace(chunk, steps=chunk.steps[:1], period_s=1.0) class SlowResetPolicy(HoldPolicy): From 63dcaccec0257614450e88b1dd10cfd3a48a776e Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 1 Nov 2026 17:45:48 +0800 Subject: [PATCH 6/6] Use deterministic clock for future action activation test --- tests/test_policy.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/tests/test_policy.py b/tests/test_policy.py index b3188b7..b5317ae 100644 --- a/tests/test_policy.py +++ b/tests/test_policy.py @@ -226,8 +226,17 @@ def result(self): def close(self): pass robot = SimulatedRobot(("left",)) robot.spec = ActionSpec(robot.spec.names, (-1,) * 8, (1,) * 8) - with patch("openarm_policy.session.InferenceWorker", Worker): - PolicySession(robot, HoldPolicy(), config=SessionConfig(inference_hz=2)).run(.95) + session = PolicySession(robot, HoldPolicy(), config=SessionConfig(inference_hz=2)) + # This tests activation timestamps, not host scheduler throughput. The + # worker is synchronous here, so advance a shared monotonic clock at wait. + clock = [100.0] + def advance(seconds): + clock[0] += seconds + return False + with patch("openarm_policy.session.InferenceWorker", Worker), \ + patch("time.monotonic", side_effect=lambda: clock[0]), \ + patch.object(session.cancel, "wait", side_effect=advance): + session.run(.95) qs = [v[0] for _, v in robot.commands] self.assertIn(.05, qs) self.assertIn(.1, qs)