diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 534ddfe..8db42b2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,6 +46,7 @@ jobs: cd "$RUNNER_TEMP" "$RUNNER_TEMP/runtime-test/bin/python" -I -m unittest discover -s "$GITHUB_WORKSPACE/tests" -p 'test_platform*.py' "$RUNNER_TEMP/runtime-test/bin/python" -I -m unittest discover -s "$GITHUB_WORKSPACE/tests" -p 'test_gravity.py' + "$RUNNER_TEMP/runtime-test/bin/python" -I -m unittest discover -s "$GITHUB_WORKSPACE/tests" -p 'test_policy*.py' - name: Test optional video from installed wheel env: OPENARM_EXPECT_INSTALLED: '1' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 07a410a..eea0960 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -37,7 +37,7 @@ jobs: "$RUNNER_TEMP/runtime-test/bin/python" -m pip install dist/*.whl cd "$RUNNER_TEMP" "$RUNNER_TEMP/runtime-test/bin/python" -I -m unittest discover -s "$GITHUB_WORKSPACE/tests" - - name: Verify optional platform and gravity from release wheel + - name: Verify optional platform, gravity and collection previews from release wheel env: OPENARM_EXPECT_INSTALLED: '1' run: | @@ -45,11 +45,13 @@ jobs: from pathlib import Path import subprocess, sys wheel = next(Path('dist').glob('*.whl')).resolve() - subprocess.run([sys.executable, '-m', 'pip', 'install', str(wheel) + '[platform,gravity]'], check=True) + subprocess.run([sys.executable, '-m', 'pip', 'install', str(wheel) + '[platform,gravity,video]'], check=True) PY cd "$RUNNER_TEMP" "$RUNNER_TEMP/runtime-test/bin/python" -I -m unittest discover -s "$GITHUB_WORKSPACE/tests" -p 'test_platform*.py' "$RUNNER_TEMP/runtime-test/bin/python" -I -m unittest discover -s "$GITHUB_WORKSPACE/tests" -p 'test_gravity.py' + "$RUNNER_TEMP/runtime-test/bin/python" -I -m unittest discover -s "$GITHUB_WORKSPACE/tests" -p 'test_policy*.py' + "$RUNNER_TEMP/runtime-test/bin/python" -I -m unittest discover -s "$GITHUB_WORKSPACE/tests" -p 'test_collection*.py' - name: Publish artifacts env: GH_TOKEN: ${{ github.token }} diff --git a/CHANGELOG.md b/CHANGELOG.md index bd7ef84..8cee30e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## 0.8.1 — 2026-11-01 + +- Add same-origin collection visualization at `/#collection`: fresh/stale + recording status, stream activity and writer queues, plus read-only episode + inspection, causal camera/tactile/joint playback and acceptance/quality labels. + A best-effort status publisher stays separate from native acquisition; recording + controls reuse the existing teleoperation owner. +- Integrate policy visualization into the platform at `/#policy`: built-in + simulated sessions, submitted-target/feedback curves, inference latency and + bounded episode replay, available through the same port in attach-only mode. +- Preserve calibrated absolute J1–J7 manual controls, trajectory/effort checks, + queued motor reports and the calibration trajectory without encoder-zero writes. + Integrate these with v0.8.0's official gains and acquisition observer while + keeping pre-command observations and post-command feedback separate. +- Retain v0.8.0 demonstration collection, synchronized return-to-zero workflow, + native recording and export; preserve read-only CAN reconnection recovery. +- Validate merged behavior with offline fake-device tests, installed-wheel tests + and browser simulation/replay. This release adds no new physical-motion trial. + ## 0.8.0 — 2026-11-01 - Add opt-in teleoperation demonstration collection: native acquisition sinks, diff --git a/README.md b/README.md index 6091bc4..55ed9fb 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,18 @@ Python 3.12 · MIT · Linux SocketCAN for followers · Independent community pro ## Policy execution and gravity compensation +The platform also provides **数采可视化** at `/#collection`: recording state, +stream updates and writer queues, then camera/tactile/joint playback from native +collection archives. Recording controls remain in the existing teleoperation +page. See [collection visualization](docs/platform.md#collection-visualization). + +The platform includes **策略可视化** 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 version 1 policy contracts; it does not launch the Classic motor backend. +See [platform policy visualization](docs/platform.md#policy-visualization). + Operator-driven [teleoperation data collection](docs/collection.md) adds explicit episode recording/review, native-time robot/camera/tactile archives, quality checks and offline aligned/LeRobot export. Enable it with `leader --follow @@ -43,10 +55,10 @@ python3.12 -m venv .venv source .venv/bin/activate # Core: state types, software mapping and control API; no GUI or hardware SDK. -pip install "openarm-runtime @ git+https://github.com/TCXM/openarm-runtime.git@v0.7.0" +pip install "openarm-runtime @ git+https://github.com/Edge-Intelligence-Lab/openarm-runtime.git@v0.8.1" # Serial leader readout, with a browser-based virtual robot. -pip install "openarm-runtime[leader,viewer] @ git+https://github.com/TCXM/openarm-runtime.git@v0.7.0" +pip install "openarm-runtime[leader,viewer] @ git+https://github.com/Edge-Intelligence-Lab/openarm-runtime.git@v0.8.1" ``` Extras compose freely: @@ -70,7 +82,7 @@ project's environment. With uv, declare and lock the dependency directly: ```sh # Run in your own Python 3.12 project. -uv add "openarm-runtime[leader,viewer] @ git+https://github.com/TCXM/openarm-runtime.git@v0.7.0" +uv add "openarm-runtime[leader,viewer] @ git+https://github.com/Edge-Intelligence-Lab/openarm-runtime.git@v0.8.1" ``` **Modify the runtime while developing your application:** clone the source @@ -115,7 +127,7 @@ configure the machine once using [platform.example.json](platform.example.json), then launch: ```sh -python -m pip install "openarm-runtime[platform] @ git+https://github.com/TCXM/openarm-runtime.git@v0.7.0" +python -m pip install "openarm-runtime[platform] @ git+https://github.com/Edge-Intelligence-Lab/openarm-runtime.git@v0.8.1" openarm-runtime platform --profile ~/.config/openarm-runtime/platform.json ``` @@ -270,7 +282,7 @@ ssh -N -L 8890:127.0.0.1:8890 -L 8891:127.0.0.1:8891 your-workstation Video is available starting with v0.3.0: ```sh -python -m pip install "openarm-runtime[video] @ git+https://github.com/TCXM/openarm-runtime.git@v0.7.0" +python -m pip install "openarm-runtime[video] @ git+https://github.com/Edge-Intelligence-Lab/openarm-runtime.git@v0.8.1" # No cameras or vendor SDK required; clearly labelled SIMULATION. openarm-runtime video --simulate --port 5004 ``` @@ -346,12 +358,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 motor-control panel also provides **自动标定(不写零位)**, 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 manual-control panel provides 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 @@ -380,7 +400,7 @@ examples in `examples/`. [Changelog](CHANGELOG.md) · [Provenance](ORIGIN.md) · Paxini IP-M2324-Core (68 points) with the single-channel USB serial converter: ```sh -pip install "openarm-runtime[tactile,viewer] @ git+https://github.com/TCXM/openarm-runtime.git@v0.7.0" +pip install "openarm-runtime[tactile,viewer] @ git+https://github.com/Edge-Intelligence-Lab/openarm-runtime.git@v0.8.1" openarm-runtime tactile --device /dev/serial/by-id/YOUR_CONVERTER --device-id 2 --port 8891 ``` 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/collection.md b/docs/collection.md index fada44b..0c00369 100644 --- a/docs/collection.md +++ b/docs/collection.md @@ -192,3 +192,10 @@ Recording is unavailable during return/hold; end an active recording before requesting another return. Stop/disconnect retains disable cleanup. This joint-space return does not plan around obstacles: clear its path before clicking the button. Real hardware return remains an operator-run acceptance check. + +## Unified platform preview (v0.8.1) + +Use the platform's **数采可视化** module to monitor the collecting process and +replay existing native archives. See [configuration and preview boundaries](platform.md#collection-visualization). +Status snapshots under `.runtime/` are diagnostic state, not dataset episodes; +raw manifests, samples and array payloads retain `openarm.collection/1` format. diff --git a/docs/platform.md b/docs/platform.md index 06ce40f..28e0657 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, collection 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. @@ -14,7 +14,7 @@ The platform is available from v0.6.0. In a Python 3.12 environment, install the optional platform dependencies and configure the machine as described below: ```sh -python -m pip install "openarm-runtime[platform] @ git+https://github.com/TCXM/openarm-runtime.git@v0.6.0" +python -m pip install "openarm-runtime[platform] @ git+https://github.com/Edge-Intelligence-Lab/openarm-runtime.git@v0.8.1" openarm-runtime platform --profile ~/.config/openarm-runtime/platform.json ``` @@ -172,3 +172,67 @@ 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 + +The platform includes 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 `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). + +## Collection visualization + +Open **数采可视化** at `/#collection`, or `/collection` for the standalone page +on the same server. No additional device process or port is created. The page +also works in `--attach-only` mode. “进入遥操录制” selects the existing teleoperation +view through the dashboard; starting/stopping/reviewing an episode stays with +that view's owner and the original control lifecycle. + +Set `collection_root` in the external platform JSON to the raw collection root. +If omitted, the platform reads `root` from the teleop command's +`--collection-profile` file when available, otherwise uses `~/openarm-collection`. +The viewer never starts acquisition to discover a directory. + +Every `Collection` instance publishes a small status snapshot under +`ROOT/.runtime/INSTANCE.json` every 0.5 seconds, in a separate best-effort thread. +It includes state, task/operator, duration, stream sequence/age and pending +writer queue size. Publishers never serialize camera images or perform I/O on +the CAN thread. Preview write failure does not stop raw acquisition; snapshots +older than three seconds are displayed as stale rather than current recording +state. Existing v0.8.0 processes need to restart on v0.8.1 to publish status. + +Select an existing episode to view its task, acceptance and quality issues, then +play or scrub its native timeline. Camera and tactile samples are selected only +from timestamps at or before the cursor. Target dispatch and motor feedback +receipt timestamps remain separate. Camera images are JPEG previews of the +original lossless arrays; depth previews use a fixed 0–4 m colour scale. Tactile +XYZ values remain raw counts. Inspecting or playing a record never writes review +files, changes acceptance, exports training data, or resubmits motor commands. + +Preview reads at most 128 MiB of journal data and retains the latest 2,000 records +per stream. Array previews require the optional `video` extra. The common retained +window is shown on the timeline; array and journal checksum issues remain visible. +Metadata/status inspection needs no camera, tactile SDK or native CAN SDK. diff --git a/pyproject.toml b/pyproject.toml index e75b46a..86d81ef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "openarm-runtime" -version = "0.8.0" +version = "0.8.1" description = "Reusable OpenArm Classic CAN control, Feetech leader readout, tactile/video capture and optional Viser tools" readme = "README.md" license = "MIT" @@ -15,9 +15,9 @@ requires-python = ">=3.12,<3.13" dependencies = [] [project.urls] -Repository = "https://github.com/TCXM/openarm-runtime" -Issues = "https://github.com/TCXM/openarm-runtime/issues" -Changelog = "https://github.com/TCXM/openarm-runtime/blob/main/CHANGELOG.md" +Repository = "https://github.com/Edge-Intelligence-Lab/openarm-runtime" +Issues = "https://github.com/Edge-Intelligence-Lab/openarm-runtime/issues" +Changelog = "https://github.com/Edge-Intelligence-Lab/openarm-runtime/blob/main/CHANGELOG.md" [project.optional-dependencies] gravity = ["pin==4.1.0"] diff --git a/src/openarm_collection/session.py b/src/openarm_collection/session.py index c46ff88..5ff1b2a 100644 --- a/src/openarm_collection/session.py +++ b/src/openarm_collection/session.py @@ -20,11 +20,16 @@ def __init__(self, root, *, capacity=512, max_bytes=256 * 1024**2): self.previews = {} self.tactile_values = {} self.previous_episode = None + self.last_state = None + self.last_metadata = {} + self.last_duration = 0.0 self.ready = False self.message = "待机" self.closed = threading.Event() self.monitor = threading.Thread(target=self._monitor, name="collection-health", daemon=True) self.monitor.start() + from .status import StatusPublisher + self.status_publisher = StatusPublisher(self.root, self.status_snapshot) def register(self, name, **spec): with self.lock: @@ -87,6 +92,9 @@ def _finish(self, reason, error): path = episode.finish(reason) with self.lock: self.last = path + self.last_state = episode.manifest['state'] + self.last_metadata = {key: episode.manifest['metadata'].get(key, '') for key in ('task', 'operator')} + self.last_duration = episode.manifest['ended_at'] - episode.manifest['started_at'] self.episode = None self.message = f"待验收 · {episode.manifest['state']} · {path.name}" if episode.manifest["quality"]["problems"]: @@ -125,7 +133,33 @@ def _monitor(self): except Exception as exc: self.message = str(exc) + def status_snapshot(self): + """Small diagnostic copy; never serialize or touch storage under this lock.""" + with self.lock: + now = time.monotonic() + episode = self.episode + state = ('closed' if self.closed.is_set() else + ('draining' if episode.stop.is_set() else 'recording') if episode else + self.last_state if self.last else 'ready' if self.ready else 'idle') + metadata = episode.manifest['metadata'] if episode else self.last_metadata + return dict(state=state, ready=self.ready, message=self.message, + task=metadata.get('task', ''), operator=metadata.get('operator', ''), + episode_id=episode.path.name if episode else self.last.name if self.last else None, + duration_s=now-episode.manifest['started_at'] if episode else self.last_duration, + queue_items=episode.queue.qsize() if episode else 0, + pending_bytes=episode.bytes if episode else 0, + error=episode.error if episode else '', + streams={name: dict(encoding=spec.get('encoding', ''), + sequence=self.sequence.get(name, 0), + age_s=now-self.latest[name] if name in self.latest else None, + max_age_s=spec.get('max_age_s', .5), required=spec.get('required', True)) + for name, spec in self.streams.items()}, + tactile={name: list(values) for name, values in tuple(self.tactile_values.items())}) + def close(self): self.closed.set() self.monitor.join(timeout=2) - self.finish("shutdown", "Collection closed while recording") + try: + self.finish("shutdown", "Collection closed while recording") + finally: + self.status_publisher.close() diff --git a/src/openarm_collection/status.py b/src/openarm_collection/status.py new file mode 100644 index 0000000..1319344 --- /dev/null +++ b/src/openarm_collection/status.py @@ -0,0 +1,41 @@ +"""Best-effort cross-process preview status, separate from acquisition journals.""" +from pathlib import Path +import os +import threading +import time +import uuid + +from .recording import atomic_json + + +class StatusPublisher: + def __init__(self, root, snapshot): + self.identity = uuid.uuid4().hex + self.path = Path(root) / '.runtime' / f'{self.identity}.json' + self.snapshot = snapshot + self.stop = threading.Event() + self.error = '' + self.thread = threading.Thread(target=self._run, name='collection-status', daemon=True) + self.thread.start() + + def publish(self): + try: + data = self.snapshot() + data.update(schema='openarm.collection-status/1', publisher=self.identity, + pid=os.getpid(), updated_wall_time_ns=time.time_ns()) + self.path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(self.path, data) + self.error = '' + except Exception as exc: + # Preview/storage failure must not stop native acquisition or CAN. + self.error = str(exc) + + def _run(self): + self.publish() + while not self.stop.wait(.5): + self.publish() + self.publish() + + def close(self): + self.stop.set() + self.thread.join(timeout=2) diff --git a/src/openarm_platform/app.py b/src/openarm_platform/app.py index 2c7e22a..ea1e74c 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,17 @@ async def select(request: Request): gateway.install(app) if with_ui: + from .policy_view import build_policy_view + from .collection_view import build_collection_view + + @ui.page('/collection', title='数采可视化 · OpenArm') + async def collection_page(): + build_collection_view(config.collection_root) + + @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/collection.py b/src/openarm_platform/collection.py new file mode 100644 index 0000000..2589d76 --- /dev/null +++ b/src/openarm_platform/collection.py @@ -0,0 +1,227 @@ +"""Read-only native collection status and bounded, causal archive inspection.""" +import base64 +from bisect import bisect_right +from collections import defaultdict, deque +import hashlib +import json +import math +from pathlib import Path +import time + + +STATE_LABELS = {'idle': '待机', 'ready': '可录制', 'recording': '录制中', 'draining': '写入中', + 'review': '待验收', 'incomplete': '数据不完整', 'closed': '已关闭'} + + +def read_json(path): + if not path.is_file() or path.stat().st_size > 1024 * 1024: + raise ValueError('元数据路径无效或超过 1 MiB') + value = json.loads(path.read_text()) + if not isinstance(value, dict): + raise ValueError('元数据必须是 JSON 对象') + return value + + +def inside(root, path): + resolved = path.resolve() + if not resolved.is_relative_to(root): + raise ValueError('记录路径越过采集目录') + return resolved + + +def finite(value): + if isinstance(value, bool) or not isinstance(value, (float, int)) or not math.isfinite(value): + raise ValueError('采样时间或数值无效') + return float(value) + + +def archive_state(manifest, review): + state = '未结束' if manifest['state'] == 'recording' else STATE_LABELS.get(manifest['state'], manifest['state']) + if type(review.get('accepted')) is bool: + decision = '已验收' if review['accepted'] else '已弃用' + state = decision if manifest['state'] == 'review' else f'{state} · {decision}' + return state + + +class CollectionBrowser: + def __init__(self, root): + self.root = Path(root).expanduser().resolve() + + def live(self, now_ns=None): + now_ns = time.time_ns() if now_ns is None else now_ns + directory = inside(self.root, self.root/'.runtime') + result = [] + for path in directory.glob('*.json') if directory.is_dir() else (): + try: + value = read_json(inside(directory, path)) + if value.get('schema') != 'openarm.collection-status/1': + continue + age = (now_ns-finite(value['updated_wall_time_ns'])) / 1e9 + value['fresh'] = 0 <= age <= 3 + value['status_age_s'] = max(0, age) + result.append(value) + except (OSError, ValueError, KeyError, TypeError): + continue + return sorted(result, key=lambda v:(v['fresh'] and v.get('state') != 'closed', v['updated_wall_time_ns']), reverse=True) + + def episodes(self): + result = {} + if not self.root.is_dir(): + return result + for path in self.root.iterdir(): + if path.name.startswith('.') or path.is_symlink() or not path.is_dir() or not (path/'manifest.json').is_file(): + continue + try: + manifest = read_json(inside(self.root, path/'manifest.json')) + if manifest.get('schema') != 'openarm.collection/1': + continue + task = str(manifest.get('metadata', {}).get('task', '未命名任务')) + review = read_json(inside(self.root, path/'review.json')) if (path/'review.json').exists() else {} + state = archive_state(manifest, review) + result[path.name] = f'{task} · {state} · {path.name[:8]}' + except (OSError, ValueError, KeyError, TypeError, AttributeError): + result[path.name] = f'元数据异常 · {path.name[:8]}' + return dict(sorted(result.items(), reverse=True)) + + def load(self, name): + if not isinstance(name, str) or not name or Path(name).name != name: + raise ValueError('请选择一个采集会话') + path = inside(self.root, self.root/name) + if path.parent != self.root: + raise ValueError('请选择采集目录中的会话') + try: + return EpisodeTimeline(path) + except (KeyError, TypeError, AttributeError, IndexError) as exc: + raise ValueError(f'数采记录结构无效:{exc}') from exc + + +class EpisodeTimeline: + def __init__(self, root): + self.root = root.resolve() + self.manifest = read_json(inside(self.root, self.root/'manifest.json')) + if self.manifest.get('schema') != 'openarm.collection/1': + raise ValueError('不支持的数采记录格式') + self.review = read_json(inside(self.root, self.root/'review.json')) if (self.root/'review.json').exists() else {} + if 'accepted' in self.review and type(self.review['accepted']) is not bool: + raise ValueError('验收标记必须是布尔值') + self.origin = finite(self.manifest['started_at']) + self.streams = dict(self.manifest['streams']) + if len(self.streams) > 64: + raise ValueError('最多预览 64 路数据流') + samples = defaultdict(lambda: deque(maxlen=2000)) + self.counts = defaultdict(int) + self.problems = list(self.manifest.get('quality', {}).get('problems', ())) + path = inside(self.root, self.root/'samples.jsonl') + if not path.is_file() or path.stat().st_size > 128 * 1024**2: + raise ValueError('采样记录无效或超过 128 MiB 预览上限') + digest, total, previous = hashlib.sha256(), 0, {} + with path.open('rb') as handle: + while line := handle.readline(2 * 1024**2 + 1): + total += len(line) + if len(line) > 2 * 1024**2 or total > 128 * 1024**2: + raise ValueError('采样记录超过预览上限') + digest.update(line) + try: + sample = json.loads(line) + except ValueError: + if not line.endswith(b'\n') and self.manifest['state'] == 'recording': + self.problems.append('末条采样尚未写完,已显示可读部分') + break + raise ValueError('采样记录损坏') from None + stream = sample['stream'] + timestamp = finite(sample['timestamp']) + if stream not in self.streams or timestamp < previous.get(stream, -math.inf): + raise ValueError('数据流未知或时间戳倒退') + previous[stream] = timestamp + samples[stream].append(sample) + self.counts[stream] += 1 + expected = self.manifest.get('journal_sha256') + if expected and digest.hexdigest() != expected: + self.problems.append('采样记录 SHA256 校验不匹配') + self.samples = {key: list(values) for key, values in samples.items()} + self.times = {key: [s['timestamp']-self.origin for s in values] for key, values in self.samples.items()} + self.start = max((values[0] for values in self.times.values() if values), default=0.) + self.end = max((values[-1] for values in self.times.values() if values), default=0.) + self.start = min(self.start, self.end) + self.joints = {} + for stream, values in self.samples.items(): + if not stream.startswith('robot/'): + continue + for mid in range(1, 9): + target, feedback = [], [] + for sample in values: + data = sample['data'] + goal = data.get('targets_rad', {}).get(str(mid)) + state = data.get('feedback', {}).get(str(mid)) + if goal is not None: + target.append([finite(data.get('dispatch_started_at', sample['timestamp']))-self.origin, math.degrees(finite(goal))]) + if state is not None: + feedback.append([finite(state.get('received_at', data.get('exchange_completed_at', sample['timestamp'])))-self.origin, + math.degrees(finite(state['position']))]) + self.joints[f'{stream}/{mid}'] = (sorted(target), sorted(feedback)) + self.end = max([self.end] + [v[-1][0] for v in (target, feedback) if v]) + + def at(self, stream, elapsed): + times = self.times.get(stream, ()) + index = bisect_right(times, elapsed) - 1 + return self.samples[stream][index] if index >= 0 else None + + def array(self, record): + import numpy as np + data = record['data'] + path = inside(self.root, self.root/data['array']) + if path.suffix != '.npy' or not path.is_file() or path.stat().st_size > 64 * 1024**2: + raise ValueError('采样数组路径或大小无效') + if data.get('sha256') and hashlib.sha256(path.read_bytes()).hexdigest() != data['sha256']: + raise ValueError('采样数组 SHA256 校验不匹配') + values = np.load(path, mmap_mode='r', allow_pickle=False) + if 'shape' in data and tuple(data['shape']) != values.shape or 'dtype' in data and str(values.dtype) != data['dtype']: + raise ValueError('采样数组与记录元数据不符') + return values + + def camera(self, stream, elapsed): + record = self.at(stream, elapsed) + if record is None: + return None + import cv2 + import numpy as np + frame = self.array(record) + encoding = self.streams[stream].get('encoding') + if encoding == 'bgr8' and frame.dtype == np.uint8 and frame.ndim == 3 and frame.shape[2] == 3: + image = frame + elif encoding == 'depth_mm' and frame.dtype == np.uint16 and frame.ndim == 2: + image = cv2.applyColorMap(np.clip(frame.astype(float)/4000*255, 0, 255).astype(np.uint8), cv2.COLORMAP_VIRIDIS) + else: + raise ValueError('不支持的相机图像格式') + height, width = image.shape[:2] + if not height or not width: + raise ValueError('图像尺寸无效') + image = cv2.resize(image, (min(640, width), max(1, round(height*min(640,width)/width)))) + ok, encoded = cv2.imencode('.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, 80]) + if not ok: + raise ValueError('预览图编码失败') + return dict(source='data:image/jpeg;base64,'+base64.b64encode(encoded).decode(), + age_s=elapsed-(record['timestamp']-self.origin), sequence=record['sequence'], + encoding=encoding) + + def tactile(self, stream, elapsed): + record = self.at(stream, elapsed) + if record is None: + return None + values = self.array(record).tolist() if isinstance(record['data'], dict) else record['data'] + if len(values) != 69 or any(len(row) != 3 for row in values): + raise ValueError('触觉采样必须是 69 × 3 XYZ 原始值') + rows = [[finite(v) for v in row] for row in values] + return dict(resultant=rows[0], taxels=rows[1:], age_s=elapsed-(record['timestamp']-self.origin)) + + def joint_rows(self, elapsed): + rows = [] + for name, (targets, feedback) in self.joints.items(): + def latest(series): + index = bisect_right([p[0] for p in series], elapsed)-1 + return series[index][1] if index >= 0 else None + target, measured = latest(targets), latest(feedback) + rows.append(dict(joint=name.replace('robot/', '').replace('/', ' · J'), + target='—' if target is None else f'{target:+.2f}', + feedback='—' if measured is None else f'{measured:+.2f}')) + return rows diff --git a/src/openarm_platform/collection_view.py b/src/openarm_platform/collection_view.py new file mode 100644 index 0000000..dd9f3ed --- /dev/null +++ b/src/openarm_platform/collection_view.py @@ -0,0 +1,253 @@ +"""Same-origin collection monitoring and archive playback, without device owners.""" +import asyncio +import time + +from openarm_runtime import __version__ +from .collection import CollectionBrowser, STATE_LABELS, archive_state + + +class CollectionView: + def __init__(self, root): + from nicegui import ui + self.ui, self.browser = ui, CollectionBrowser(root) + self.timeline = None + self.render_key = None + self.cursor = 0. + self.last_tick = time.monotonic() + self.playing = self.updating = self.rendering = self.polling = self.loading = False + self.images, self.tactiles, self.sequences = {}, {}, {} + ui.colors(primary='#36735a') + ui.add_css(''' + body {background:#f6f8f5;color:#263d32} + .collection-workspace {max-width:1300px;width:100%;margin:auto;padding:24px;gap:18px} + .collection-card {width:100%;border:1px solid #dfe7df;box-shadow:none!important;border-radius:12px} + .collection-toolbar {width:100%;align-items:center;gap:14px;flex-wrap:wrap} + .collection-metrics {width:100%;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px} + .collection-metric {background:white;border:1px solid #dfe7df;border-radius:12px;padding:14px} + .collection-media {display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));width:100%;gap:12px} + @media(max-width:650px) {.collection-workspace{padding:14px}.collection-metrics{grid-template-columns:repeat(2,minmax(0,1fr))}} + ''') + with ui.column().classes('collection-workspace'): + with ui.row().classes('collection-toolbar'): + with ui.column().classes('grow gap-1'): + ui.label('数采可视化').classes('text-2xl font-semibold') + ui.label(f'OpenArm {__version__} · 录制状态与多模态回放').classes('text-sm text-grey-7') + ui.button('进入遥操录制', icon='precision_manufacturing', on_click=self.open_capture).props('outline data-testid=collection-capture') + ui.label(str(self.browser.root)).classes('text-xs text-grey-7 break-all') + with ui.row().classes('collection-metrics'): + self.metrics = {} + for key,label in [('state','录制状态'),('duration','本段时长'),('queue','待写队列'),('episodes','已有会话')]: + with ui.column().classes('collection-metric gap-1'): + ui.label(label).classes('text-xs text-grey-7') + self.metrics[key] = ui.label('—').classes('text-xl font-semibold').props(f'data-testid=collection-{key}') + with ui.card().classes('collection-card'): + self.publisher = ui.select({}, label='采集实例', on_change=self.refresh_live).classes('w-full') + self.live_message = ui.label('正在读取录制状态…').classes('text-sm').props('data-testid=collection-live-message') + columns=[dict(name=k,label=l,field=k,align='left') for k,l in + [('stream','数据流'),('state','更新状态'),('age','采样距现在'),('sequence','源序号')]] + self.live_table = ui.table(columns=columns,rows=[],row_key='stream').classes('w-full').props('flat dense') + ui.label('状态来自采集进程,每 0.5 秒更新;开始、结束和验收录制沿用遥操中的控制。').classes('text-xs text-grey-7') + with ui.card().classes('collection-card'): + ui.label('已有记录').classes('text-lg font-medium') + with ui.row().classes('collection-toolbar'): + self.episode = ui.select({}, label='采集会话').classes('grow').props('data-testid=collection-episode') + ui.button('刷新列表',icon='refresh',on_click=self.refresh_episodes).props('flat data-testid=collection-refresh') + self.load_button = ui.button('加载回放',on_click=self.load).props('data-testid=collection-load') + self.summary = ui.label('选择会话查看相机、触觉和关节记录。').classes('text-sm').props('data-testid=collection-summary') + self.problems = ui.label('').classes('text-orange-9 whitespace-pre-wrap').props('data-testid=collection-quality') + with ui.row().classes('collection-toolbar'): + self.play_button = ui.button('播放回放',icon='play_arrow',on_click=self.toggle_play).props('flat data-testid=collection-play') + self.slider = ui.slider(min=0,max=1,step=.01,value=0,on_change=self.seek).classes('grow').props('data-testid=collection-time') + self.time_label = ui.label('0.00 s') + ui.label('使用光标之前最近的采样。回放窗口保留每路最新 2,000 条记录;图像为历史预览。').classes('text-xs text-grey-7') + self.error = ui.label('').classes('text-red-8 whitespace-pre-wrap').props('role=alert data-testid=collection-error') + self.media = ui.row().classes('collection-media').props('data-testid=collection-media') + self.touch = ui.row().classes('collection-media') + with ui.card().classes('collection-card'): + with ui.row().classes('collection-toolbar'): + ui.label('关节目标与反馈').classes('text-lg font-medium grow') + self.joint = ui.select({},label='关节',on_change=self.render).classes('w-44') + self.chart = ui.echart({'animation':False,'tooltip':{'trigger':'axis'}, + 'legend':{'data':['提交目标','反馈采样']}, + '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,'data':[],'color':'#36735a'}] + }).classes('w-full h-72').props('data-testid=collection-chart') + columns=[dict(name=k,label=l,field=k,align='left') for k,l in + [('joint','关节'),('target','提交目标(°)'),('feedback','反馈采样(°)')]] + self.joint_table = ui.table(columns=columns,rows=[],row_key='joint').classes('w-full').props('flat dense data-testid=collection-joints') + self.play_button.disable() + self.slider.disable() + ui.timer(.1,self.refresh_episodes,once=True) + ui.timer(.5,self.refresh_live) + ui.timer(.25,self.render) + + async def open_capture(self): + await self.ui.run_javascript('''(() => { + const button = window.parent.document.getElementById('nav-teleop'); + if (button) button.click(); else window.location.assign('/#teleop'); + })()''') + + async def refresh_live(self, _=None): + if self.polling: + return + self.polling = True + try: + values = await asyncio.to_thread(self.browser.live) + options = {v['publisher']:f"{v.get('task') or '采集实例'} · {v['publisher'][:8]}" for v in values} + selected = self.publisher.value if self.publisher.value in options else next(iter(options),None) + if options != self.publisher.options: + self.publisher.set_options(options,value=selected) + value = next((v for v in values if v['publisher']==selected),None) + if value is None: + self.metrics['state'].set_text('未连接') + self.live_message.set_text('未发现采集进程状态。采集目录需要与遥操的 collection profile 中 root 一致。') + self.live_table.rows=[] + self.live_table.update() + return + fresh = value['fresh'] + state = STATE_LABELS.get(value['state'],value['state']) if fresh or value['state']=='closed' else '状态过期' + self.metrics['state'].set_text(state) + self.metrics['duration'].set_text(f"{value.get('duration_s',0):.1f} s") + self.metrics['queue'].set_text(f"{value.get('queue_items',0)} 条") + self.live_message.set_text(f"{value.get('task','')} · {value.get('operator','')} · {value.get('message','')}" + + ('' if fresh else ' · 上次发布的状态,未确认当前是否仍在录制')) + rows=[] + for name,spec in value.get('streams',{}).items(): + age=spec.get('age_s') + age=None if age is None else age+value['status_age_s'] + rows.append(dict(stream=name,state='更新中' if fresh and age is not None and 0<=age<=spec.get('max_age_s',.5) else '未更新', + age='—' if age is None else f'{age*1000:.0f} ms',sequence=spec.get('sequence',0))) + self.live_table.rows=rows + self.live_table.update() + except (OSError,ValueError,KeyError,TypeError) as exc: + self.live_message.set_text(f'状态读取失败:{exc}') + finally: + self.polling=False + + async def refresh_episodes(self): + try: + options=await asyncio.to_thread(self.browser.episodes) + self.episode.set_options(options,value=self.episode.value if self.episode.value in options else next(iter(options),None)) + self.metrics['episodes'].set_text(str(len(options))) + except (OSError,ValueError) as exc: + self.error.set_text(str(exc)) + + async def load(self): + if self.loading: + return + self.loading=True + self.load_button.disable() + try: + timeline=await asyncio.to_thread(self.browser.load,self.episode.value) + self.timeline=timeline + self.cursor=timeline.start + self.playing=False + self.sequences={} + self.error.set_text('') + manifest=timeline.manifest + metadata=manifest.get('metadata',{}) + state=archive_state(manifest,timeline.review) + self.summary.set_text(f"{metadata.get('task','未命名任务')} · {metadata.get('operator','')} · {state} · {sum(timeline.counts.values())} 条采样") + self.problems.set_text('\n'.join(timeline.problems)) + self.images,self.tactiles={},{} + self.media.clear() + self.touch.clear() + with self.media: + for stream in timeline.streams: + if stream.startswith('camera/'): + with self.ui.card().classes('collection-card'): + self.ui.label(stream).classes('font-medium') + image=self.ui.image().classes('w-full h-48').props('fit=contain') + status=self.ui.label('该时间无采样').classes('text-xs text-grey-7') + self.images[stream]=(image,status) + with self.touch: + for stream in timeline.streams: + if stream.startswith('tactile/'): + with self.ui.card().classes('collection-card'): + self.ui.label(stream).classes('font-medium') + label=self.ui.label('该时间无采样').classes('text-sm') + chart=self.ui.echart({'animation':False,'tooltip':{'trigger':'axis'}, + 'legend':{'data':['X','Y','Z']},'xAxis':{'type':'category','name':'触点','data':list(range(68))}, + 'yAxis':{'type':'value','name':'原始计数'}, + 'series':[{'name':axis,'type':'line','showSymbol':False,'data':[]} for axis in ('X','Y','Z')] + }).classes('w-full h-52').props('data-testid=collection-tactile') + self.tactiles[stream]=(label,chart) + self.joint.set_options({key:key.replace('robot/','').replace('/',' · J') for key in timeline.joints},value=next(iter(timeline.joints),None)) + self.slider._props.update(min=timeline.start,max=max(timeline.start+.01,timeline.end)) + self.play_button.enable() + self.slider.enable() + await self.render() + except (OSError,ValueError,KeyError,TypeError,ImportError) as exc: + self.error.set_text(f'记录加载失败:{exc}') + finally: + self.loading=False + self.load_button.enable() + + def seek(self,event): + if not self.updating: + self.cursor=float(event.value) + self.playing=False + + def toggle_play(self): + if self.timeline is not None: + self.playing=not self.playing + if self.playing and self.cursor>=self.timeline.end: + self.cursor=self.timeline.start + self.last_tick=time.monotonic() + + async def render(self,_=None): + if self.rendering or self.timeline is None: + return + self.rendering=True + timeline=self.timeline + try: + now=time.monotonic() + if self.playing: + self.cursor=min(timeline.end,self.cursor+max(0,now-self.last_tick)) + if self.cursor>=timeline.end: + self.playing=False + self.last_tick=now + key=(id(timeline),self.cursor,self.joint.value,self.playing) + if key==self.render_key: + return + self.render_key=key + self.updating=True + self.slider.value=self.cursor + self.updating=False + self.time_label.set_text(f'{self.cursor:.2f} s') + self.play_button.set_text('暂停回放' if self.playing else '播放回放') + for stream,(image,label) in self.images.items(): + sample=timeline.at(stream,self.cursor) + sequence=sample['sequence'] if sample else None + if self.sequences.get(stream,-1)!=sequence: + frame=await asyncio.to_thread(timeline.camera,stream,self.cursor) + if timeline is not self.timeline: + return + image.set_source(frame['source'] if frame else '') + self.sequences[stream]=sequence + label.set_text('该时间无采样' if sample is None else f"帧 {sequence} · 采样距光标 {(self.cursor-sample['timestamp']+timeline.origin)*1000:.0f} ms") + for stream,(label,chart) in self.tactiles.items(): + sample=await asyncio.to_thread(timeline.tactile,stream,self.cursor) + if timeline is not self.timeline: + return + label.set_text('该时间无采样' if sample is None else '合力 XYZ 原始值:'+' / '.join(f'{v:.0f}' for v in sample['resultant'])) + for index,series in enumerate(chart.options['series']): + series['data']=[row[index] for row in sample['taxels']] if sample else [] + chart.update() + series=timeline.joints.get(self.joint.value,([],[])) + for option,values in zip(self.chart.options['series'],series): + option['data']=values[::max(1,(len(values)+699)//700)] + self.chart.options['series'][0]['markLine']={'silent':True,'symbol':'none','label':{'show':False},'data':[{'xAxis':self.cursor}]} + self.chart.update() + self.joint_table.rows=timeline.joint_rows(self.cursor) + self.joint_table.update() + except (OSError,ValueError,KeyError,TypeError,ImportError) as exc: + self.playing=False + self.error.set_text(f'采样预览失败:{exc}') + finally: + self.rendering=False + + +def build_collection_view(root): + return CollectionView(root) diff --git a/src/openarm_platform/config.py b/src/openarm_platform/config.py index 8fa9265..4ea9122 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,12 @@ class PlatformConfig: log_dir: Path support: tuple[Page, ...] = () title: str = 'OpenArm Platform' + policy_record_root: Path = field(default_factory=lambda: Path.home() / 'openarm-episodes') + collection_root: Path = field(default_factory=lambda: Path.home() / 'openarm-collection') @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 +68,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', 'collection_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 +114,20 @@ 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('collection', '数采可视化', None, '录制状态、数据流质量与多模态回放', path='/collection')) + pages.append(Page('policy', '策略可视化', None, '策略仿真、目标与反馈轨迹、记录回放', path='/policy')) + collection_root = path_value(data.get('collection_root', '~/openarm-collection')) + if 'collection_root' not in data: + teleop = next(p for p in pages if p.id == 'teleop') + if '--collection-profile' in teleop.command: + index = teleop.command.index('--collection-profile') + 1 + if index < len(teleop.command): + profile = Path(teleop.command[index]).expanduser() + if not profile.is_absolute(): + profile = (teleop.cwd or base) / profile + if profile.is_file(): + acquisition = json.loads(profile.read_text()) + collection_root = (profile.parent / acquisition['root']).resolve() 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')), collection_root)) diff --git a/src/openarm_platform/dashboard.py b/src/openarm_platform/dashboard.py index 2879788..cee7e2c 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', 'collection': 'storage'} 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(f'{len(self.pages)} 个模块 · 同一个工作空间'), '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.id == 'collection' else '策略页支持仿真和记录回放 · 当前设备连接保持不变' if page.path else '切换到感知页面会保留当前控制或遥操连接') else: self.current_label.set_text('概览') - self.footer.set_text('四个模块 · 同一个工作空间') + self.footer.set_text(f'{len(self.pages)} 个模块 · 同一个工作空间') 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..b13c104 --- /dev/null +++ b/src/openarm_platform/policy_view.py @@ -0,0 +1,214 @@ +"""Native NiceGUI policy visualization inside the existing platform origin.""" +import asyncio +import math +import time + +from openarm_runtime import __version__ + +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(f'OpenArm {__version__} · 仿真与记录回放').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/src/openarm_runtime/__init__.py b/src/openarm_runtime/__init__.py index 6226c65..4000f45 100644 --- a/src/openarm_runtime/__init__.py +++ b/src/openarm_runtime/__init__.py @@ -5,5 +5,5 @@ from .calibration import calibrate_arm from .telemetry import MotorRange, MotorState, ArmConnection -__version__ = "0.8.0" +__version__ = "0.8.1" __all__ = ["Profile", "hold_arm", "calibrate_arm", "MotorRange", "MotorState", "ArmConnection"] diff --git a/src/openarm_runtime/__main__.py b/src/openarm_runtime/__main__.py index 70f4ff4..971a218 100644 --- a/src/openarm_runtime/__main__.py +++ b/src/openarm_runtime/__main__.py @@ -28,6 +28,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) @@ -205,11 +207,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 d01c805..e832f65 100644 --- a/src/openarm_runtime/arm.py +++ b/src/openarm_runtime/arm.py @@ -1,13 +1,15 @@ """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. # J1–J7: Enactic openarm_description OpenArm v2 control_gains.yaml. # J8 is not specified upstream; retain the existing gripper gains. FOLLOWER_KP = (70.0, 70.0, 70.0, 60.0, 10.0, 10.0, 10.0, 25.0) @@ -15,11 +17,16 @@ class ArmHold: - def __init__(self, bus, cancelled, record, publish, *, tracking=False, gravity=None, observe=None): + def __init__(self, bus, cancelled, record, publish, *, tracking=False, manual_side=None, gravity=None, observe=None): self.bus, self.cancelled, self.record, self.publish = bus, cancelled, record, publish self.tracking = tracking self.gravity = gravity self.observe = observe + 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 = {} @@ -52,6 +59,13 @@ def __enter__(self): state = self.bus.state(mid) self.validate(state, enabled=False) initial[mid] = state + 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) if self.gravity is not None: self.gravity.preflight(initial, self.bus.ranges) @@ -73,9 +87,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) @@ -83,15 +100,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. @@ -120,7 +144,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): @@ -129,17 +153,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): @@ -161,30 +203,50 @@ def track(self, targets): def _exchange(self, targets, kp, kd): before = self.states - feedforward = {mid: 0.0 for mid in IDS} - if self.gravity is None: - started = time.monotonic() - states = self.bus.exchange(targets, kp, kd) - else: - feedforward = self.gravity.update(self.states) - for mid in IDS: - state = self.states[mid] - effort = kp[mid-1] * (targets[mid] - state.position) - kd[mid-1] * state.velocity + feedforward[mid] - if abs(effort) > .9 * self.bus.ranges[mid].torque: - raise RuntimeError(f"ID{mid}: combined PD/gravity effort near firmware range") + 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: + feedforward = None if self.gravity is None else self.gravity.update(self.states) + if feedforward is not None: + for mid in IDS: + state = self.states[mid] + effort = kp[mid-1] * (targets[mid] - state.position) - kd[mid-1] * state.velocity + feedforward[mid] + if abs(effort) > .9 * self.bus.ranges[mid].torque: + raise RuntimeError(f"ID{mid}: combined PD/gravity effort near firmware range") + if frame is not None: + frame["gravity"] = self.gravity.last + if self.motion: + self.motion.supervise(self.states, targets, self.bus.ranges, kp, kd, time.monotonic(), feedforward=feedforward) started = time.monotonic() - states = self.bus.exchange(targets, kp, kd, feedforward) - 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) + states = (self.bus.exchange(targets, kp, kd) if feedforward is None else + self.bus.exchange(targets, kp, kd, feedforward)) + 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, feedforward=feedforward) + 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 if self.observe is not None: self.observe({"dispatch_started_at": started, "exchange_completed_at": time.monotonic(), "targets_rad": dict(targets), "kp": tuple(kp), "kd": tuple(kd), - "feedforward_nm": feedforward, + "feedforward_nm": feedforward if feedforward is not None else dict.fromkeys(IDS, 0.0), "observation_before": {mid: asdict(s) for mid, s in before.items()}, "feedback": {mid: asdict(s) for mid, s in states.items()}, "gravity": self.gravity.last if self.gravity else None}) 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/config.py b/src/openarm_runtime/config.py index e4a7c44..08981db 100644 --- a/src/openarm_runtime/config.py +++ b/src/openarm_runtime/config.py @@ -79,6 +79,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/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..9299b62 --- /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, feedforward=None): + 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 + (feedforward or {}).get(mid, 0.0) + 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 73baa21..1bdf0c8 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) @@ -111,12 +127,14 @@ def progress(message): report.record({"event": "modes", "readback": modes}) gravity = prepare_gravity(self.profile, self.side, bus, preflight) - with ArmHold(bus, self.cancel.is_set, report.record, publish, gravity=gravity) as control: + with ArmHold(bus, self.cancel.is_set, report.record, publish, manual_side=self.side, gravity=gravity) 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") @@ -143,6 +161,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() @@ -153,24 +176,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 @@ -184,17 +209,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) @@ -211,8 +242,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): @@ -223,12 +256,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 c188c3d..9093d7a 100644 --- a/src/openarm_runtime/report.py +++ b/src/openarm_runtime/report.py @@ -19,7 +19,10 @@ 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) @@ -28,6 +31,59 @@ def record(self, event): 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() + + class AsyncReport: """Bounded teleoperation diagnostic journal; legacy JSON is finalized on close. 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/src/openarm_runtime/transport.py b/src/openarm_runtime/transport.py index ce9bb76..041e596 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 @@ -158,8 +161,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 164bfe3..c2361c1 100644 --- a/tests/test_arm.py +++ b/tests/test_arm.py @@ -122,6 +122,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_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() diff --git a/tests/test_collection_preview.py b/tests/test_collection_preview.py new file mode 100644 index 0000000..0b8f6f9 --- /dev/null +++ b/tests/test_collection_preview.py @@ -0,0 +1,142 @@ +"""Collection monitoring/replay reads real-format fixtures, never owns hardware.""" +import hashlib +import importlib.util +import json +import math +from pathlib import Path +import tempfile +import time +import unittest +from unittest.mock import patch + +from openarm_collection import Collection +from openarm_collection.recording import atomic_json +from openarm_platform.collection import CollectionBrowser +from test_collection import fixture, np + + +class CollectionPreviewTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + + def wait_for(self, condition): + deadline = time.monotonic()+3 + while time.monotonic()