Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
05241c15dThis file is pinned to the selected release. Download the original to open it in your design tool.
#!/usr/bin/env python
# Copyright 2026 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Bridge remote operators' keyboard intent (over LiveKit) into the TOM arms — with a fair QUEUE.
Runs on the Raspberry Pi next to the arms, as a SEPARATE process from the robot-control loop — the
same standalone, torch-free pattern as ``-m tomctl.livekit.cameras`` (it imports only ``livekit`` + stdlib).
It joins the SAME LiveKit room the cameras publish to, so camera video flows DOWN to operators and
control flows UP over the same authenticated, DTLS-encrypted WebRTC session.
ARCADE QUEUE MODEL (this is the new part):
* Up to TWO arms (``--arms arm1 arm2``), driven STRICTLY ONE AT A TIME. Across sessions the active
arm **cycles** arm1 -> arm2 -> arm1 -> ... (with a single arm it just reuses it).
* Anyone with a valid token may **join** a single shared FIFO queue (open access by default; pass
``--operator`` one or more times to restrict to an allow-list). Joining/driving uses the
server-verified LiveKit identity, which cannot be spoofed.
* When no arm is active and someone is waiting, the head of the queue is auto-assigned to the NEXT
arm in the cycle (a new session). Everyone else waits and spectates the video.
* A session **starts** automatically with torque ON + a move to HOME, and **ends** (on **release**,
an **idle timeout** ``--idle-timeout-s``, or an optional **max session time** ``--max-session-s``)
with a move to REST + torque OFF — signalled to the teleop as the one-shot edges ``session_start`` /
``session_end``.
* A **disconnect** does NOT end the session immediately: the operator's slot (or queue spot) is held
for ``--disconnect-grace-s`` seconds so a refresh/reconnect with the SAME identity resumes it in
place (the arm just freezes meanwhile — no re-home). If they don't return in time, it's released.
* The active driver may pin a **primary camera** (RPC ``set_camera``); it is broadcast in the state
and reset when their session ends.
* The bridge broadcasts queue/session state on data topic ``"session"`` so each viewer can show its
position / "you're driving ARM x / m:ss left", the board, and the pinned camera.
Data flow (per driven arm):
operator browser ──(LiveKit data, topic "control")──► [this bridge] ──(UDP 127.0.0.1)──►
teleop --remote-port N → RemoteTargetServer → CartesianController → arm{1,2}
The bridge is a thin AUTHENTICATED RELAY + queue manager. It does not integrate motion or talk to the
servos; it stamps each operator's *intent frame* (just the held keys) with that operator's ASSIGNED arm
and forwards it to the teleop, which translates held keys into the SAME ``command_delta`` the local
keyboard uses. The home/rest/torque moves are AUTOMATIC at the session boundaries (the bridge injects
``session_start`` / ``session_end`` edges) — the operator sends no edges of its own. All the teleop's
guards (workspace boundary, max_relative_target, IK clamp, 0.4 s deadman, park-on-exit) still apply.
Wire protocol:
* operator → bridge, topic ``"control"``: intent frame (held keys only; no edges)
{"seq": 30, "type": "intent", "deadman": true, "held": ["up","left","."]}
The operator never names an arm; the bridge stamps the assigned arm when relaying.
* operator → bridge, RPC (destination identity = this bridge, default ``pi-control``):
join payload {"name": "<display>"} -> "driving" | "queued" | "denied"
release -> "ok" (leave the queue and/or end your session)
set_camera payload {"camera": "<name>"} -> "ok" | "denied" (active driver only)
* bridge → all, topic ``"session"`` (reliable):
{"type":"state",
"arms":{"arm1":{"driver":"alice","name":"ALICE","remaining_s":42.0,"max_s":120},
"arm2":{"driver":null}},
"queue":[{"id":"bob","name":"BOB"}]}
* bridge → teleop, UDP datagram: the intent frame plus ``"arm": "<arm_id>"``.
Setup (in the project venv): uv pip install "livekit>=1.0" livekit-api # already on the Pi rig
Run (dev mode, on the Pi, alongside the camera publisher and a teleop with --remote-port):
python -m tomctl.real --port <PORT> --id tom_follower_01 --remote-port 9090
python -m tomctl.livekit.bridge --room tom-cams --arms arm1 arm2 --remote-port 9090
Offline self-test of the queue/parse/relay logic (no LiveKit, no network):
python -m tomctl.livekit.bridge --selftest
"""
from __future__ import annotations
import argparse
import json
import logging
import os
import socket
import time
from collections.abc import Callable
from datetime import datetime
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("tom-control-bridge")
# Must match RemoteTargetServer.JOG_VELOCITY keys in -m tomctl.control.
HELD_TOKENS = frozenset({"up", "down", "left", "right", "'", ".", "[", "]"})
# Operators send NO edges — the session lifecycle (home/rest/torque) is bridge-injected. So any edge
# arriving in an operator frame is dropped; this keeps a stray/old client from injecting actions.
EDGE_ACTIONS: frozenset[str] = frozenset()
CONTROL_TOPIC = "control" # operator -> bridge intent frames
STATE_TOPIC = "session" # bridge -> all queue/session state broadcasts
ADMIN_TOPIC = "admin" # server (password-gated) -> bridge pause/resume; server-injected only
EDGE_REPEATS = 5 # resend each edge in this many consecutive datagrams (loopback UDP dedup by id)
SESSION_GAP_S = 1.0 # a control gap longer than this is a new operator session (reset the seq baseline)
# --------------------------------------------------------------------------------------------------
# Pure logic (no LiveKit / no sockets) — unit-tested by --selftest.
# --------------------------------------------------------------------------------------------------
def parse_intent(payload: bytes | str) -> dict | None:
"""Parse + validate one operator intent frame. Returns a normalised dict or None if invalid.
Normalised shape: {"seq": int, "deadman": bool, "held": [str...], "edges": [{"id":int,"action":str}...]}.
Unknown held tokens and unknown/malformed edges are dropped (not rejected wholesale), so one bad
field never discards a whole frame; a structurally invalid frame returns None."""
try:
msg = json.loads(payload.decode() if isinstance(payload, bytes) else payload)
except Exception:
return None
if not isinstance(msg, dict):
return None
raw_seq = msg.get("seq", 0)
seq = int(raw_seq) if isinstance(raw_seq, (int, float)) and not isinstance(raw_seq, bool) else 0
held_in = msg.get("held", [])
held = [k for k in held_in if k in HELD_TOKENS] if isinstance(held_in, list) else []
edges_out = []
edges_in = msg.get("edges", [])
if isinstance(edges_in, list):
for e in edges_in:
if not isinstance(e, dict):
continue
try:
eid, action = int(e["id"]), str(e["action"])
except (KeyError, TypeError, ValueError):
continue
if action in EDGE_ACTIONS:
edges_out.append({"id": eid, "action": action})
return {"seq": seq, "deadman": bool(msg.get("deadman", False)), "held": held, "edges": edges_out}
def build_datagram(seq: int, arm: str, held: list[str], deadman: bool, edges: list[dict]) -> bytes:
"""Encode the UDP intent datagram the teleop RemoteTargetServer consumes (tagged with the arm)."""
return json.dumps(
{"seq": seq, "t": time.time(), "type": "intent", "arm": arm,
"deadman": deadman, "held": held, "edges": edges}
).encode()
def build_status_datagram(arm: str, online: bool, fault: str | None) -> bytes:
"""Encode the teleop→bridge liveness report (the reverse of the one-way intent path). The teleop
sends this a few Hz; the bridge folds it into `arm_online`/`arm_fault` and the session broadcast."""
return json.dumps({"type": "status", "arm": arm, "online": bool(online), "fault": fault}).encode()
def parse_status(data: bytes) -> dict | None:
"""Validate an inbound status datagram → {"arm", "online", "fault"} or None if malformed."""
try:
raw = data.decode() if isinstance(data, (bytes, bytearray)) else data
msg = json.loads(raw)
except (ValueError, UnicodeDecodeError):
return None
if not isinstance(msg, dict) or msg.get("type") != "status":
return None
arm = msg.get("arm")
if not isinstance(arm, str) or not arm:
return None
fault = msg.get("fault")
return {"arm": arm, "online": bool(msg.get("online", False)),
"fault": str(fault) if fault else None}
# --------------------------------------------------------------------------------------------------
# Per-arm relay buffer: the latest held/deadman an arm's assigned driver sent, plus a queue of
# one-shot edges re-keyed to bridge-monotonic ids. Mutated only on the asyncio loop thread.
# --------------------------------------------------------------------------------------------------
class ArmRelay:
def __init__(self, operator_timeout: float) -> None:
self.operator_timeout = operator_timeout
self.holder: str | None = None # identity currently assigned to this arm (or None)
self.held: list[str] = []
self.deadman: bool = False
self.in_seq: int = -1 # last applied operator seq (latest-wins)
self.last_rx: float = 0.0 # monotonic time of the last accepted operator frame
self._edge_queue: list[tuple[int, str, int]] = [] # (id, action, repeats_left)
self._edge_id: int = 0
self._seen_op_edges: set[int] = set() # operator edge ids already enqueued (dedup re-sends)
def fresh(self) -> bool:
return self.holder is not None and (time.monotonic() - self.last_rx) <= self.operator_timeout
def accept(self, frame: dict) -> None:
"""Apply a validated operator frame (latest-wins on seq for held; edges always enqueued)."""
now = time.monotonic()
if now - self.last_rx > SESSION_GAP_S:
# The driver reconnected/refreshed and their seq restarted low. Reset the baseline and DROP
# the held set so the previous burst's motion can never resume.
self.in_seq = -1
self.held = []
self.deadman = False
self._seen_op_edges.clear()
if frame["seq"] >= self.in_seq:
self.in_seq = frame["seq"]
self.held = frame["held"]
self.deadman = frame["deadman"]
for e in frame["edges"]:
# De-dup by the OPERATOR's edge id: a sender that re-sends the same edge across frames for
# reliability fires the action exactly once.
if e["id"] in self._seen_op_edges:
continue
self._seen_op_edges.add(e["id"])
self._enqueue_edge(e["action"])
if len(self._seen_op_edges) > 4096: # bound memory; operator ids are monotonic per session
self._seen_op_edges = set(sorted(self._seen_op_edges)[-1024:])
self.last_rx = now
def inject_edge(self, action: str) -> None:
"""Locally-originated edge (e.g. estop on session end / rearm on assignment / via RPC)."""
self._enqueue_edge(action)
def _enqueue_edge(self, action: str) -> None:
# Re-key to a bridge-monotonic id so the teleop's de-dup never confuses two operators'
# independent id streams, and an operator can't replay an old edge id.
self._edge_id += 1
self._edge_queue.append((self._edge_id, action, EDGE_REPEATS))
def drain_edges(self) -> list[dict]:
"""Edges to include in THIS datagram; each is repeated EDGE_REPEATS times then dropped."""
out, keep = [], []
for eid, action, n in self._edge_queue:
out.append({"id": eid, "action": action})
if n - 1 > 0:
keep.append((eid, action, n - 1))
self._edge_queue = keep
return out
def assign(self, identity: str) -> None:
"""A new operator took this arm: clear the previous driver's motion, seq baseline and edge-id
memory (so their low edge ids don't collide), then fire session_start (clear latch + torque on
+ move to home) so the arm comes up powered and ready."""
self.holder = identity
self.held = []
self.deadman = False
self.in_seq = -1
self._edge_queue = []
self._seen_op_edges.clear()
self.inject_edge("session_start") # torque on + home; fresh session starts un-latched
def release(self) -> None:
"""The session ended. Drop motion + holder; the caller fires session_end (park + torque off)."""
self.holder = None
self.held = []
self.deadman = False
# --------------------------------------------------------------------------------------------------
# Queue + arm-slot assignment. Pure logic (time injected) — unit-tested by --selftest.
# --------------------------------------------------------------------------------------------------
class Session:
def __init__(self, identity: str, name: str, now: float) -> None:
self.identity = identity
self.name = name or identity
self.started_at = now
self.last_active = now
self.ever_active = False # True once the driver sends any real input; gates the initial-idle timer
self.deadline: float | None = None # set at assignment when a max-session time is configured
class SessionManager:
"""Shared FIFO queue feeding the arms ONE AT A TIME (strict single-driver), cycling which physical
arm each session lands on: arm1 -> arm2 -> arm1 -> ... With a single arm it just reuses it. Time is
injected (monotonic seconds). Also holds the active driver's primary-camera pick.
`slots` keeps one entry per arm for the relay/snapshot code, but AT MOST ONE is ever non-None."""
def __init__(self, arms: list[str], max_session_s: float | None, idle_timeout_s: float,
disconnect_grace_s: float = 0.0, initial_idle_timeout_s: float = 20.0,
audit_cb: Callable[[dict], None] | None = None) -> None:
self.arm_ids = list(arms)
self.max_session_s = max_session_s
# Optional durable driver log: called with one record per session start/end (the run loop stamps a
# wall-clock ts + appends it to a JSONL file). Kept as a callback so SessionManager stays pure I/O-
# free and clock-free (tests/selftest inject nothing or a list collector). See _audit.
self.audit_cb = audit_cb
self.idle_timeout_s = idle_timeout_s
# Stricter idle timer for a driver who NEVER sends a single input (AFK at home): fires earlier than
# the general idle timeout (which tolerates a legitimate mid-drive pause). 0 disables.
self.initial_idle_timeout_s = initial_idle_timeout_s
self.disconnect_grace_s = disconnect_grace_s
self.slots: dict[str, Session | None] = {a: None for a in self.arm_ids}
self.queue: list[Session] = []
# identities that dropped their connection but whose slot/queue spot is held until this monotonic
# deadline; a reconnect (same identity) within the window resumes it, otherwise it's released.
self.pending: dict[str, float] = {}
self.last_arm: str | None = None # arm used by the previous session, for the cycle
self.primary_camera: str | None = None # active driver's pinned camera (reset when they leave)
# --- health, folded into the broadcast so the web client can show ARMS_OFFLINE / MAINTENANCE ---
# Each arm is assumed ONLINE until the teleop's status back-channel says otherwise (so a bridge
# running against a teleop that predates the probe never falsely reports arms offline). Once an
# arm has EVER reported, its telemetry going stale (teleop gone / wedged) flips it offline.
self.arm_online: dict[str, bool] = {a: True for a in self.arm_ids}
self.arm_fault: dict[str, str | None] = {a: None for a in self.arm_ids}
self.arm_status_at: dict[str, float] = {} # monotonic time of the last status report per arm
self.status_timeout_s = 3.0 # a reported arm with no fresh telemetry ⇒ offline
# Admin pause (echoed to every viewer). robots_paused parks + blocks driving; cameras_paused is
# the operator's "we're down" intent (also blocks driving) — actual camera-track teardown lives
# in the standalone camera publisher.
self.robots_paused = False
self.cameras_paused = False
# Deferred robots pause: admin queued a pause that fires the moment the current session ends
# (natural release, idle timeout, max-time, disconnect grace). Lets an operator apply a
# non-urgent fix without abruptly kicking the current driver. Cleared by immediate pause/resume.
self.robots_pause_pending = False
def arm_of(self, identity: str) -> str | None:
for aid, s in self.slots.items():
if s is not None and s.identity == identity:
return aid
return None
def _queued(self, identity: str) -> bool:
return any(s.identity == identity for s in self.queue)
def join(self, identity: str, name: str, now: float) -> str:
"""Enqueue an identity (no-op if already driving/queued), then try to assign. Returns the
resulting role: 'driving' or 'queued'."""
self.pending.pop(identity, None) # an explicit join clears any pending disconnect hold
if self.arm_of(identity) is None and not self._queued(identity):
self.queue.append(Session(identity, name, now))
self._assign(now)
return "driving" if self.arm_of(identity) is not None else "queued"
def _audit(self, event: str, aid: str, s: "Session | None", now: float, reason: str | None = None) -> None:
"""Emit one durable driver-log record (session start/end). No-op without an audit_cb."""
if self.audit_cb is None or s is None:
return
rec = {"event": event, "arm": aid, "identity": s.identity, "name": s.name}
if event == "end":
rec["reason"] = reason
rec["duration_s"] = round(max(0.0, now - s.started_at), 1)
try:
self.audit_cb(rec)
except Exception: # a broken sink must never disturb the queue
logger.warning("driver-log audit_cb failed", exc_info=False)
def leave(self, identity: str, now: float, reason: str = "left") -> None:
"""Remove an identity from its slot and/or the queue, then assign the next person (to the OTHER
arm — see _assign). Ending the active session resets the pinned camera."""
self.pending.pop(identity, None)
aid = self.arm_of(identity)
if aid is not None:
self._audit("end", aid, self.slots[aid], now, reason)
self.slots[aid] = None
self.primary_camera = None
self.queue = [s for s in self.queue if s.identity != identity]
self._assign(now)
def mark_disconnected(self, identity: str, now: float) -> bool:
"""A participant dropped. If they hold a slot or a queue spot, keep it for `disconnect_grace_s`
(a same-identity reconnect resumes it); with grace <= 0, release immediately. Returns True if the
slot/queue changed *now* (i.e. an immediate release the caller must reconcile)."""
if self.arm_of(identity) is None and not self._queued(identity):
return False
if self.disconnect_grace_s > 0:
self.pending[identity] = now + self.disconnect_grace_s
logger.info("participant %r disconnected -> holding its spot %.0fs for reconnect",
identity, self.disconnect_grace_s)
return False
self.leave(identity, now, reason="disconnected")
logger.info("participant %r disconnected -> released/dequeued (no grace)", identity)
return True
def mark_reconnected(self, identity: str) -> bool:
"""Same identity came back within the grace window — cancel the pending release. Returns True if
a hold was actually cancelled."""
if identity in self.pending:
del self.pending[identity]
return True
return False
def sweep_grace(self, now: float, connected: set[str]) -> bool:
"""Resolve held spots: cancel the hold for any identity that's connected again, release any whose
grace expired (then reassign). `connected` = identities currently in the room. Returns True if a
slot/queue changed (caller should reconcile)."""
changed = False
for ident, deadline in list(self.pending.items()):
if ident in connected:
del self.pending[ident]
logger.info("participant %r reconnected within grace -> spot resumed", ident)
elif now >= deadline:
logger.info("participant %r grace expired -> released/dequeued", ident)
self.leave(ident, now, reason="disconnected") # also clears self.pending[ident]
changed = True
return changed
def hold_all(self, now: float, grace_s: float) -> None:
"""Put every current holder + queued identity on a grace hold — used right after a restart-restore
so the per-loop sweep resumes whoever is actually present and drops no-shows once grace expires."""
for s in list(self.slots.values()) + self.queue:
if s is not None:
self.pending[s.identity] = now + max(0.0, grace_s)
def note_active(self, identity: str, now: float) -> None:
"""Reset the idle timer for a driver that is actually driving (deadman held or edge fired)."""
aid = self.arm_of(identity)
if aid is not None:
self.slots[aid].last_active = now # type: ignore[union-attr]
self.slots[aid].ever_active = True # type: ignore[union-attr] # clears the initial-idle timer
def set_camera(self, identity: str, camera: str, now: float) -> bool:
"""Pin a primary camera — accepted ONLY from the current active driver. Returns True if applied."""
if self.arm_of(identity) is None:
return False
self.primary_camera = camera
return True
def set_arm_status(self, arm: str, online: bool, fault: str | None, now: float) -> None:
"""Ingest an arm-liveness report from the teleop's status back-channel. Unknown arms are ignored."""
if arm not in self.arm_online:
return
self.arm_online[arm] = online
self.arm_fault[arm] = fault if not online else None
self.arm_status_at[arm] = now
def set_paused(self, target: str, paused: bool) -> None:
"""Apply an admin pause/resume. Parking + reassignment happen on the next tick(). An explicit
pause/resume on robots always supersedes and clears any queued pause-after-session (the admin
just took a definitive stance)."""
if target == "robots":
self.robots_paused = paused
self.robots_pause_pending = False
elif target == "cameras":
self.cameras_paused = paused
def arm_pause_after_session(self, target: str) -> None:
"""Queue a robots pause that fires when the current session ends. If nobody is driving, the
next tick() (or arm-immediate check below) collapses it into an immediate pause. No-op on an
already-paused target — you don't need to queue what's already done. Cameras isn't
session-scoped so this is robots-only."""
if target != "robots" or self.robots_paused:
return
# if no arm is active, don't bother waiting — pause now so the admin's fix window opens
if not any(self.slots[a] is not None for a in self.arm_ids):
self.robots_paused = True
self.robots_pause_pending = False
else:
self.robots_pause_pending = True
@property
def system_paused(self) -> bool:
"""Either admin pause blocks driving (robots = arm hold; cameras = 'we're down' intent)."""
return self.robots_paused or self.cameras_paused
def _expire_stale_status(self, now: float) -> None:
"""An arm that reported once but has since gone silent past the timeout is treated as offline —
covers a teleop that died or wedged (the arm is no longer confirmed live)."""
for aid, at in self.arm_status_at.items():
if now - at > self.status_timeout_s and self.arm_online.get(aid, True):
self.arm_online[aid] = False
self.arm_fault[aid] = "no telemetry"
logger.info("arm %s status stale (%.1fs) -> offline", aid, now - at)
def _drivable(self, aid: str) -> bool:
"""An arm can be assigned/kept only if it's online and driving isn't admin-paused."""
return self.arm_online.get(aid, True) and not self.system_paused
def tick(self, now: float) -> None:
"""Expire the active session on idle / max-time / health, then assign the next waiting user.
A queued pause-after-session fires the instant the last slot empties (before assignment) so
the next driver in the queue is held until the admin resumes."""
self._expire_stale_status(now)
for aid, s in self.slots.items():
if s is None:
continue
if s.deadline is not None and now >= s.deadline:
logger.info("arm %s session (%r) hit max time -> released", aid, s.identity)
self._audit("end", aid, s, now, "max_time")
self.slots[aid] = None
self.primary_camera = None
elif (not s.ever_active and self.initial_idle_timeout_s > 0
and (now - s.started_at) > self.initial_idle_timeout_s):
logger.info("arm %s session (%r) never active %.0fs -> released (initial idle)",
aid, s.identity, self.initial_idle_timeout_s)
self._audit("end", aid, s, now, "initial_idle")
self.slots[aid] = None
self.primary_camera = None
elif self.idle_timeout_s > 0 and (now - s.last_active) > self.idle_timeout_s:
logger.info("arm %s session (%r) idle %.0fs -> released", aid, s.identity, self.idle_timeout_s)
self._audit("end", aid, s, now, "idle")
self.slots[aid] = None
self.primary_camera = None
elif not self._drivable(aid):
# UNIFIED recovery path: any degradation (arm went offline, or admin paused) parks the
# active arm and blocks driving, but the driver KEEPS their turn — re-enqueued at the
# head so the standard assignment resumes them once the system is drivable again.
reason = "robots paused" if self.system_paused else "arm offline"
logger.info("arm %s session (%r) suspended -> %s (held at queue head)", aid, s.identity, reason)
self._audit("end", aid, s, now, "suspended:" + reason.replace(" ", "_"))
if not self._queued(s.identity):
s.deadline = None # a fresh turn is granted on reassignment
self.queue.insert(0, s)
self.slots[aid] = None
self.primary_camera = None
# queued pause: the moment no arm is active, flip to a real pause BEFORE _assign() so the next
# driver isn't handed the arm just to be immediately suspended again.
if self.robots_pause_pending and not any(self.slots[a] is not None for a in self.arm_ids):
self.robots_paused = True
self.robots_pause_pending = False
logger.info("pause-after-session fired -> robots paused (queue holds until resume)")
self._assign(now)
def _next_arm(self) -> str | None:
"""Which arm the next session lands on: alternate away from last_arm over the DRIVABLE arms
(skips offline arms; single/absent -> the first drivable). None if no arm can be driven."""
drivable = [a for a in self.arm_ids if self._drivable(a)]
if not drivable:
return None
if len(drivable) == 1 or self.last_arm is None:
return drivable[0]
start = (self.arm_ids.index(self.last_arm) + 1) % len(self.arm_ids)
for k in range(len(self.arm_ids)):
cand = self.arm_ids[(start + k) % len(self.arm_ids)]
if self._drivable(cand):
return cand
return None
def _assign(self, now: float) -> None:
# STRICT SINGLE: assign only when NO arm is active; pick the next DRIVABLE arm in the cycle.
if not self.queue or any(self.slots[a] is not None for a in self.arm_ids):
return
aid = self._next_arm()
if aid is None:
return # nothing drivable (all arms offline / admin-paused) — hold the queue
s = self.queue.pop(0)
s.started_at = now
s.last_active = now
s.deadline = (now + self.max_session_s) if self.max_session_s else None
self.slots[aid] = s
self.last_arm = aid
logger.info("arm %s assigned to %r (queue now %d)", aid, s.identity, len(self.queue))
self._audit("start", aid, s, now)
def structure(self) -> tuple:
"""A hashable summary of WHO holds what + the queue order + pinned camera + health/pause (ignores
the countdown), for change detection so we broadcast immediately on a real change — including an
arm dropping offline or an admin pause — and otherwise just tick at the periodic rate."""
return (
tuple((a, self.slots[a].identity if self.slots[a] else None) for a in self.arm_ids),
tuple(s.identity for s in self.queue),
self.primary_camera,
tuple((a, self.arm_online.get(a, True)) for a in self.arm_ids),
self.robots_paused,
self.cameras_paused,
self.robots_pause_pending,
)
def snapshot(self, now: float) -> dict:
arms = {}
for aid in self.arm_ids:
s = self.slots[aid]
health = {"online": self.arm_online.get(aid, True), "fault": self.arm_fault.get(aid)}
if s is None:
arms[aid] = {"driver": None, **health}
else:
remaining = None if s.deadline is None else max(0.0, round(s.deadline - now, 1))
# Inactivity countdown for the /control UI: the STRICT initial-idle timer until the driver
# sends a first input, then the general idle timeout. idle_kind lets the client word it.
if not s.ever_active and self.initial_idle_timeout_s > 0:
idle_rem, idle_kind = max(0.0, round(self.initial_idle_timeout_s - (now - s.started_at), 1)), "initial"
elif self.idle_timeout_s > 0:
idle_rem, idle_kind = max(0.0, round(self.idle_timeout_s - (now - s.last_active), 1)), "idle"
else:
idle_rem, idle_kind = None, None
arms[aid] = {"driver": s.identity, "name": s.name,
"remaining_s": remaining, "max_s": self.max_session_s,
"idle_remaining_s": idle_rem, "idle_kind": idle_kind, **health}
return {"type": "state", "arms": arms,
"queue": [{"id": s.identity, "name": s.name} for s in self.queue],
"primary_camera": self.primary_camera,
"robots_paused": self.robots_paused,
"robots_pause_pending": self.robots_pause_pending,
"cameras_paused": self.cameras_paused}
def to_state(self, now: float) -> dict:
"""Serialisable snapshot for on-disk persistence: who holds each arm + the queue order + the
pinned camera + arm-cycle position. Timing is stored as REMAINING seconds (monotonic clocks
reset across a restart), so a reload rebuilds absolute deadlines from the load-time clock."""
def ser(s: Session) -> dict:
remaining = None if s.deadline is None else max(0.0, s.deadline - now)
return {"identity": s.identity, "name": s.name, "remaining_s": remaining}
return {
"version": 1,
"slots": {aid: (ser(s) if s is not None else None) for aid, s in self.slots.items()},
"queue": [ser(s) for s in self.queue],
"primary_camera": self.primary_camera,
"last_arm": self.last_arm,
}
def load_state(self, state: dict, now: float) -> None:
"""Rebuild slots/queue/camera from a persisted `to_state()` dict. Arms not in the current config
are ignored, an identity can appear only once, deadlines are rebuilt from the load-time clock,
and idle timers start fresh (last_active = now)."""
def de(d: dict) -> Session:
s = Session(str(d.get("identity")), str(d.get("name") or d.get("identity")), now)
rem = d.get("remaining_s")
s.deadline = (now + float(rem)) if rem is not None else None
return s
slots = state.get("slots") or {}
seen: set[str] = set()
for aid in self.arm_ids:
d = slots.get(aid)
if d and d.get("identity") and d["identity"] not in seen:
self.slots[aid] = de(d)
seen.add(d["identity"])
else:
self.slots[aid] = None
self.queue = []
for d in (state.get("queue") or []):
ident = d.get("identity")
if ident and ident not in seen:
self.queue.append(de(d))
seen.add(ident)
self.primary_camera = state.get("primary_camera")
self.last_arm = state.get("last_arm") if state.get("last_arm") in self.arm_ids else None
# --------------------------------------------------------------------------------------------------
# UDP link to the local teleop.
# --------------------------------------------------------------------------------------------------
class UdpLink:
"""Fire-and-forget UDP sender to the local teleop's --remote-port (loopback)."""
def __init__(self, host: str, port: int) -> None:
self.addr = (host, port)
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._seq = 0
def send(self, arm: str, held: list[str], deadman: bool, edges: list[dict]) -> None:
self._seq += 1
try:
self._sock.sendto(build_datagram(self._seq, arm, held, deadman, edges), self.addr)
except OSError as exc:
logger.warning("UDP send failed: %s", exc)
def close(self) -> None:
self._sock.close()
# --------------------------------------------------------------------------------------------------
# Durable state (queue + sessions) — a tiny JSON file so a bridge restart resumes where it left off.
# --------------------------------------------------------------------------------------------------
def save_state(path: str, state: dict) -> None:
"""Atomically write `state` to `path` (temp file + rename) so a crash mid-write can't corrupt it."""
d = os.path.dirname(path)
if d:
os.makedirs(d, exist_ok=True)
tmp = f"{path}.tmp"
with open(tmp, "w") as f:
json.dump(state, f)
os.replace(tmp, path)
def load_state_file(path: str) -> dict | None:
"""Read a persisted state dict, or None if it's missing / unreadable / malformed."""
try:
with open(path) as f:
return json.load(f)
except (FileNotFoundError, ValueError, OSError):
return None
# --------------------------------------------------------------------------------------------------
# LiveKit wiring.
# --------------------------------------------------------------------------------------------------
async def run_bridge(args: argparse.Namespace) -> None:
import asyncio
import signal
from livekit import api, rtc
allow = set(args.operator or []) # optional allow-list; empty = OPEN access (anyone may join)
if allow:
logger.info("restricted to allow-listed operators: %s", ", ".join(sorted(allow)))
else:
logger.warning("OPEN access: any participant that can publish data may join the queue & drive.")
arm_ids = list(args.arms)
# Durable driver log: one JSONL line per session start/end, appended (never rewritten) so it's a real
# audit trail of who drove which arm, when, for how long, and why the turn ended — independent of the
# journald ring buffer, and it captures the operator NAME (the console log only has the identity).
audit_cb = None
if args.driver_log:
_dl_dir = os.path.dirname(args.driver_log)
if _dl_dir:
os.makedirs(_dl_dir, exist_ok=True)
def _write_driver_log(rec: dict) -> None:
rec = {"ts": datetime.now().astimezone().isoformat(timespec="seconds"), **rec}
try:
with open(args.driver_log, "a") as f:
f.write(json.dumps(rec) + "\n")
except OSError as exc:
logger.warning("driver-log write to %s failed: %s", args.driver_log, exc)
audit_cb = _write_driver_log
logger.info("driver log -> %s", args.driver_log)
mgr = SessionManager(arm_ids, args.max_session_s, args.idle_timeout_s, args.disconnect_grace_s,
args.initial_idle_timeout_s, audit_cb=audit_cb)
relays = {aid: ArmRelay(args.operator_timeout) for aid in arm_ids}
link = UdpLink(args.remote_host, args.remote_port)
# Reverse channel: the teleop reports per-arm liveness here (the intent path is one-way down). A
# non-blocking loopback socket we drain each loop; disabled with --status-port 0 (then arms stay
# advisory-online, i.e. exactly the pre-probe behaviour).
status_sock = None
if args.status_port:
status_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
status_sock.setblocking(False)
try:
status_sock.bind((args.status_host, args.status_port))
logger.info("listening for teleop arm-status on %s:%d", args.status_host, args.status_port)
except OSError as exc:
logger.warning("arm-status listener bind failed (%s) — arms stay advisory-online", exc)
status_sock.close()
status_sock = None
# restore the queue + active session from a previous run, if any (the sweep below reconciles it
# against who's actually in the room once we connect).
if args.state_file:
persisted = load_state_file(args.state_file)
if persisted:
mgr.load_state(persisted, time.monotonic())
logger.info("restored state from %s: %d driving, %d queued", args.state_file,
sum(1 for a in arm_ids if mgr.slots[a] is not None), len(mgr.queue))
token = (
api.AccessToken(args.api_key, args.api_secret)
.with_identity(args.identity)
.with_name("TOM control bridge")
.with_grants(api.VideoGrants(
room_join=True, room=args.room,
can_subscribe=True, # required to RECEIVE data
can_publish=False, # the bridge publishes no tracks
can_publish_data=True, # broadcast session state + answer RPCs
))
.to_jwt()
)
room = rtc.Room()
def _authorized(identity: str) -> bool:
return (not allow) or identity in allow
def _reconcile() -> None:
"""Make each arm's relay buffer agree with the authoritative SessionManager. On a session START
transition inject session_start (torque on + home); on a session END transition inject
session_end (park to rest + torque off). Idempotent — safe after every join/leave/tick."""
for aid in arm_ids:
s = mgr.slots[aid]
want = s.identity if s is not None else None
have = relays[aid].holder
if want == have:
continue
if want is None:
relays[aid].release()
relays[aid].inject_edge("session_end") # park to rest + release torque
logger.info("arm %s session ended -> REST + torque off", aid)
else:
relays[aid].assign(want) # session_start: torque on + home; holds until they drive
logger.info("arm %s now driven by %r", aid, want)
@room.on("data_received")
def _on_data(packet: "rtc.DataPacket") -> None:
topic = packet.topic or ""
if topic == ADMIN_TOPIC:
# SECURITY: admin commands are injected by the web server via the LiveKit HTTP API, so they
# arrive with NO source participant. Anything published on this topic by a real participant
# is a spoof (a browser trying to bypass the password) and is ignored.
if packet.participant is not None:
logger.warning("ignoring admin data from participant %r (spoof)", packet.participant.identity)
return
try:
cmd = json.loads(packet.data.decode())
target, action = cmd.get("target"), cmd.get("action")
except (ValueError, AttributeError, UnicodeDecodeError):
logger.warning("dropped malformed admin command")
return
if target in ("robots", "cameras") and action in ("pause", "resume"):
mgr.set_paused(target, action == "pause")
mgr.tick(time.monotonic()) # apply immediately: park on pause / reassign on resume
_reconcile()
logger.info("admin: %s %sd", target, action)
elif target == "robots" and action == "pause_after_session":
# queue the pause; tick may fire it right away if nobody's driving. Reconcile after
# so an immediate-pause path parks the (empty) arm state consistently.
mgr.arm_pause_after_session(target)
mgr.tick(time.monotonic())
_reconcile()
logger.info("admin: robots pause queued for end of current session")
return
if topic != CONTROL_TOPIC:
return
if packet.participant is None:
return # unresolved sender (brief SDK race at session start); a 25 Hz stream self-corrects
sender = packet.participant.identity
aid = mgr.arm_of(sender)
if aid is None:
return # sender isn't currently driving an arm (queued / spectating) -> ignore control
frame = parse_intent(packet.data)
if frame is None:
logger.warning("dropped malformed intent frame from %r", sender)
return
relays[aid].accept(frame)
if frame["deadman"] or frame["edges"]:
mgr.note_active(sender, time.monotonic()) # actively driving -> keep the session alive
@room.on("participant_disconnected")
def _on_left(participant: "rtc.RemoteParticipant") -> None:
# hold their slot/queue spot for the grace window (a same-identity reconnect resumes it); the
# per-loop sweep_grace releases it if they don't come back. Reconcile only on an immediate release.
if mgr.mark_disconnected(participant.identity, time.monotonic()):
_reconcile()
@room.on("participant_connected")
def _on_joined(participant: "rtc.RemoteParticipant") -> None:
if mgr.mark_reconnected(participant.identity):
logger.info("participant %r reconnected within grace -> spot resumed", participant.identity)
async def _join_rpc(data: "rtc.RpcInvocationData") -> str:
ident = data.caller_identity
if not _authorized(ident):
return "denied"
try:
name = str(json.loads(data.payload or "{}").get("name", ident))[:32]
except Exception:
name = ident
role = mgr.join(ident, name, time.monotonic())
_reconcile()
logger.info("join %r (%r) -> %s", ident, name, role)
return role
async def _release_rpc(data: "rtc.RpcInvocationData") -> str:
ident = data.caller_identity
mgr.leave(ident, time.monotonic())
_reconcile()
logger.info("release %r", ident)
return "ok"
async def _set_camera_rpc(data: "rtc.RpcInvocationData") -> str:
ident = data.caller_identity
try:
camera = str(json.loads(data.payload or "{}").get("camera", ""))[:32]
except Exception:
return "bad-payload"
if not camera or not mgr.set_camera(ident, camera, time.monotonic()):
return "denied" # only the active driver may pin the primary camera
logger.info("primary camera -> %r (by %r)", camera, ident)
return "ok"
await room.connect(args.url, token)
for _name, _fn in (("join", _join_rpc), ("release", _release_rpc), ("set_camera", _set_camera_rpc)):
room.local_participant.register_rpc_method(_name, _fn)
logger.info("bridge connected to %s room=%r as %r -> teleop udp %s:%d arms=%s",
args.url, args.room, args.identity, args.remote_host, args.remote_port, arm_ids)
logger.info("max session: %s | idle timeout: %ss | disconnect grace: %ss",
f"{args.max_session_s}s" if args.max_session_s else "unlimited",
args.idle_timeout_s, args.disconnect_grace_s)
# If we just restored operators from disk, hold them for the (longer) restore grace so clients
# reconnecting after a server restart resume in place; the per-loop sweep drops any no-shows.
if args.state_file and (any(mgr.slots[a] is not None for a in arm_ids) or mgr.queue):
mgr.hold_all(time.monotonic(), args.restore_grace_s)
logger.info("holding restored operators up to %.0fs for reconnect", args.restore_grace_s)
# Sender loop: relay each arm's latest intent to the teleop at a fixed rate, and broadcast the
# queue/session state. When a driver is fresh we forward their held/deadman; when stale or the
# slot is empty we forward a RELEASED frame (no motion) so the arm holds. Pending edges (assign
# rearm, end-of-session estop, RPC estop) are always flushed.
period = 1.0 / args.rate
state_period = 0.5 # broadcast at >=2 Hz for the countdown, plus immediately on any change
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, stop.set)
last_struct = None
last_bcast = 0.0
bcast_seq = 0
try:
while not stop.is_set():
now = time.monotonic()
# Drain any arm-liveness reports from the teleop before the health checks in tick() run.
if status_sock is not None:
while True:
try:
data, _ = status_sock.recvfrom(4096)
except (BlockingIOError, OSError):
break
st = parse_status(data)
if st is not None:
mgr.set_arm_status(st["arm"], st["online"], st["fault"], now)
# livekit 1.x: room.remote_participants (dict by identity); guard the name defensively so a
# future SDK rename can never crash the control loop — worst case grace just expires on time.
_parts = getattr(room, "remote_participants", None)
if _parts is None:
_parts = getattr(room, "participants", {})
connected = {p.identity for p in _parts.values()}
mgr.sweep_grace(now, connected) # resume reconnects / release expired holds
mgr.tick(now)
_reconcile()
for aid in arm_ids:
edges = relays[aid].drain_edges()
if relays[aid].fresh():
link.send(aid, relays[aid].held, relays[aid].deadman, edges)
else:
link.send(aid, [], False, edges)
struct = mgr.structure()
if struct != last_struct or (now - last_bcast) >= state_period:
bcast_seq += 1
snap = mgr.snapshot(now)
snap["ts"] = round(now, 3) # monotonic stamp so the client can age out a silent bridge
snap["seq"] = bcast_seq
try:
await room.local_participant.publish_data(
json.dumps(snap).encode(), reliable=True, topic=STATE_TOPIC)
except Exception as exc: # noqa: BLE001 transient publish failure is non-fatal
logger.debug("state broadcast dropped: %s", exc)
if struct != last_struct and args.state_file: # persist only on a real change
try:
save_state(args.state_file, mgr.to_state(now))
except OSError as exc:
logger.warning("state save to %s failed: %s", args.state_file, exc)
last_struct = struct
last_bcast = now
try:
await asyncio.wait_for(stop.wait(), timeout=period)
except asyncio.TimeoutError:
pass
finally:
if args.state_file: # capture the latest state (with fresh remaining_s) before parking
try:
save_state(args.state_file, mgr.to_state(time.monotonic()))
except OSError as exc:
logger.warning("state save on shutdown failed: %s", exc)
logger.info("bridge shutting down — parking all arms to rest + releasing torque")
for aid in arm_ids:
link.send(aid, [], False, [{"id": 10**9, "action": "session_end"}]) # park + torque off
link.close()
if status_sock is not None:
status_sock.close()
await room.disconnect()
# --------------------------------------------------------------------------------------------------
# Offline self-test of the pure logic.
# --------------------------------------------------------------------------------------------------
def _selftest() -> int:
ok = True
def check(name, cond):
nonlocal ok
print(f" [{'PASS' if cond else 'FAIL'}] {name}")
ok = ok and cond
# --- parse_intent ---
check("rejects non-json", parse_intent(b"not json") is None)
check("rejects non-dict", parse_intent(b"[1,2,3]") is None)
f = parse_intent(b'{"seq":5,"deadman":true,"held":["up","left","X"],"edges":[{"id":1,"action":"home"}]}')
check("parses valid frame", f is not None)
check("filters unknown held token", f["held"] == ["up", "left"])
check("drops ALL operator edges (operators send none)", f["edges"] == [])
check("deadman bool", f["deadman"] is True)
check("seq not fooled by bool", parse_intent(b'{"seq":true}')["seq"] == 0)
# --- ArmRelay: latest-wins, edge re-keying + repeat ---
st = ArmRelay(operator_timeout=0.5)
st.accept({"seq": 1, "deadman": True, "held": ["up"], "edges": []})
st.accept({"seq": 0, "deadman": True, "held": ["down"], "edges": []}) # stale -> ignored
check("latest-wins on seq (held)", st.held == ["up"])
st.accept({"seq": 2, "deadman": True, "held": ["left"], "edges": [{"id": 99, "action": "home"}]})
check("newer seq updates held", st.held == ["left"])
d1 = st.drain_edges()
check("edge re-keyed to bridge id (not operator's 99)", d1 and d1[0]["id"] != 99 and d1[0]["action"] == "home")
check("edge repeats across drains", any(e["action"] == "home" for e in st.drain_edges()))
for _ in range(EDGE_REPEATS + 2):
st.drain_edges()
check("edge eventually drops", st.drain_edges() == [])
st.inject_edge("session_end")
check("injected lifecycle edge drains", any(e["action"] == "session_end" for e in st.drain_edges()))
st.assign("bob")
check("assign fires session_start + clears motion", st.holder == "bob" and st.held == [] and
any(e["action"] == "session_start" for e in st.drain_edges()))
# --- build_datagram round-trips through the receiver's parser shape (now arm-tagged) ---
dg = json.loads(build_datagram(7, "arm2", ["up"], True, [{"id": 3, "action": "rest"}]).decode())
check("datagram has type intent + arm", dg["type"] == "intent" and dg["arm"] == "arm2")
check("datagram carries held+edges+deadman", dg["held"] == ["up"] and dg["deadman"] and dg["edges"][0]["action"] == "rest")
# --- SessionManager: STRICT single driver, arm cycling arm1->arm2->arm1, camera pin ---
t = 100.0
only_one = lambda m: sum(1 for a in m.arm_ids if m.slots[a] is not None) <= 1
mgr = SessionManager(["arm1", "arm2"], max_session_s=None, idle_timeout_s=30.0)
check("alice joins -> driving arm1 (first session)", mgr.join("alice", "ALICE", t) == "driving" and mgr.arm_of("alice") == "arm1")
check("bob joins -> QUEUED (strict single, arm2 NOT used concurrently)",
mgr.join("bob", "BOB", t) == "queued" and only_one(mgr))
check("carol joins -> queued", mgr.join("carol", "CAROL", t) == "queued")
check("double-join is a no-op", mgr.join("bob", "BOB", t) == "queued" and len(mgr.queue) == 2)
mgr.leave("alice", t) # alice releases -> bob takes the OTHER arm (cycle to arm2)
check("cycle: next session lands on arm2", mgr.arm_of("bob") == "arm2" and only_one(mgr))
mgr.leave("bob", t) # bob releases -> carol cycles back to arm1
check("cycle: arm1 -> arm2 -> arm1", mgr.arm_of("carol") == "arm1" and only_one(mgr))
# camera pin: only the ACTIVE driver may set it; resets when their session ends
check("non-driver cannot pin camera", mgr.set_camera("bob", "wrist_1", t) is False and mgr.primary_camera is None)
check("active driver pins camera", mgr.set_camera("carol", "wrist_1", t) is True and mgr.primary_camera == "wrist_1")
snap = mgr.snapshot(t)
check("snapshot has primary_camera + single driver", snap.get("primary_camera") == "wrist_1"
and snap["arms"]["arm1"]["driver"] == "carol" and snap["arms"]["arm2"]["driver"] is None)
mgr.leave("carol", t)
check("camera resets when the session ends", mgr.primary_camera is None)
# single arm: no second arm to cycle to -> always reuses arm1
solo = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0)
solo.join("p", "P", t); solo.join("q", "Q", t)
solo.leave("p", t)
check("single arm reuses arm1 for the next session", solo.arm_of("q") == "arm1")
# idle timeout: active driver AFK -> released, next in queue takes the OTHER arm
mgr3 = SessionManager(["arm1", "arm2"], max_session_s=None, idle_timeout_s=5.0)
mgr3.join("u", "U", t) # u -> arm1
mgr3.join("v", "V", t) # queued
mgr3.tick(t + 10) # u idle since t -> released; v cycles to arm2
check("idle active released, next cycles to arm2", mgr3.arm_of("u") is None and mgr3.arm_of("v") == "arm2")
# initial-idle: a driver who NEVER sends an input is released at the STRICT initial timeout (20s),
# earlier than the general idle timeout (60s) would fire.
ii = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=60.0, initial_idle_timeout_s=20.0)
ii.join("afk", "AFK", t)
ii.tick(t + 10)
check("initial-idle: never-active driver still held before 20s", ii.arm_of("afk") == "arm1")
ii.tick(t + 21)
check("initial-idle: never-active driver released at 20s (before the 60s idle)", ii.arm_of("afk") is None)
# a driver who DID send an input keeps the general idle window, NOT the strict initial one
ai = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=60.0, initial_idle_timeout_s=20.0)
ai.join("drv", "DRV", t)
ai.note_active("drv", t + 5) # sent input -> initial-idle no longer applies
ai.tick(t + 25)
check("initial-idle: an active driver is NOT caught by the strict initial timer", ai.arm_of("drv") == "arm1")
# the countdown surfaces in the snapshot for the /control UI
fresh = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=60.0, initial_idle_timeout_s=20.0)
fresh.join("z", "Z", t)
sarm = fresh.snapshot(t + 8)["arms"]["arm1"]
check("snapshot exposes initial-idle countdown", sarm["idle_kind"] == "initial" and abs(sarm["idle_remaining_s"] - 12.0) < 0.2)
# max-session expiry (single arm)
mgr2 = SessionManager(["arm1"], max_session_s=2.0, idle_timeout_s=0.0)
mgr2.join("x", "X", 0.0); mgr2.join("y", "Y", 0.0) # y queued
mgr2.tick(1.0)
check("within max time keeps driver", mgr2.arm_of("x") == "arm1")
mgr2.tick(2.5)
check("max-session expiry reassigns", mgr2.arm_of("x") is None and mgr2.arm_of("y") == "arm1")
rem = mgr2.snapshot(2.6)["arms"]["arm1"]["remaining_s"]
check("snapshot reports remaining_s under max", isinstance(rem, (int, float)) and rem <= 2.0)
# --- driver audit log: a record on assign (start) and on release (end + reason + duration) ---
audit: list[dict] = []
al = SessionManager(["arm1"], max_session_s=2.0, idle_timeout_s=0.0, audit_cb=audit.append)
al.join("al", "AL", 0.0) # first join assigns immediately -> "start"
al.tick(3.0) # past the 2s cap -> "end" (max_time)
starts = [r for r in audit if r["event"] == "start"]
ends = [r for r in audit if r["event"] == "end"]
check("audit logs a session start with arm/identity/name",
len(starts) == 1 and starts[0]["arm"] == "arm1" and starts[0]["identity"] == "al" and starts[0]["name"] == "AL")
check("audit logs a session end with reason + duration",
len(ends) == 1 and ends[0]["reason"] == "max_time" and ends[0]["duration_s"] == 3.0)
audit.clear()
al2 = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0, audit_cb=audit.append)
al2.join("x", "X", 0.0)
al2.leave("x", 4.0, reason="left")
check("audit end on explicit leave carries the reason + duration",
any(r["event"] == "end" and r["reason"] == "left" and r["duration_s"] == 4.0 for r in audit))
check("audit is a no-op without a callback", SessionManager(["arm1"], None, 0.0).audit_cb is None)
# --- disconnect grace: hold a slot/queue spot across a reconnect, release when it expires ---
g = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0, disconnect_grace_s=15.0)
g.join("d", "D", t) # d -> driving arm1
g.join("e", "E", t) # e -> queued
g.mark_disconnected("d", t) # d drops -> slot HELD (not released yet)
check("disconnect holds the active slot", g.arm_of("d") == "arm1" and "d" in g.pending)
g.sweep_grace(t + 10, connected=set()) # still within grace, nobody connected
check("within grace keeps the held slot", g.arm_of("d") == "arm1")
g.sweep_grace(t + 20, connected=set()) # grace expired, d never came back
check("grace expiry releases + reassigns", g.arm_of("d") is None and g.arm_of("e") == "arm1")
# reconnect within grace via the connected set (race-proof path) resumes in place
g2 = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0, disconnect_grace_s=15.0)
g2.join("f", "F", t); g2.join("h", "H", t) # f driving, h queued
g2.mark_disconnected("f", t)
g2.sweep_grace(t + 20, connected={"f"}) # f is back (in the room) -> hold cancelled, no release
check("reconnect within grace resumes the slot", g2.arm_of("f") == "arm1" and "f" not in g2.pending
and g2.arm_of("h") is None)
# a held QUEUE spot survives too, and mark_reconnected cancels the hold
g3 = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0, disconnect_grace_s=15.0)
g3.join("m", "M", t); g3.join("n", "N", t) # m driving, n queued
g3.mark_disconnected("n", t) # the QUEUED n drops -> spot held
check("mark_reconnected cancels a held queue spot", g3.mark_reconnected("n") is True
and "n" not in g3.pending and any(s.identity == "n" for s in g3.queue))
# grace disabled -> immediate release (old behaviour), and mark_disconnected reports the change
g4 = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0, disconnect_grace_s=0.0)
g4.join("p", "P", t); g4.join("q", "Q", t)
changed = g4.mark_disconnected("p", t)
check("grace=0 releases immediately + signals a change", changed is True
and g4.arm_of("p") is None and g4.arm_of("q") == "arm1")
# --- arm health: offline arms are skipped, the active driver is HELD (not dropped) + resumes ---
hw = SessionManager(["arm1", "arm2"], max_session_s=None, idle_timeout_s=0.0)
hw.join("a", "A", t) # a -> arm1
hw.set_arm_status("arm1", False, "serial", t)
hw.tick(t) # arm1 offline -> a suspended, cycles to the ONLINE arm2
check("offline active arm suspends driver, cycles to the online arm", hw.arm_of("a") == "arm2")
hw.set_arm_status("arm2", False, "serial", t)
hw.tick(t) # both offline -> nobody driving, a held at the queue head
check("all arms offline -> queue holds the driver (no assignment)",
hw.arm_of("a") is None and any(s.identity == "a" for s in hw.queue))
hw.set_arm_status("arm1", True, None, t)
hw.tick(t) # arm1 back -> the held driver resumes automatically
check("recovery reassigns the held driver from the queue head", hw.arm_of("a") == "arm1")
snap = hw.snapshot(t)
check("snapshot carries per-arm online + fault + pause flags",
snap["arms"]["arm1"]["online"] is True and "fault" in snap["arms"]["arm2"]
and snap["robots_paused"] is False and snap["cameras_paused"] is False)
# telemetry staleness: an arm that reported once then went silent is treated offline; one that
# NEVER reported stays advisory-online (a teleop predating the status back-channel keeps working).
stl = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0)
stl.set_arm_status("arm1", True, None, t)
stl.tick(t + 10) # 10s > status_timeout_s -> offline
check("stale telemetry flips the arm offline", stl.arm_online["arm1"] is False
and stl.arm_fault["arm1"] == "no telemetry")
never = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0)
never.tick(t + 100)
check("no telemetry EVER -> arm stays advisory-online", never.arm_online["arm1"] is True)
# admin pause: robots pause parks + holds the active driver + blocks assignment; resume reassigns
pz = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0)
pz.join("a", "A", t)
pz.set_paused("robots", True); pz.tick(t)
check("robots pause parks + holds the driver + blocks assignment",
pz.arm_of("a") is None and pz.robots_paused and any(s.identity == "a" for s in pz.queue))
pz.set_paused("robots", False); pz.tick(t)
check("robots resume reassigns the held driver", pz.arm_of("a") == "arm1")
# pause_after_session: queued while somebody's driving, fires on session end (idle here),
# nobody driving -> collapses to an immediate pause, and pause/resume clear a queued pending.
pa = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=5.0)
pa.join("a", "A", t); pa.join("b", "B", t) # a driving arm1, b queued
pa.arm_pause_after_session("robots"); pa.tick(t)
check("pause_after_session with an active driver just arms pending (no immediate pause)",
pa.robots_pause_pending and not pa.robots_paused and pa.arm_of("a") == "arm1")
pa.tick(t + 10) # a idle -> released; pending fires before b can be assigned
check("pending fires on session end, before the next driver gets the arm",
pa.robots_paused and not pa.robots_pause_pending and pa.arm_of("b") is None
and any(s.identity == "b" for s in pa.queue))
snap_pa = pa.snapshot(t + 10)
check("snapshot carries robots_pause_pending",
snap_pa.get("robots_pause_pending") is False and snap_pa.get("robots_paused") is True)
pa2 = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0)
pa2.arm_pause_after_session("robots")
check("pause_after_session with nobody driving pauses immediately",
pa2.robots_paused and not pa2.robots_pause_pending)
pa3 = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0)
pa3.join("a", "A", t)
pa3.arm_pause_after_session("robots")
check("arming pending is armed while a driver holds the arm", pa3.robots_pause_pending)
pa3.set_paused("robots", False)
check("resume clears a queued pending",
not pa3.robots_pause_pending and not pa3.robots_paused)
pa3.arm_pause_after_session("robots")
pa3.set_paused("robots", True); pa3.tick(t)
check("immediate pause supersedes + clears a queued pending",
pa3.robots_paused and not pa3.robots_pause_pending)
pa4 = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0)
pa4.set_paused("robots", True)
pa4.arm_pause_after_session("robots")
check("pause_after_session is a no-op when already paused",
pa4.robots_paused and not pa4.robots_pause_pending)
pa5 = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0)
pa5.arm_pause_after_session("cameras")
check("pause_after_session is robots-only (cameras ignored)",
not pa5.robots_paused and not pa5.robots_pause_pending and not pa5.cameras_paused)
# status datagram round-trips through the bridge's parser; malformed / wrong-type is rejected
sd = parse_status(build_status_datagram("arm2", False, "overload"))
check("status datagram round-trips", sd == {"arm": "arm2", "online": False, "fault": "overload"})
check("status rejects malformed / wrong type",
parse_status(b"nope") is None and parse_status(b'{"type":"intent"}') is None)
fx = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0)
fx.set_arm_status("arm1", True, "stale-fault", t) # a stray fault on an online report is cleared
check("online report clears any stale fault", fx.arm_fault["arm1"] is None)
# --- persistence: to_state / load_state round-trip preserves the queue, driver, camera + cycle ---
src = SessionManager(["arm1", "arm2"], max_session_s=100.0, idle_timeout_s=30.0)
src.join("a", "A", t); src.join("b", "B", t); src.join("c", "C", t) # a driving arm1, b/c queued
src.set_camera("a", "wrist_1", t)
st_dict = src.to_state(t)
dst = SessionManager(["arm1", "arm2"], max_session_s=100.0, idle_timeout_s=30.0)
dst.load_state(json.loads(json.dumps(st_dict)), t + 5) # through JSON, on a fresh clock
check("restore keeps the active driver + arm", dst.arm_of("a") == "arm1")
check("restore keeps the queue order", [s.identity for s in dst.queue] == ["b", "c"])
check("restore keeps the pinned camera", dst.primary_camera == "wrist_1")
rem = dst.snapshot(t + 5)["arms"]["arm1"]["remaining_s"]
check("restore rebuilds max-session remaining on the new clock", rem is not None and 95.0 <= rem <= 100.0)
# arms not in the current config are dropped on restore; last_arm only kept if still valid
solo_dst = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0)
solo_dst.load_state({"slots": {"arm1": {"identity": "a", "name": "A"}, "arm2": {"identity": "z"}},
"queue": [{"identity": "b"}], "last_arm": "arm2"}, t)
check("restore ignores arms not in config + invalid last_arm",
solo_dst.arm_of("a") == "arm1" and solo_dst.arm_of("z") is None and solo_dst.last_arm is None)
# hold_all marks every restored operator pending, so the sweep can resume the present / drop the gone
h = SessionManager(["arm1"], max_session_s=None, idle_timeout_s=0.0, disconnect_grace_s=15.0)
h.load_state(st_dict, t)
h.hold_all(t, 45.0)
check("hold_all marks driver + queue pending", {"a", "b", "c"} <= set(h.pending))
h.sweep_grace(t + 1, connected={"a", "b"}) # a,b present; c gone but grace not yet up
check("present restored operators resume", "a" not in h.pending and "b" not in h.pending)
h.sweep_grace(t + 60, connected={"a", "b"}) # c's grace expired
check("no-show restored operator dropped after grace",
not any(s.identity == "c" for s in h.queue) and any(s.identity == "b" for s in h.queue))
# --- --prod credential gate: reject dev defaults, overlay real creds from LIVEKIT_* env ---
def _mkargs(**kw):
base = dict(url=_DEV_URL, api_key=_DEV_KEY, api_secret=_DEV_SECRET, room="tom-cams")
base.update(kw)
return argparse.Namespace(**base)
_keys = ("LIVEKIT_URL", "LIVEKIT_API_KEY", "LIVEKIT_API_SECRET", "LIVEKIT_ROOM")
_saved = {k: os.environ.pop(k, None) for k in _keys}
try:
rejected = False
try:
_apply_prod(_mkargs()) # dev defaults + no env -> reject
except SystemExit:
rejected = True
check("--prod rejects the dev-mode defaults", rejected)
os.environ.update(LIVEKIT_URL="wss://x.livekit.cloud", LIVEKIT_API_KEY="realkey",
LIVEKIT_API_SECRET="realsecret", LIVEKIT_ROOM="armcade-prod")
a = _mkargs()
_apply_prod(a) # real env -> ok, overlays onto args
check("--prod overlays real creds from env",
a.url == "wss://x.livekit.cloud" and a.api_key == "realkey"
and a.api_secret == "realsecret" and a.room == "armcade-prod")
finally:
for k in _keys:
os.environ.pop(k, None)
if _saved[k] is not None:
os.environ[k] = _saved[k]
print("SELFTEST:", "PASS" if ok else "FAIL")
return 0 if ok else 1
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--url", default="ws://localhost:7880", help="LiveKit server ws URL")
p.add_argument("--api-key", default="devkey", help="LiveKit API key (dev mode: devkey)")
p.add_argument("--api-secret", default="secret", help="LiveKit API secret (dev mode: secret)")
p.add_argument("--room", default="tom-cams", help="Room to join (same as the camera publisher)")
p.add_argument("--identity", default="pi-control", help="This bridge's participant identity")
p.add_argument("--prod", action="store_true",
help="Production mode: take LiveKit url/key/secret/room from env (LIVEKIT_URL, "
"LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_ROOM), REFUSE the dev-mode defaults "
"(devkey / secret / ws://localhost), and warn on an insecure ws:// URL. Keeps real "
"secrets out of the CLI / process list.")
p.add_argument("--arms", nargs="+", default=["arm1", "arm2"], metavar="ARM",
help="Arm ids that can run a session (1 or 2, e.g. --arms arm1 arm2). Default: arm1 arm2.")
p.add_argument("--operator", action="append", metavar="IDENTITY",
help="Optional allow-list: only these identities may join. Omit for OPEN access.")
p.add_argument("--max-session-s", type=float, default=180.0,
help="Max seconds per session before auto-release (0 = unlimited). Default 180 (3 min).")
p.add_argument("--idle-timeout-s", type=float, default=30.0,
help="Release a session after this long with no driving (0 disables). Default 30.")
p.add_argument("--initial-idle-timeout-s", type=float, default=20.0,
help="Release a driver who NEVER sends an input this many seconds after taking control "
"(AFK-at-home guard; stricter than --idle-timeout-s, which tolerates a mid-drive "
"pause). 0 disables. Default 20.")
p.add_argument("--disconnect-grace-s", type=float, default=15.0,
help="Hold a disconnected operator's slot/queue spot this long so a refresh/reconnect "
"(same identity) resumes it. 0 = release immediately. Default 15.")
p.add_argument("--state-file", default="assets/queue_state.json",
help="Persist the queue + active session here so a bridge restart resumes it (empty "
"string disables). Default assets/queue_state.json (relative to the robot/ dir).")
p.add_argument("--driver-log", default="assets/driver_log.jsonl",
help="Append a durable JSONL record of every session start/end (who drove which arm, "
"when, how long, why it ended) here — an audit trail beyond the journald logs. "
"Empty string disables. Default assets/driver_log.jsonl (relative to robot/).")
p.add_argument("--restore-grace-s", type=float, default=45.0,
help="After a restart, hold restored operators this long to reconnect before dropping "
"them (a full server restart takes clients longer than a refresh). Default 45.")
p.add_argument("--remote-host", default="127.0.0.1", help="teleop --remote-port host (keep loopback)")
p.add_argument("--remote-port", type=int, default=9090, help="teleop --remote-port UDP port")
p.add_argument("--status-host", default="127.0.0.1", help="bind addr for the teleop arm-status listener")
p.add_argument("--status-port", type=int, default=9091,
help="UDP port to receive teleop arm-liveness reports (0 = disabled; arms stay advisory-online)")
p.add_argument("--rate", type=float, default=30.0, help="UDP relay rate to the teleop (Hz)")
p.add_argument("--operator-timeout", type=float, default=0.5,
help="Treat the driver as silent (relay a held frame) after this long with no frame.")
p.add_argument("--selftest", action="store_true", help="Run offline logic tests and exit.")
return p.parse_args()
_DEV_URL, _DEV_KEY, _DEV_SECRET = "ws://localhost:7880", "devkey", "secret"
def _apply_prod(args: argparse.Namespace) -> None:
"""--prod: overlay LiveKit creds from the LIVEKIT_* env vars (so real secrets never sit on the CLI /
in the process list), then refuse to start on the dev-mode defaults. Warns on an insecure ws:// URL."""
for attr, env in (("url", "LIVEKIT_URL"), ("api_key", "LIVEKIT_API_KEY"),
("api_secret", "LIVEKIT_API_SECRET"), ("room", "LIVEKIT_ROOM")):
val = os.environ.get(env)
if val:
setattr(args, attr, val)
stale = []
if not args.url or args.url == _DEV_URL:
stale.append("LIVEKIT_URL")
if not args.api_key or args.api_key == _DEV_KEY:
stale.append("LIVEKIT_API_KEY")
if not args.api_secret or args.api_secret == _DEV_SECRET:
stale.append("LIVEKIT_API_SECRET")
if stale:
raise SystemExit("--prod refuses the dev-mode defaults; set real credentials via env or CLI. "
"Missing / still dev: " + ", ".join(stale))
if args.url.startswith("ws://"):
logger.warning("--prod but LIVEKIT_URL is insecure ws:// (%s) — a public deploy should use wss://",
args.url)
def main() -> None:
args = parse_args()
if args.selftest:
raise SystemExit(_selftest())
if args.prod:
_apply_prod(args)
if not 1 <= len(args.arms) <= 2:
raise SystemExit(f"--arms takes 1 or 2 arm ids, got {args.arms}")
import asyncio
asyncio.run(run_bridge(args))
if __name__ == "__main__":
main()