Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
workbenchthis machine
The machine, not a magic box: a Machine panel shows the raw arm state and every command in and out, live #71
Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.
vesper/arm:vesper/67-the-machine-not-a-magic-box-a-machine-pa → main 3 commits fork
18 files
changed +1179
−25
Software/README.md +43 −1
| @@ -135,7 +135,11 @@ The API, all JSON (the full list with bodies is at the top of | ||
| 135 | 135 | `/recording/delete`, `/play`; |
| 136 | 136 | `PUT /calibration/camera|handeye`; the WebSocket `/follow` taking |
| 137 | 137 | `{"1": ticks, ...}` frames; and the read-only WebSocket `/watch`, which sends |
| 138 | the `/status` body every 250 ms, one bus read shared by every watcher. One thing drives the arm at a time. Every move | |
| 138 | the `/status` body every 250 ms, one bus read shared by every watcher, and | |
| 139 | between them the machine log: every register written on the bus, every change | |
| 140 | of driver, hold and E-stop, and every safety clamp, as it happens. Each joint | |
| 141 | in `/status` also carries its last goal (`target`), its calibrated range | |
| 142 | (`min`, `max`) and the bounds commands are held inside (`lo`, `hi`). One thing drives the arm at a time. Every move | |
| 139 | 143 | goes through the joint supervisor; `/stop` ends a move, a playback, a |
| 140 | 144 | recording, or a stream, and the arm holds. The stream is clamped to the |
| 141 | 145 | joint limits, eases over to the first frame, drops jumps no hand makes, is |
| @@ -266,6 +270,39 @@ real arm when the link dropped comes back as an error; it is not replayed. Chang | ||
| 266 | 270 | stream) are only accepted from the app's own page, so another site can't |
| 267 | 271 | drive the arm through it. |
| 268 | 272 | |
| 273 | **The Machine tab: the arm, not a magic box.** Anyone watching can open the | |
| 274 | **Machine** tab (a column beside the view on a wide screen). It shows, pushed | |
| 275 | as it happens with nothing polled: | |
| 276 | ||
| 277 | - each joint as its servo reports it: position in ticks and degrees, the last | |
| 278 | goal the server wrote, load, temperature, torque on or off, the calibrated | |
| 279 | range and the bounds every command is held inside; | |
| 280 | - the link: which arm, the round trip to the Pi (a WebSocket ping each | |
| 281 | second), status frames per second, and reconnects; | |
| 282 | - the server: whose turn it is, what drives the arm, whether the dead-man | |
| 283 | hold is in force, the E-stop, the zone, jams, the speed cap; | |
| 284 | - a log of every command in and out: `→` sent (each stream frame the app | |
| 285 | passed on, each request, and each register the Pi wrote on the bus), `←` | |
| 286 | received (each answer, and each status that changed), `⚠` every clamp the | |
| 287 | moment it is applied (a joint limit, the zone, a jump too far, a jam, the | |
| 288 | speed cap, a frame not passed on), `•` state changes. Each line has its | |
| 289 | number and its age. **Pause** freezes the view while the log keeps | |
| 290 | collecting; **Copy** puts the last 500 lines on the clipboard, one | |
| 291 | tab-separated line each with the time in UTC. | |
| 292 | ||
| 293 | The page reads it from the app's WebSocket `/machine` (`src/machine-feed.ts`), | |
| 294 | open only while the tab is; the app gets it from the Pi's `/watch`. It is | |
| 295 | read-only for everyone: nothing in it can move the arm. Opened on a bare | |
| 296 | `so101 serve`, the tab reads `/watch` directly. | |
| 297 | The terminal shows the same panel with `/machine` (see **The terminal door** | |
| 298 | below). | |
| 299 | ||
| 300 | Names appear in the feed in two places: whose turn it is, and the `by` on each | |
| 301 | logged request (the name of whoever sent it). Both are already public to | |
| 302 | anyone watching: the lobby shows every viewer, guests included, who drives, | |
| 303 | who waits and who said what. The feed adds no name the room does not | |
| 304 | already show. | |
| 305 | ||
| 269 | 306 | **Drive with your own leader arm.** Plug an SO-101 leader (its |
| 270 | 307 | bus board on USB, and on its own power supply) into the computer or Android |
| 271 | 308 | phone you are watching from, and press **Connect leader arm**, then pick the |
| @@ -384,6 +421,11 @@ watches. A line you type is said in the chat; commands start with `/`: | ||
| 384 | 421 | - `/end [name]`, owner: end that turn (no name: whoever drives), or take |
| 385 | 422 | them out of the line. |
| 386 | 423 | - `/mute <name>`, `/unmute <name>`, owner. |
| 424 | - `/machine`: the Machine panel, the same rows the page's Machine tab shows | |
| 425 | (one line per joint, then the link and the server), followed by every | |
| 426 | command in and out and every clamp, line by line as it happens. `/machine` | |
| 427 | again prints the joints again; `/machine off` stops the stream. Anyone may, | |
| 428 | guests too: it is read-only. | |
| 387 | 429 | - `/who` (who drives, who waits), `/help`, `/quit`. |
| 388 | 430 | |
| 389 | 431 | The terminal is a client of the running server, like the page: it opens |
Software/so101/src/arm-link.test.ts +1 −1
| @@ -5,7 +5,7 @@ import { ArmLink, parseStatus, type LinkState, type LinkTimings } from "./arm-li | ||
| 5 | 5 | |
| 6 | 6 | const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); |
| 7 | 7 | /** The issue's timings at 1/100: retries after 5, 10, 20, 40 ms, offline after 600 ms (60 s), 10 s down is 100 ms. */ |
| 8 | const FAST: LinkTimings = { backoffMs: [5, 10, 20, 40], staleMs: 60, offlineAfterMs: 600, connectTimeoutMs: 50, pollEveryMs: 10 }; | |
| 8 | const FAST: LinkTimings = { backoffMs: [5, 10, 20, 40], staleMs: 60, offlineAfterMs: 600, connectTimeoutMs: 50, pollEveryMs: 10, pingEveryMs: 20 }; | |
| 9 | 9 | const status = (n: number) => ({ joints: [{ id: 1, position: n }], driving: null }); |
| 10 | 10 | |
| 11 | 11 | /** |
Software/so101/src/arm-link.ts +74 −3
| @@ -10,10 +10,15 @@ | ||
| 10 | 10 | * This is where a link starts, until the first status comes in. |
| 11 | 11 | * offline still gone `offlineAfterMs` after it went (60 s); the relay may fall back to the simulation now, |
| 12 | 12 | * and says so. The retries go on, and the first status that comes in makes it live again. |
| 13 | * | |
| 14 | * It measures itself for the Machine panel (`stats`): the round trip to the arm server (a WebSocket ping every | |
| 15 | * `pingEveryMs`, or the GET when polling), the status frames per second, and how often it came back after a drop. | |
| 16 | * The arm server's machine log (src/machine-log.ts) arrives on the same watch and is handed on, checked, to `onMachine`. | |
| 13 | 17 | */ |
| 14 | 18 | |
| 15 | 19 | import type WebSocket from "ws"; |
| 16 | 20 | import { whyNot } from "./egress.ts"; |
| 21 | import { parseEntries, type MachineEntry } from "./machine-log.ts"; | |
| 17 | 22 | |
| 18 | 23 | export type LinkState = "live" | "reconnecting" | "offline"; |
| 19 | 24 | |
| @@ -28,9 +33,21 @@ export interface LinkTimings { | ||
| 28 | 33 | connectTimeoutMs: number; |
| 29 | 34 | /** How often an arm server without /watch is asked for its status. */ |
| 30 | 35 | pollEveryMs: number; |
| 36 | /** How often the watch is pinged, to time the round trip. */ | |
| 37 | pingEveryMs: number; | |
| 31 | 38 | } |
| 32 | 39 | |
| 33 | export const DEFAULT_TIMINGS: LinkTimings = { backoffMs: [500, 1000, 2000, 4000], staleMs: 2000, offlineAfterMs: 60_000, connectTimeoutMs: 1500, pollEveryMs: 250 }; | |
| 40 | export const DEFAULT_TIMINGS: LinkTimings = { backoffMs: [500, 1000, 2000, 4000], staleMs: 2000, offlineAfterMs: 60_000, connectTimeoutMs: 1500, pollEveryMs: 250, pingEveryMs: 1000 }; | |
| 41 | ||
| 42 | /** How the link is doing, measured: null until there is a measurement. */ | |
| 43 | export interface LinkStats { | |
| 44 | /** The last round trip to the arm server, ms. */ | |
| 45 | rttMs: number | null; | |
| 46 | /** Status frames per second over the last two seconds. */ | |
| 47 | fps: number; | |
| 48 | /** Times the link came back after a drop. */ | |
| 49 | reconnects: number; | |
| 50 | } | |
| 34 | 51 | |
| 35 | 52 | export interface ArmLinkOptions { |
| 36 | 53 | /** The arm server's HTTP and WebSocket bases, and its host:port for messages. */ |
| @@ -40,6 +57,10 @@ export interface ArmLinkOptions { | ||
| 40 | 57 | timings?: Partial<LinkTimings>; |
| 41 | 58 | /** Called on every change of state, after it is made. */ |
| 42 | 59 | onChange?: (state: LinkState, previous: LinkState) => void; |
| 60 | /** Called with every status that comes in. */ | |
| 61 | onStatus?: (status: Status) => void; | |
| 62 | /** Called with the arm server's machine log as it comes in: entries checked, and the id of the server's run. */ | |
| 63 | onMachine?: (entries: MachineEntry[], run: string) => void; | |
| 43 | 64 | } |
| 44 | 65 | |
| 45 | 66 | export type Status = Record<string, unknown>; |
| @@ -59,6 +80,20 @@ export function parseStatus(text: string): Status | null { | ||
| 59 | 80 | } |
| 60 | 81 | } |
| 61 | 82 | |
| 83 | /** A machine log frame from /watch: {"machine": [...], "run": "…"}; null for anything else. */ | |
| 84 | export function parseMachine(text: string): { entries: MachineEntry[]; run: string } | null { | |
| 85 | try { | |
| 86 | const body = JSON.parse(text) as { machine?: unknown; run?: unknown } | null; | |
| 87 | if (!body || typeof body !== "object" || !Array.isArray(body.machine)) return null; | |
| 88 | const run = typeof body.run === "string" ? body.run.slice(0, 64) : ""; | |
| 89 | return { entries: parseEntries(body.machine), run }; | |
| 90 | } catch { | |
| 91 | return null; | |
| 92 | } | |
| 93 | } | |
| 94 | ||
| 95 | const FPS_WINDOW_MS = 2000; | |
| 96 | ||
| 62 | 97 | export class ArmLink { |
| 63 | 98 | state: LinkState = "reconnecting"; |
| 64 | 99 | /** Why the link is not live; null while it is. */ |
| @@ -69,6 +104,11 @@ export class ArmLink { | ||
| 69 | 104 | lastAt = 0; |
| 70 | 105 | downSince = Date.now(); |
| 71 | 106 | readonly ready: Promise<void>; |
| 107 | private rttMs: number | null = null; | |
| 108 | private reconnects = 0; | |
| 109 | private everLive = false; | |
| 110 | private readonly arrivals: number[] = []; | |
| 111 | private pinger: ReturnType<typeof setInterval> | undefined; | |
| 72 | 112 | private readonly t: LinkTimings; |
| 73 | 113 | private attempt = 0; |
| 74 | 114 | private polling = false; |
| @@ -94,6 +134,7 @@ export class ArmLink { | ||
| 94 | 134 | clearTimeout(this.retry); |
| 95 | 135 | clearTimeout(this.stale); |
| 96 | 136 | clearTimeout(this.offline); |
| 137 | clearInterval(this.pinger); | |
| 97 | 138 | this.ws?.terminate(); |
| 98 | 139 | this.ws = null; |
| 99 | 140 | this.settle(); |
| @@ -117,9 +158,24 @@ export class ArmLink { | ||
| 117 | 158 | this.stale = setTimeout(() => ((why = `no status in ${this.t.staleMs} ms`), ws.terminate()), this.t.staleMs); |
| 118 | 159 | }; |
| 119 | 160 | wait(); |
| 161 | let pingedAt = 0; | |
| 162 | clearInterval(this.pinger); | |
| 163 | this.pinger = setInterval(() => { | |
| 164 | if (ws.readyState !== ws.OPEN) return; | |
| 165 | pingedAt = performance.now(); | |
| 166 | ws.ping(); | |
| 167 | }, this.t.pingEveryMs); | |
| 168 | ws.on("pong", () => { | |
| 169 | if (pingedAt) this.rttMs = Math.round((performance.now() - pingedAt) * 10) / 10; | |
| 170 | }); | |
| 120 | 171 | ws.on("message", (data) => { |
| 121 | const body = parseStatus(String(data)); | |
| 122 | if (!body) return; | |
| 172 | const text = String(data); | |
| 173 | const body = parseStatus(text); | |
| 174 | if (!body) { | |
| 175 | const machine = this.o.onMachine && parseMachine(text); | |
| 176 | if (machine) this.o.onMachine!(machine.entries, machine.run); | |
| 177 | return; | |
| 178 | } | |
| 123 | 179 | wait(); |
| 124 | 180 | this.seen(body); |
| 125 | 181 | }); |
| @@ -128,13 +184,16 @@ export class ArmLink { | ||
| 128 | 184 | if (this.ws !== ws) return; |
| 129 | 185 | this.ws = null; |
| 130 | 186 | clearTimeout(this.stale); |
| 187 | clearInterval(this.pinger); | |
| 131 | 188 | this.lost(why); |
| 132 | 189 | }); |
| 133 | 190 | } |
| 134 | 191 | |
| 135 | 192 | private async poll() { |
| 136 | 193 | try { |
| 194 | const asked = performance.now(); | |
| 137 | 195 | const r = await fetch(`${this.o.remote.http}/status`, { signal: AbortSignal.timeout(this.t.connectTimeoutMs), cache: "no-store" }); |
| 196 | this.rttMs = Math.round((performance.now() - asked) * 10) / 10; | |
| 138 | 197 | if (!r.ok) throw new Error(await whyNot(r, "/status")); |
| 139 | 198 | const body = parseStatus(await r.text()); |
| 140 | 199 | if (!body) throw new Error("/status did not answer an arm's status"); |
| @@ -156,14 +215,26 @@ export class ArmLink { | ||
| 156 | 215 | if (!this.closed) this.retry = setTimeout(() => void this.connect(), ms); |
| 157 | 216 | } |
| 158 | 217 | |
| 218 | /** The link's measurements, for the Machine panel. */ | |
| 219 | stats(): LinkStats { | |
| 220 | const since = Date.now() - FPS_WINDOW_MS; | |
| 221 | while (this.arrivals.length && this.arrivals[0]! < since) this.arrivals.shift(); | |
| 222 | return { rttMs: this.rttMs, fps: Math.round((this.arrivals.length / (FPS_WINDOW_MS / 1000)) * 10) / 10, reconnects: this.reconnects }; | |
| 223 | } | |
| 224 | ||
| 159 | 225 | private seen(body: Status) { |
| 160 | 226 | this.last = body; |
| 161 | 227 | this.lastAt = Date.now(); |
| 228 | this.arrivals.push(this.lastAt); | |
| 229 | if (this.arrivals.length > 600) this.arrivals.shift(); | |
| 230 | if (this.state !== "live" && this.everLive) this.reconnects++; | |
| 231 | this.everLive = true; | |
| 162 | 232 | this.attempt = 0; |
| 163 | 233 | clearTimeout(this.offline); |
| 164 | 234 | this.problem = null; |
| 165 | 235 | this.change("live"); |
| 166 | 236 | this.settle(); |
| 237 | this.o.onStatus?.(body); | |
| 167 | 238 | } |
| 168 | 239 | |
| 169 | 240 | private lost(why: string) { |
Software/so101/src/bus.ts +5 −1
| @@ -81,6 +81,8 @@ export class FeetechBus { | ||
| 81 | 81 | : boolean; |
| 82 | 82 | = false; |
| 83 | 83 | : Error | null = null; |
| 84 | /** Told of every sync write before it goes on the wire: what the arm server shows as "sent" (src/machine-log.ts). */ | |
| 85 | onSyncWrite: ((register: Register, values: ReadonlyArray<readonly [number, number]>) => void) | null = null; | |
| 84 | 86 | |
| 85 | 87 | constructor(transport: Transport, { echo = false }: BusOptions = {}) { |
| 86 | 88 | this. = transport; |
| @@ -191,8 +193,10 @@ export class FeetechBus { | ||
| 191 | 193 | |
| 192 | 194 | /** Write the same register on many servos in one bus transaction. No status comes back. */ |
| 193 | 195 | async syncWrite(register: Register, values: Iterable<readonly [number, number]>): Promise<void> { |
| 196 | const list = [...values]; | |
| 197 | this.onSyncWrite?.(register, list); | |
| 194 | 198 | const params = [register.address, register.size]; |
| 195 | for (const [id, value] of values) params.push(id, ...encodeValue(register, value)); | |
| 199 | for (const [id, value] of list) params.push(id, ...encodeValue(register, value)); | |
| 196 | 200 | await this.(encodeInstruction(BROADCAST_ID, Instruction.SyncWrite, params), [], 0); |
| 197 | 201 | } |
| 198 | 202 |
Software/so101/src/machine-feed.test.ts added +130
| @@ -0,0 +1,130 @@ | ||
| 1 | import { afterEach, expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import WebSocket from "ws"; | |
| 6 | import { FeetechBus } from "./bus.ts"; | |
| 7 | import { FakeBus } from "./fake-bus.ts"; | |
| 8 | import type { MachineEntry } from "./machine-log.ts"; | |
| 9 | import { parseRemote, startRelay, type RunningRelay } from "./relay.ts"; | |
| 10 | import { startServer, type RunningServer } from "./server.ts"; | |
| 11 | import { entryLine, jointRows, linkRows, stateRows } from "./ui/machine.js"; | |
| 12 | ||
| 13 | const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); | |
| 14 | const shut = (s: { close(): Promise<void> } | undefined) => (s ? Promise.race([s.close(), sleep(500)]) : undefined); | |
| 15 | const FAST = { backoffMs: [5, 10, 20, 40], staleMs: 200, offlineAfterMs: 600, connectTimeoutMs: 100, pollEveryMs: 10, pingEveryMs: 20 }; | |
| 16 | const le = (n: number) => [n & 0xff, n >> 8]; | |
| 17 | ||
| 18 | /** An arm server on a fake bus whose servo 2 reads exactly what is written in its memory here. */ | |
| 19 | async function fakePi(ids: number[]) { | |
| 20 | const fake = new FakeBus(ids); | |
| 21 | for (const id of ids) fake.servos.get(id)!.set([...le(818), ...le(3487)], 9); // Min_Position_Limit, Max_Position_Limit | |
| 22 | const two = fake.servos.get(2)!; | |
| 23 | two.set(le(1234), 56); // Present_Position | |
| 24 | two.set([123, 1 << 2], 60); // Present_Load: 123 with the sign bit (10) set, -12.3 % | |
| 25 | two[63] = 41; // Present_Temperature | |
| 26 | two[40] = 1; // Torque_Enable | |
| 27 | const server = await startServer(new FeetechBus(fake), { host: "127.0.0.1", port: 0, ids, posesFile: join(mkdtempSync(join(tmpdir(), "so101-machine-")), "poses.json"), watchEveryMs: 10 }); | |
| 28 | return server; | |
| 29 | } | |
| 30 | ||
| 31 | type Message = { type: string; status?: Record<string, unknown>; link?: Record<string, unknown>; room?: Record<string, unknown>; log?: MachineEntry[]; entries?: MachineEntry[] }; | |
| 32 | /** A Machine panel's socket, keeping every message and every log entry. */ | |
| 33 | async function panel(port: number) { | |
| 34 | const ws = new WebSocket(`ws://127.0.0.1:${port}/machine`); | |
| 35 | const messages: Message[] = []; | |
| 36 | const log: MachineEntry[] = []; | |
| 37 | ws.on("message", (data) => { | |
| 38 | const m = JSON.parse(String(data)) as Message; | |
| 39 | messages.push(m); | |
| 40 | log.push(...(m.log ?? m.entries ?? [])); | |
| 41 | }); | |
| 42 | await new Promise((r, j) => (ws.once("open", r), ws.once("error", j))); | |
| 43 | const until = async <T>(find: () => T | undefined, what: string, ms = 2000): Promise<T> => { | |
| 44 | const end = Date.now() + ms; | |
| 45 | for (;;) { | |
| 46 | const found = find(); | |
| 47 | if (found !== undefined) return found; | |
| 48 | if (Date.now() > end) throw new Error(`no ${what} in ${ms} ms`); | |
| 49 | await sleep(5); | |
| 50 | } | |
| 51 | }; | |
| 52 | return { ws, messages, log, until }; | |
| 53 | } | |
| 54 | ||
| 55 | let pi: RunningServer | undefined; | |
| 56 | let sim: RunningServer | undefined; | |
| 57 | let relay: RunningRelay | undefined; | |
| 58 | afterEach(async () => { | |
| 59 | await shut(relay); | |
| 60 | await shut(pi); | |
| 61 | await shut(sim); | |
| 62 | relay = pi = sim = undefined; | |
| 63 | }); | |
| 64 | ||
| 65 | async function rig() { | |
| 66 | pi = await fakePi([1, 2, 6]); | |
| 67 | sim = await startServer(new FeetechBus(new FakeBus([1, 2, 3, 4, 5, 6])), { host: "127.0.0.1", port: 0, posesFile: join(mkdtempSync(join(tmpdir(), "so101-machine-")), "poses.json"), watchEveryMs: 10 }); | |
| 68 | relay = await startRelay({ port: 0, simulation: `http://127.0.0.1:${sim.port}`, remote: parseRemote({ ARM_SERVER: `ws://127.0.0.1:${pi.port}` }), link: FAST }); | |
| 69 | return relay; | |
| 70 | } | |
| 71 | ||
| 72 | test("the panel shows a fake Pi's raw values exactly, pushed, with the link measured", async () => { | |
| 73 | const { port } = await rig(); | |
| 74 | const p = await panel(port); | |
| 75 | const status = await p.until(() => p.messages.find((m) => m.type === "status" && m.link?.rttMs !== null), "status with a round trip"); | |
| 76 | const two = jointRows(status.status as never).find((r) => r.id === "2")!; | |
| 77 | expect(two).toEqual({ id: "2", name: "shoulder_lift", ticks: "1234", degrees: "108.5°", target: "—", load: "-12.3%", temperature: "41 °C", torque: "on", limits: "818–3487", bounds: "848–3457" }); | |
| 78 | const link = Object.fromEntries(linkRows(status.link as never)); | |
| 79 | expect(link.arm).toBe(`live · 127.0.0.1:${pi!.port}`); | |
| 80 | expect(link["round trip"]).toMatch(/^\d+(\.\d)? ms$/); | |
| 81 | expect(link.reconnects).toBe("0"); | |
| 82 | const state = Object.fromEntries(stateRows(status.status as never, status.room as never)); | |
| 83 | expect(state).toMatchObject({ turn: "nobody", driving: "nothing (idle)", held: "no", "E-stop": "off" }); | |
| 84 | // The status messages come as the arm server pushes them, several a second, with nobody asking. | |
| 85 | const before = p.messages.length; | |
| 86 | await sleep(200); | |
| 87 | expect(p.messages.length - before).toBeGreaterThan(3); | |
| 88 | expect(Number(Object.fromEntries(linkRows(p.messages.at(-1)!.link as never))["status frames"]!.replace("/s", ""))).toBeGreaterThan(5); | |
| 89 | p.ws.close(); | |
| 90 | }); | |
| 91 | ||
| 92 | test("a clamp shows up in the log the moment it is applied, with the command that went out instead", async () => { | |
| 93 | const { port } = await rig(); | |
| 94 | const p = await panel(port); | |
| 95 | const follow = new WebSocket(`ws://127.0.0.1:${port}/follow`); | |
| 96 | await new Promise((r, j) => (follow.once("open", r), follow.once("error", j))); | |
| 97 | follow.send(JSON.stringify({ 1: 9999 })); | |
| 98 | ||
| 99 | const sent = await p.until(() => p.log.find((e) => e.kind === "sent" && e.what === "follow frame"), "frame passed on"); | |
| 100 | expect(sent.detail.values).toEqual({ 1: 9999 }); | |
| 101 | const clamp = await p.until(() => p.log.find((e) => e.kind === "clamp" && e.what === "joint limit"), "clamp"); | |
| 102 | expect(clamp.detail).toMatchObject({ id: 1, asked: 9999, sent: 3457, source: "stream" }); | |
| 103 | expect(typeof clamp.detail.armSeq).toBe("number"); | |
| 104 | expect(entryLine(clamp, clamp.t).text).toBe("⚠ joint limit id=1 asked=9999 sent=3457 source=stream (arm #" + clamp.detail.armSeq + ")"); | |
| 105 | // What reached the servo is the bounded goal, never the 9999 asked for, and the panel's target says so. | |
| 106 | const goal = await p.until(() => p.log.find((e) => e.kind === "sent" && e.what === "Goal_Position" && (e.detail.values as Record<string, number>)["1"] === 3457), "the bounded goal on the bus"); | |
| 107 | expect(goal.seq).toBeGreaterThan(clamp.seq); | |
| 108 | expect(p.log.some((e) => e.what === "Goal_Position" && (e.detail.values as Record<string, number>)["1"] === 9999)).toBe(false); | |
| 109 | await p.until(() => p.messages.find((m) => m.type === "status" && jointRows(m.status as never)[0]?.target === "3457 (303.8°)"), "the target in the joints"); | |
| 110 | expect(p.log.find((e) => e.kind === "state" && e.what === "driver")?.detail).toEqual({ driving: "stream", armSeq: expect.any(Number) }); | |
| 111 | follow.close(); | |
| 112 | p.ws.close(); | |
| 113 | }); | |
| 114 | ||
| 115 | test("a panel that opens later gets the log so far; the simulation has a panel too", async () => { | |
| 116 | sim = await startServer(new FeetechBus(new FakeBus([1, 2, 3, 4, 5, 6])), { host: "127.0.0.1", port: 0, posesFile: join(mkdtempSync(join(tmpdir(), "so101-machine-")), "poses.json"), watchEveryMs: 10 }); | |
| 117 | relay = await startRelay({ port: 0, simulation: `http://127.0.0.1:${sim.port}`, link: FAST }); | |
| 118 | const first = await panel(relay.port); | |
| 119 | await first.until(() => first.messages.find((m) => m.type === "status"), "a status from the simulation"); | |
| 120 | const moved = await fetch(`http://127.0.0.1:${relay.port}/move`, { method: "POST", body: JSON.stringify({ targets: { 3: 5000 } }) }); | |
| 121 | expect(moved.status).toBe(200); | |
| 122 | await first.until(() => first.log.find((e) => e.kind === "received" && e.what === "POST /move" && e.detail.status === 200), "the answer"); | |
| 123 | await first.until(() => first.log.find((e) => e.kind === "clamp" && e.detail.asked === 5000), "the clamp"); | |
| 124 | const later = await panel(relay.port); | |
| 125 | const hello = await later.until(() => later.messages.find((m) => m.type === "hello"), "hello"); | |
| 126 | expect(hello.log!.some((e) => e.kind === "sent" && e.what === "POST /move")).toBe(true); | |
| 127 | expect(hello.log!.some((e) => e.kind === "clamp" && e.detail.asked === 5000)).toBe(true); | |
| 128 | first.ws.close(); | |
| 129 | later.ws.close(); | |
| 130 | }); |
Software/so101/src/machine-feed.ts added +147
| @@ -0,0 +1,147 @@ | ||
| 1 | /** | |
| 2 | * The Machine panel's feed, over one WebSocket (/machine): the arm as it is, raw, and every command in and out. | |
| 3 | * | |
| 4 | * The relay hands it each status the arm server pushes (src/arm-link.ts), the arm server's own machine log (every | |
| 5 | * register it wrote, every clamp it applied), and what the relay itself passed on or held back (stream frames, | |
| 6 | * requests, the speed cap). Nothing here asks the arm anything: it is pushed what comes in, and pushes it on. | |
| 7 | * | |
| 8 | * Server → client, one JSON object per message: | |
| 9 | * {"type": "hello", "now", "log": [entries], "status": {…}|null, "link": {…}, "room": {…}} on connecting | |
| 10 | * {"type": "status", "status": {…}, "link": {…}, "room": {…}} each status that comes in | |
| 11 | * {"type": "log", "entries": [entries]} new log entries, batched | |
| 12 | * Read-only: whatever a viewer sends is ignored. A viewer that cannot keep up misses status messages, never the log. | |
| 13 | */ | |
| 14 | ||
| 15 | import type { IncomingMessage } from "node:http"; | |
| 16 | import type { Duplex } from "node:stream"; | |
| 17 | import WebSocket, { WebSocketServer } from "ws"; | |
| 18 | import { MachineLog, perServo, type DetailValue, type EntryKind, type MachineEntry } from "./machine-log.ts"; | |
| 19 | ||
| 20 | export interface FeedLink { | |
| 21 | mode: string; | |
| 22 | host: string | null; | |
| 23 | problem: string | null; | |
| 24 | rttMs: number | null; | |
| 25 | fps: number; | |
| 26 | reconnects: number; | |
| 27 | } | |
| 28 | ||
| 29 | export interface Room { | |
| 30 | /** Whose turn it is, by name; null when nobody drives. */ | |
| 31 | driver: string | null; | |
| 32 | paused: boolean; | |
| 33 | speedCapPercent: number; | |
| 34 | } | |
| 35 | ||
| 36 | export interface MachineFeedOptions { | |
| 37 | link: () => FeedLink; | |
| 38 | room: () => Room; | |
| 39 | /** Told how many viewers there are whenever that changes. */ | |
| 40 | onViewers?: (count: number) => void; | |
| 41 | log?: MachineLog; | |
| 42 | } | |
| 43 | ||
| 44 | /** A viewer with this much unsent is too slow for another status; it still gets the log. */ | |
| 45 | const SLOW_BYTES = 1 << 20; | |
| 46 | const HELLO_ENTRIES = 300; | |
| 47 | ||
| 48 | type Status = Record<string, unknown>; | |
| 49 | interface Joint { | |
| 50 | id?: unknown; | |
| 51 | position?: unknown; | |
| 52 | torque?: unknown; | |
| 53 | target?: unknown; | |
| 54 | } | |
| 55 | ||
| 56 | /** What makes one status different from the last, for "received": where the joints are, their torque, who drives, the stop. */ | |
| 57 | function signature(status: Status): string { | |
| 58 | const joints = Array.isArray(status.joints) ? (status.joints as Joint[]) : []; | |
| 59 | return JSON.stringify([joints.map((j) => [j.id, j.position, j.torque]), status.driving, status.estop ? 1 : 0, status.held]); | |
| 60 | } | |
| 61 | ||
| 62 | function positions(status: Status): Record<string, number> { | |
| 63 | const joints = Array.isArray(status.joints) ? (status.joints as Joint[]) : []; | |
| 64 | return perServo(joints.flatMap((j) => (Number.isInteger(j.id) && typeof j.position === "number" ? [[j.id as number, j.position] as const] : []))); | |
| 65 | } | |
| 66 | ||
| 67 | export class MachineFeed { | |
| 68 | readonly log: MachineLog; | |
| 69 | : Status | null = null; | |
| 70 | = ""; | |
| 71 | : string | null | undefined = undefined; | |
| 72 | /** The arm server's run and the last of its entries kept, so a backlog sent again on reconnecting is not kept twice. */ | |
| 73 | = ""; | |
| 74 | = 0; | |
| 75 | readonly = new WebSocketServer({ noServer: true, maxPayload: 256 }); | |
| 76 | readonly : MachineFeedOptions; | |
| 77 | readonly : () => void; | |
| 78 | ||
| 79 | constructor(o: MachineFeedOptions) { | |
| 80 | this. = o; | |
| 81 | this.log = o.log ?? new MachineLog(); | |
| 82 | this. = this.log.subscribe((entries) => this.({ type: "log", entries }, false)); | |
| 83 | this..on("connection", (ws: WebSocket) => { | |
| 84 | ws.on("error", () => ws.terminate()); | |
| 85 | ws.on("close", () => this..onViewers?.(this..clients.size)); | |
| 86 | ws.send(JSON.stringify({ type: "hello", now: Date.now(), log: this.log.recent(HELLO_ENTRIES), status: this., link: o.link(), room: o.room() })); | |
| 87 | this..onViewers?.(this..clients.size); | |
| 88 | }); | |
| 89 | } | |
| 90 | ||
| 91 | get viewers(): number { | |
| 92 | return this..clients.size; | |
| 93 | } | |
| 94 | ||
| 95 | /** Something the relay did: a frame passed on, a request answered, a clamp of its own. */ | |
| 96 | note(kind: EntryKind, what: string, detail: Record<string, DetailValue> = {}): MachineEntry { | |
| 97 | return this.log.note(kind, what, detail); | |
| 98 | } | |
| 99 | ||
| 100 | /** A status came in from the arm being shown: kept, logged when it changed, pushed to every viewer. */ | |
| 101 | status(status: Status): void { | |
| 102 | this. = status; | |
| 103 | const room = this..room(); | |
| 104 | if (room.driver !== this.) { | |
| 105 | if (this. !== undefined) this.log.note("state", "turn", { driver: room.driver }); | |
| 106 | this. = room.driver; | |
| 107 | } | |
| 108 | const sig = signature(status); | |
| 109 | if (sig !== this.) { | |
| 110 | this. = sig; | |
| 111 | this.log.note("received", "status", { positions: positions(status), driving: typeof status.driving === "string" ? status.driving : null }); | |
| 112 | } | |
| 113 | if (this..clients.size) this.({ type: "status", status, link: this..link(), room }, true); | |
| 114 | } | |
| 115 | ||
| 116 | /** The arm server's own log; its numbering is kept as `armSeq`, and a new run starts it over. */ | |
| 117 | arm(entries: readonly MachineEntry[], run: string): void { | |
| 118 | if (run !== this.) { | |
| 119 | this. = run; | |
| 120 | this. = 0; | |
| 121 | } | |
| 122 | for (const e of entries) { | |
| 123 | if (e.seq <= this.) continue; | |
| 124 | this. = e.seq; | |
| 125 | this.log.note(e.kind, e.what, { ...e.detail, armSeq: e.seq }, e.t); | |
| 126 | } | |
| 127 | } | |
| 128 | ||
| 129 | upgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void { | |
| 130 | this..handleUpgrade(req, socket, head, (ws) => this..emit("connection", ws, req)); | |
| 131 | } | |
| 132 | ||
| 133 | close(): void { | |
| 134 | this.(); | |
| 135 | for (const ws of this..clients) ws.terminate(); | |
| 136 | this..close(); | |
| 137 | } | |
| 138 | ||
| 139 | (message: unknown, droppable: boolean) { | |
| 140 | if (!this..clients.size) return; | |
| 141 | const text = JSON.stringify(message); | |
| 142 | for (const ws of this..clients) { | |
| 143 | if (ws.readyState !== WebSocket.OPEN || (droppable && ws.bufferedAmount > SLOW_BYTES)) continue; | |
| 144 | ws.send(text); | |
| 145 | } | |
| 146 | } | |
| 147 | } |
Software/so101/src/machine-log.test.ts added +46
| @@ -0,0 +1,46 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { MachineLog, parseEntries, perServo } from "./machine-log.ts"; | |
| 3 | ||
| 4 | const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); | |
| 5 | ||
| 6 | describe("MachineLog", () => { | |
| 7 | test("numbers every entry and keeps the last `size`", () => { | |
| 8 | const log = new MachineLog({ size: 3 }); | |
| 9 | for (let i = 0; i < 5; i++) log.note("sent", "Goal_Position", { values: perServo([[1, 2000 + i]]) }); | |
| 10 | expect(log.seq).toBe(5); | |
| 11 | expect(log.recent().map((e) => e.seq)).toEqual([3, 4, 5]); | |
| 12 | expect(log.recent(1)[0]!.detail).toEqual({ values: { 1: 2004 } }); | |
| 13 | }); | |
| 14 | ||
| 15 | test("a burst of entries reaches a listener as one batch", async () => { | |
| 16 | const log = new MachineLog({ flushMs: 10 }); | |
| 17 | const batches: number[][] = []; | |
| 18 | const stop = log.subscribe((batch) => batches.push(batch.map((e) => e.seq))); | |
| 19 | for (let i = 0; i < 30; i++) log.note("sent", "Goal_Position"); | |
| 20 | await sleep(30); | |
| 21 | expect(batches).toEqual([Array.from({ length: 30 }, (_, i) => i + 1)]); | |
| 22 | stop(); | |
| 23 | log.note("clamp", "joint limit"); | |
| 24 | await sleep(30); | |
| 25 | expect(batches.length).toBe(1); | |
| 26 | }); | |
| 27 | }); | |
| 28 | ||
| 29 | describe("parseEntries", () => { | |
| 30 | test("keeps entries, drops what is not one, and cleans what it keeps", () => { | |
| 31 | const entries = parseEntries([ | |
| 32 | { seq: 1, t: 5, kind: "clamp", what: "joint\u0000 limit", detail: { id: 1, asked: 9999, values: { 1: 3457 }, bad: { x: 1 }, "no-key": 1, deep: [1] } }, | |
| 33 | { seq: 0, t: 5, kind: "sent", what: "x" }, | |
| 34 | { seq: 2, t: 5, kind: "exec", what: "x" }, | |
| 35 | { seq: 3, t: "now", kind: "sent", what: "x" }, | |
| 36 | "junk", | |
| 37 | null, | |
| 38 | { seq: 4, t: 6, kind: "state", what: "<b>driver</b>".repeat(20), detail: { by: "x".repeat(500) } }, | |
| 39 | ]); | |
| 40 | expect(entries.map((e) => e.seq)).toEqual([1, 4]); | |
| 41 | expect(entries[0]!).toEqual({ seq: 1, t: 5, kind: "clamp", what: "joint limit", detail: { id: 1, asked: 9999, values: { 1: 3457 } } }); | |
| 42 | expect(entries[1]!.what.length).toBe(80); // kept as text: the page puts it in with textContent | |
| 43 | expect((entries[1]!.detail.by as string).length).toBe(200); | |
| 44 | expect(parseEntries({ seq: 1 })).toEqual([]); | |
| 45 | }); | |
| 46 | }); |
Software/so101/src/machine-log.ts added +138
| @@ -0,0 +1,138 @@ | ||
| 1 | /** | |
| 2 | * What went to the machine and what came back, as it happened: the Machine panel's log. | |
| 3 | * | |
| 4 | * Every entry is plain data with a sequence number that only grows: | |
| 5 | * sent a command on its way: a register written on the bus (on the arm server), a frame or a request passed on (the relay) | |
| 6 | * received an answer: a status that changed, a request's reply | |
| 7 | * clamp a safety rule changed or refused a command, the moment it did: a joint limit, the zone, a jump too far, a jam, the speed cap | |
| 8 | * state who drives, a hold, an emergency stop, a park | |
| 9 | * The log keeps the last `size` entries; listeners get them in batches, at most one batch per `flushMs`, so a | |
| 10 | * command stream at 30 Hz is a handful of messages a second. Entries that come from another process are checked | |
| 11 | * with `parseEntries` before they are kept. | |
| 12 | */ | |
| 13 | ||
| 14 | export const KINDS = ["sent", "received", "clamp", "state"] as const; | |
| 15 | export type EntryKind = (typeof KINDS)[number]; | |
| 16 | /** A detail value: a number, a short text, a flag, or a flat map of numbers (servo id → ticks). */ | |
| 17 | export type DetailValue = number | string | boolean | null | Readonly<Record<string, number>>; | |
| 18 | ||
| 19 | export interface MachineEntry { | |
| 20 | readonly seq: number; | |
| 21 | /** When, ms since the epoch. */ | |
| 22 | readonly t: number; | |
| 23 | readonly kind: EntryKind; | |
| 24 | /** What it was: a register, a route, a rule. */ | |
| 25 | readonly what: string; | |
| 26 | readonly detail: Readonly<Record<string, DetailValue>>; | |
| 27 | } | |
| 28 | ||
| 29 | const MAX_WHAT = 80; | |
| 30 | const MAX_TEXT = 200; | |
| 31 | const MAX_KEYS = 16; | |
| 32 | ||
| 33 | export class MachineLog { | |
| 34 | readonly size: number; | |
| 35 | = 0; | |
| 36 | readonly : MachineEntry[] = []; | |
| 37 | readonly = new Set<(batch: readonly MachineEntry[]) => void>(); | |
| 38 | readonly : number; | |
| 39 | : MachineEntry[] = []; | |
| 40 | : ReturnType<typeof setTimeout> | undefined; | |
| 41 | ||
| 42 | constructor({ size = 500, flushMs = 50 }: { size?: number; flushMs?: number } = {}) { | |
| 43 | this.size = size; | |
| 44 | this. = flushMs; | |
| 45 | } | |
| 46 | ||
| 47 | /** The last sequence number given out; 0 before the first entry. */ | |
| 48 | get seq(): number { | |
| 49 | return this.; | |
| 50 | } | |
| 51 | ||
| 52 | note(kind: EntryKind, what: string, detail: Record<string, DetailValue> = {}, t = Date.now()): MachineEntry { | |
| 53 | const entry: MachineEntry = { seq: ++this., t, kind, what: what.slice(0, MAX_WHAT), detail }; | |
| 54 | this..push(entry); | |
| 55 | if (this..length > this.size) this..shift(); | |
| 56 | if (this..size) { | |
| 57 | this..push(entry); | |
| 58 | this. ??= setTimeout(() => this.(), this.); | |
| 59 | } | |
| 60 | return entry; | |
| 61 | } | |
| 62 | ||
| 63 | /** The last `n` entries, oldest first. */ | |
| 64 | recent(n = this.size): MachineEntry[] { | |
| 65 | return this..slice(-n); | |
| 66 | } | |
| 67 | ||
| 68 | /** Called with each batch of new entries; returns the way to stop. */ | |
| 69 | subscribe(listener: (batch: readonly MachineEntry[]) => void): () => void { | |
| 70 | this..add(listener); | |
| 71 | return () => { | |
| 72 | this..delete(listener); | |
| 73 | if (!this..size) this.close(); | |
| 74 | }; | |
| 75 | } | |
| 76 | ||
| 77 | /** Drop what is waiting to go out and stop the batch timer. */ | |
| 78 | close(): void { | |
| 79 | clearTimeout(this.); | |
| 80 | this. = undefined; | |
| 81 | this. = []; | |
| 82 | } | |
| 83 | ||
| 84 | () { | |
| 85 | this. = undefined; | |
| 86 | const batch = this.; | |
| 87 | this. = []; | |
| 88 | if (batch.length) for (const listener of this.) listener(batch); | |
| 89 | } | |
| 90 | } | |
| 91 | ||
| 92 | /** One map of servo id → value, e.g. the goals of a sync write. */ | |
| 93 | export function perServo(values: Iterable<readonly [number, number]>): Record<string, number> { | |
| 94 | const out: Record<string, number> = {}; | |
| 95 | for (const [id, value] of values) out[String(id)] = value; | |
| 96 | return out; | |
| 97 | } | |
| 98 | ||
| 99 | function detailValue(value: unknown): DetailValue | undefined { | |
| 100 | if (value === null || typeof value === "boolean") return value; | |
| 101 | if (typeof value === "number") return Number.isFinite(value) ? value : undefined; | |
| 102 | if (typeof value === "string") return value.replace(/[\p{Cc}\p{Cf}]+/gu, " ").slice(0, MAX_TEXT); | |
| 103 | if (typeof value !== "object" || Array.isArray(value)) return undefined; | |
| 104 | const out: Record<string, number> = {}; | |
| 105 | const entries = Object.entries(value as Record<string, unknown>); | |
| 106 | if (entries.length > MAX_KEYS) return undefined; | |
| 107 | for (const [key, n] of entries) { | |
| 108 | if (!/^\d{1,3}$/.test(key) || typeof n !== "number" || !Number.isFinite(n)) return undefined; | |
| 109 | out[key] = n; | |
| 110 | } | |
| 111 | return out; | |
| 112 | } | |
| 113 | ||
| 114 | /** | |
| 115 | * Entries from the wire (the arm server's /watch), checked one by one: anything that is not an entry is left out, | |
| 116 | * texts are cut short and stripped of control characters, a detail keeps only the values it may have. | |
| 117 | */ | |
| 118 | export function parseEntries(input: unknown): MachineEntry[] { | |
| 119 | if (!Array.isArray(input)) return []; | |
| 120 | const out: MachineEntry[] = []; | |
| 121 | for (const raw of input.slice(0, 1000)) { | |
| 122 | if (!raw || typeof raw !== "object") continue; | |
| 123 | const e = raw as Record<string, unknown>; | |
| 124 | if (!Number.isSafeInteger(e.seq) || (e.seq as number) < 1) continue; | |
| 125 | if (typeof e.t !== "number" || !Number.isFinite(e.t)) continue; | |
| 126 | if (!KINDS.includes(e.kind as EntryKind) || typeof e.what !== "string") continue; | |
| 127 | const detail: Record<string, DetailValue> = {}; | |
| 128 | if (e.detail && typeof e.detail === "object" && !Array.isArray(e.detail)) { | |
| 129 | for (const [key, value] of Object.entries(e.detail as Record<string, unknown>).slice(0, MAX_KEYS)) { | |
| 130 | if (!/^[A-Za-z][A-Za-z0-9]{0,31}$/.test(key)) continue; | |
| 131 | const v = detailValue(value); | |
| 132 | if (v !== undefined) detail[key] = v; | |
| 133 | } | |
| 134 | } | |
| 135 | out.push({ seq: e.seq as number, t: e.t, kind: e.kind as EntryKind, what: (detailValue(e.what) as string).slice(0, MAX_WHAT), detail }); | |
| 136 | } | |
| 137 | return out; | |
| 138 | } |
Software/so101/src/relay.ts +61 −8
| @@ -22,6 +22,8 @@ | ||
| 22 | 22 | * The owner's speed cap (src/speed-cap.ts) is applied here too, to moves, poses, grips, playbacks and every stream frame. |
| 23 | 23 | * |
| 24 | 24 | * WS /live the lobby: the turn, the queue, the chat, and the arm's /status pushed when it changes |
| 25 | * WS /machine read-only, for anyone: the arm's raw status, the link's round trip and frame rate, and every | |
| 26 | * command in and out with every safety clamp, pushed as it happens (src/machine-feed.ts) | |
| 25 | 27 | * POST /join {"name": "…"}: become someone here, no forge account needed (src/accounts.ts); the answer |
| 26 | 28 | * sets the HttpOnly session cookie and names you: {"you": {"id", "name", "owner"}} |
| 27 | 29 | * GET /admin, POST /admin the owner's page: pause, end a turn, take control, the settings, the log |
| @@ -45,6 +47,9 @@ import { Readable } from "node:stream"; | ||
| 45 | 47 | import { pipeline } from "node:stream/promises"; |
| 46 | 48 | import WebSocket, { WebSocketServer } from "ws"; |
| 47 | 49 | import { ArmLink, type LinkTimings } from "./arm-link.ts"; |
| 50 | import { MachineFeed } from "./machine-feed.ts"; | |
| 51 | import { perServo } from "./machine-log.ts"; | |
| 52 | import { parseFrame } from "./safety.ts"; | |
| 48 | 53 | import { acceptsGzip, GzipCache, worthCompressing } from "./compress.ts"; |
| 49 | 54 | import { AccountError, sessionCookie, visitor } from "./accounts.ts"; |
| 50 | 55 | import { AdminError, changeFromForm } from "./admin.ts"; |
| @@ -212,6 +217,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 212 | 217 | |
| 213 | 218 | // ------------------------------------------------------------------ the link |
| 214 | 219 | let armLink: ArmLink | null = null; |
| 220 | /** The simulation's own watch, held only while someone has the Machine panel open and the simulation is the arm. */ | |
| 221 | let simLink: ArmLink | null = null; | |
| 215 | 222 | let problem: string | null = options.problem ?? null; |
| 216 | 223 | /** Requests in flight to the arm server: cut when the link drops, so nothing waits on a dead one. */ |
| 217 | 224 | const inFlight = new Set<AbortController>(); |
| @@ -224,6 +231,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 224 | 231 | remote, |
| 225 | 232 | open: (url, timeoutMs) => open(url, timeoutMs), |
| 226 | 233 | timings: options.link, |
| 234 | onStatus: (status) => onArm() && machine.status(status), | |
| 235 | onMachine: (entries, run) => onArm() && machine.arm(entries, run), | |
| 227 | 236 | onChange: (state, previous) => { |
| 228 | 237 | if (state === "live") console.log(`arm server ${host}: live`); |
| 229 | 238 | else console.error(`arm server ${host}: ${state === "offline" ? "offline; simulating" : "reconnecting"} (${armLink?.problem})`); |
| @@ -246,6 +255,28 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 246 | 255 | /** Whether the arm server, not the simulation, is the arm right now: live, or only briefly gone. */ |
| 247 | 256 | const onArm = () => mode() === "live" || mode() === "reconnecting"; |
| 248 | 257 | const link = (): Link => ({ mode: mode(), host: remote?.host ?? null, problem: armLink ? armLink.problem : problem }); |
| 258 | // ------------------------------------------------------------------ the Machine panel's feed | |
| 259 | const shown = () => (onArm() ? armLink : simLink); | |
| 260 | const machine = new MachineFeed({ | |
| 261 | link: () => ({ ...link(), ...(shown()?.stats() ?? { rttMs: null, fps: 0, reconnects: 0 }) }), | |
| 262 | room: () => { | |
| 263 | const snapshot = lobby?.turns.snapshot(); | |
| 264 | return { driver: snapshot?.driver?.name ?? null, paused: Boolean(lobby?.admin.settings.paused), speedCapPercent: lobby?.maxSpeedPercent ?? 100 }; | |
| 265 | }, | |
| 266 | onViewers: (count) => { | |
| 267 | if (count === 0) { | |
| 268 | simLink?.close(); | |
| 269 | simLink = null; | |
| 270 | } else | |
| 271 | simLink ??= new ArmLink({ | |
| 272 | remote: { http: simulation, ws: simulationWs, host: "simulation" }, | |
| 273 | open: (url, timeoutMs) => open(url, timeoutMs), | |
| 274 | timings: options.link, | |
| 275 | onStatus: (status) => !onArm() && machine.status(status), | |
| 276 | onMachine: (entries, run) => !onArm() && machine.arm(entries, run), | |
| 277 | }); | |
| 278 | }, | |
| 279 | }); | |
| 249 | 280 | const source = () => { |
| 250 | 281 | const m = mode(); |
| 251 | 282 | if (m === "live") return `live ${remote!.host}`; |
| @@ -591,14 +622,25 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 591 | 622 | // Who stopped or cleared the arm is the relay's to say, never the page's; every other command is held to the admin's speed cap. |
| 592 | 623 | const raw = reading || route === "POST /estop" || route === "POST /estop/clear" ? undefined : await readBody(req); |
| 593 | 624 | const body = reading ? undefined : !raw ? Buffer.from(JSON.stringify({ by })) : lobby ? capBody(url.pathname, raw, lobby.maxSpeedPercent) : raw; |
| 594 | if (LOCAL.test(url.pathname) || !onArm() || !remote) return await pass(res, await ask(simulation + path, req, body, null, false)); | |
| 625 | const logged = !reading && !LOCAL.test(url.pathname); | |
| 626 | if (logged) machine.note("sent", route, { by }); | |
| 627 | const answered = (status: number) => logged && machine.note("received", route, { status }); | |
| 628 | if (LOCAL.test(url.pathname) || !onArm() || !remote) { | |
| 629 | const answer = await ask(simulation + path, req, body, null, false); | |
| 630 | answered(answer.response.status); | |
| 631 | return await pass(res, answer); | |
| 632 | } | |
| 595 | 633 | if (mode() === "reconnecting" && !reading && !STOPS.has(route)) { |
| 634 | machine.note("clamp", "not passed on", { route, why: RECONNECTING }); | |
| 596 | 635 | return json(res, 503, { error: `${RECONNECTING} at ${remote.host}…; driving resumes when it answers`, reconnecting: true }); |
| 597 | 636 | } |
| 598 | 637 | try { |
| 599 | 638 | // A read must answer fast; a move or a playback answers when the arm arrives, and is only cut when the link drops. |
| 600 | return await pass(res, await ask(remote.http + path, req, body, reading ? readTimeoutMs : null, true)); | |
| 639 | const answer = await ask(remote.http + path, req, body, reading ? readTimeoutMs : null, true); | |
| 640 | answered(answer.response.status); | |
| 641 | return await pass(res, answer); | |
| 601 | 642 | } catch (err) { |
| 643 | if (logged) machine.note("received", route, { error: reason(err) }); | |
| 602 | 644 | return json(res, mode() === "reconnecting" ? 503 : 502, { error: `the arm server at ${remote.host} did not answer (${reason(err)})`, reconnecting: mode() === "reconnecting" }); |
| 603 | 645 | } |
| 604 | 646 | } catch (err) { |
| @@ -663,22 +705,30 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 663 | 705 | .finally(() => (asking = false)); |
| 664 | 706 | }; |
| 665 | 707 | seed(); |
| 708 | /** A frame as the panel shows it: servo id → ticks. */ | |
| 709 | const values = (text: string) => perServo(parseFrame(text) ?? []); | |
| 666 | 710 | browser.on("message", (data, binary) => { |
| 667 | 711 | if (driver !== null) { |
| 668 | 712 | // The turn may have ended while this frame was on its way, before the close reaches the page: it is not passed on. |
| 669 | if (lobby && !lobby.turns.isDriver(driver) && !lobby.local) return; | |
| 713 | if (lobby && !lobby.turns.isDriver(driver) && !lobby.local) return void machine.note("clamp", "not passed on", { why: "the turn ended" }); | |
| 670 | 714 | lobby?.activity(driver); |
| 671 | 715 | } |
| 672 | if (arm.readyState !== WebSocket.OPEN || (real && mode() !== "live")) return; | |
| 716 | if (arm.readyState !== WebSocket.OPEN) return; | |
| 717 | if (real && mode() !== "live") return void machine.note("clamp", "not passed on", { why: RECONNECTING }); | |
| 673 | 718 | const percent = lobby?.maxSpeedPercent ?? 100; |
| 719 | const text = String(data); | |
| 674 | 720 | if (percent >= 100) { |
| 675 | if (lobby) cap.cap(String(data), percent); // keeps each joint's last target, so a cap set mid-stream starts from there | |
| 721 | if (lobby) cap.cap(text, percent); // keeps each joint's last target, so a cap set mid-stream starts from there | |
| 722 | machine.note("sent", "follow frame", { values: values(text) }); | |
| 676 | 723 | arm.send(data, { binary }); |
| 677 | 724 | return; |
| 678 | 725 | } |
| 679 | 726 | if (!seeded) seed(); |
| 680 | const capped = cap.cap(String(data), percent); | |
| 681 | if (capped !== null) arm.send(capped); | |
| 727 | const capped = cap.cap(text, percent); | |
| 728 | if (capped !== text) machine.note("clamp", "speed cap", { percent, asked: values(text), sent: capped === null ? {} : values(capped) }); | |
| 729 | if (capped === null) return; | |
| 730 | machine.note("sent", "follow frame", { values: values(capped) }); | |
| 731 | arm.send(capped); | |
| 682 | 732 | }); |
| 683 | 733 | arm.on("close", (code, why) => browser.close(sendable(code) ? code : 1011, why.length ? why.toString() : "the arm server went away")); |
| 684 | 734 | // A browser that closed the stream on purpose leaves the arm holding; one that vanished leaves it parking. |
| @@ -699,10 +749,11 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 699 | 749 | }; |
| 700 | 750 | http.on("upgrade", (req: IncomingMessage, socket: Duplex, head: Buffer) => { |
| 701 | 751 | const url = new URL(req.url ?? "/", "http://x"); |
| 702 | if (url.pathname !== "/follow" && !(url.pathname === "/live" && lobby)) return refuse(socket, "404 Not Found"); | |
| 752 | if (url.pathname !== "/follow" && url.pathname !== "/machine" && !(url.pathname === "/live" && lobby)) return refuse(socket, "404 Not Found"); | |
| 703 | 753 | if (!sameOrigin(req)) return refuse(socket, "403 Forbidden"); |
| 704 | 754 | socket.on("error", () => socket.destroy()); |
| 705 | 755 | if (url.pathname === "/live") return lobby!.upgrade(req, socket, head); |
| 756 | if (url.pathname === "/machine") return machine.upgrade(req, socket, head); | |
| 706 | 757 | let driver: string | null = null; |
| 707 | 758 | if (lobby) { |
| 708 | 759 | const who = lobby.who(req); |
| @@ -769,6 +820,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 769 | 820 | turnEnded?.(); |
| 770 | 821 | arrived?.(); |
| 771 | 822 | armLink?.close(); |
| 823 | simLink?.close(); | |
| 824 | machine.close(); | |
| 772 | 825 | if (!options.cameras) cameras.close(); |
| 773 | 826 | for (const c of inFlight) c.abort(); |
| 774 | 827 | for (const client of wss.clients) client.terminate(); |
Software/so101/src/server.test.ts +3 −2
| @@ -147,10 +147,11 @@ describe("viewer page", () => { | ||
| 147 | 147 | bytes += gzipSync(Buffer.from(await r.arrayBuffer()), { level: 6 }).length; |
| 148 | 148 | } |
| 149 | 149 | expect(bytes).toBeLessThan(50_000); |
| 150 | // three.js, the leader's mapping and the calibration panel are imported where they are used, not up front. | |
| 151 | for (const lazy of ["three", "/leader-map.js", "calibration.js", "reach.js"]) expect([...upfront].some((p) => p === lazy || p.endsWith(`/${lazy}`))).toBe(false); | |
| 150 | // three.js, the leader's mapping, the calibration panel and the Machine panel are imported where they are used, not up front. | |
| 151 | for (const lazy of ["three", "/leader-map.js", "calibration.js", "reach.js", "machine-panel.js", "machine.js"]) expect([...upfront].some((p) => p === lazy || p.endsWith(`/${lazy}`))).toBe(false); | |
| 152 | 152 | expect(script).toContain('import("/leader-map.js")'); |
| 153 | 153 | expect(script).toMatch(/import\("\/ui\/[0-9a-f]{12}\/calibration\.js"\)/); |
| 154 | expect(script).toMatch(/import\("\/ui\/[0-9a-f]{12}\/machine-panel\.js"\)/); | |
| 154 | 155 | }); |
| 155 | 156 | |
| 156 | 157 | test("names its modules by their content, serves them for good, and serves nothing else from src/ui", async () => { |
Software/so101/src/server.ts +75 −6
| @@ -33,7 +33,10 @@ | ||
| 33 | 33 | * GET /printables the sheets to print for the vision quest (board, cube markers, gripper marker); GET /printables/<file> |
| 34 | 34 | * WS /follow client sends {"1": ticks, "2": ticks, ...} frames; the server drives the arm |
| 35 | 35 | * WS /watch read-only: the server sends the /status body every watchEveryMs, one bus read shared by every watcher; |
| 36 | * the hosted app's relay keeps one open, so viewers see the arm without each of them asking the Pi | |
| 36 | * the hosted app's relay keeps one open, so viewers see the arm without each of them asking the Pi. | |
| 37 | * Between them, {"machine": [entries], "run": "<id>"}: every register written on the bus, every | |
| 38 | * change of driver, hold and E-stop, and every safety clamp, as it happens (src/machine-log.ts); | |
| 39 | * the last 200 first, on connecting. `run` changes when the server restarts and its numbering starts over. | |
| 37 | 40 | * |
| 38 | 41 | * One thing drives the arm at a time. Every target is pulled inside the joint limits and every motion held to the speed and |
| 39 | 42 | * acceleration limits (src/safety.ts); a stream that goes silent holds, one whose connection is lost parks. Every target, whether a move or a stream frame, is run through |
| @@ -46,17 +49,18 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, | ||
| 46 | 49 | import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; |
| 47 | 50 | import { dirname, extname, join, resolve } from "node:path"; |
| 48 | 51 | import type { Duplex } from "node:stream"; |
| 49 | import { createHash } from "node:crypto"; | |
| 52 | import { createHash, randomUUID } from "node:crypto"; | |
| 50 | 53 | import { fileURLToPath } from "node:url"; |
| 51 | 54 | import { WebSocketServer, type WebSocket } from "ws"; |
| 52 | 55 | import { browserModule } from "./browser-modules.ts"; |
| 53 | 56 | import type { FeetechBus } from "./bus.ts"; |
| 54 | 57 | import { ArmModel, gripperTicksToRadians, ticksToRadians, type Violation } from "./kinematics.ts"; |
| 55 | 58 | import { clamp, type Frame } from "./mapping.ts"; |
| 59 | import { MachineLog, perServo } from "./machine-log.ts"; | |
| 56 | 60 | import { Metrics } from "./metrics.ts"; |
| 57 | 61 | import { MotionError, moveToPose, playTrajectory, recordTrajectory, STALL_SPAN_TICKS } from "./motion.ts"; |
| 58 | 62 | import { assertPoseName, parsePoseFile, serializePoseFile, type PoseFile } from "./poses.ts"; |
| 59 | import { JOINTS, STS3215, ticksToDegrees } from "./sts3215.ts"; | |
| 63 | import { JOINTS, registerName, STS3215, ticksToDegrees } from "./sts3215.ts"; | |
| 60 | 64 | import { largestStep, parseTrajectory, serializeTrajectory, type Trajectory } from "./trajectory.ts"; |
| 61 | 65 | import { accelRegister, bound, DEFAULT_SAFETY, Governor, jointBounds, motionLimits, parseFrame, SAFETY_KEYS, SafetyError, TICKS_PER_DEGREE, validateSafety, type SafetySettings } from "./safety.ts"; |
| 62 | 66 | |
| @@ -165,6 +169,16 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 165 | 169 | throw new Error(`safety options: ${(err as Error).message}`); |
| 166 | 170 | } |
| 167 | 171 | const metrics = new Metrics(join(dataDir, "metrics.jsonl")); |
| 172 | // The machine, raw: every sync write as it goes on the wire, and each joint's last goal, for the Machine panel. | |
| 173 | const machine = new MachineLog(); | |
| 174 | const run = randomUUID(); | |
| 175 | const goals = new Map<number, number>(); | |
| 176 | bus.onSyncWrite = (register, values) => { | |
| 177 | if (register === STS3215.Goal_Position) for (const [id, v] of values) goals.set(id, v); | |
| 178 | machine.note("sent", registerName(register), { values: perServo(values) }); | |
| 179 | }; | |
| 180 | /** The stream's dead-man hold is in force: no frame came for holdAfterMs, and the arm stays where it was. */ | |
| 181 | let held = false; | |
| 168 | 182 | |
| 169 | 183 | const limits = new Map<number, { min: number; max: number }>(); |
| 170 | 184 | for (const id of ids) { |
| @@ -251,9 +265,11 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 251 | 265 | if (driver) throw new HttpError(409, `${describe(driver)} is driving the arm`); |
| 252 | 266 | driver = kind; |
| 253 | 267 | current = new AbortController(); |
| 268 | machine.note("state", "driver", { driving: kind }); | |
| 254 | 269 | return current; |
| 255 | 270 | }; |
| 256 | 271 | const release = () => { |
| 272 | if (driver) machine.note("state", "driver", { driving: null }); | |
| 257 | 273 | driver = null; |
| 258 | 274 | current = null; |
| 259 | 275 | }; |
| @@ -293,6 +309,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 293 | 309 | estop = { by, at: new Date().toISOString() }; |
| 294 | 310 | writeAtomic(estopFile, JSON.stringify(estop)); |
| 295 | 311 | metrics.event("estop", { by }); |
| 312 | machine.note("state", "emergency stop", { by }); | |
| 296 | 313 | } |
| 297 | 314 | const was = driver; |
| 298 | 315 | if (was === "stream") for (const client of wss.clients) client.close(ESTOP_CLOSE, "emergency stop"); // its close handler holds, never parks |
| @@ -314,6 +331,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 314 | 331 | /* already gone */ |
| 315 | 332 | } |
| 316 | 333 | metrics.event("estop-clear", { by }); |
| 334 | machine.note("state", "emergency stop cleared", { by }); | |
| 317 | 335 | return true; |
| 318 | 336 | }; |
| 319 | 337 | |
| @@ -335,6 +353,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 335 | 353 | const violation = checkPath(from, new Map([...from, ...targets])); |
| 336 | 354 | if (violation && settings.zone === "enforce") { |
| 337 | 355 | metrics.event("park", { why, parked: false, error: `refused: ${describeViolation(violation)}` }); |
| 356 | machine.note("clamp", "zone", { what: violation.what, link: violation.link, depthMm: Math.round(violation.depth * 1000), refused: true, source: "park" }); | |
| 338 | 357 | return; |
| 339 | 358 | } |
| 340 | 359 | await moveToPose(bus, targets.map(([id]) => id), targets.map(([, t]) => t), { |
| @@ -344,6 +363,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 344 | 363 | signal: controller.signal, |
| 345 | 364 | }); |
| 346 | 365 | metrics.event("park", { why, parked: true, pose: pose ? settings.parkPose : "middle" }); |
| 366 | machine.note("state", "parked", { why, pose: pose ? settings.parkPose : "middle" }); | |
| 347 | 367 | } catch (err) { |
| 348 | 368 | metrics.event("park", { why, parked: false, error: err instanceof Error ? err.message : String(err) }); |
| 349 | 369 | } finally { |
| @@ -509,6 +529,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 509 | 529 | const loads = await bus.syncRead(ids, STS3215.Present_Load); |
| 510 | 530 | const temps = await bus.syncRead(ids, STS3215.Present_Temperature); |
| 511 | 531 | const torque = await bus.syncRead(ids, STS3215.Torque_Enable); |
| 532 | const b = bounds(); | |
| 512 | 533 | const joints = ids.map((id) => ({ |
| 513 | 534 | id, |
| 514 | 535 | joint: JOINTS[id] ?? null, |
| @@ -517,6 +538,13 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 517 | 538 | load: loads.has(id) ? loads.get(id)! / 10 : null, |
| 518 | 539 | temperature: temps.get(id) ?? null, |
| 519 | 540 | torque: torque.has(id) ? torque.get(id) === 1 : null, |
| 541 | /** The last Goal_Position this server wrote, ticks; null before the first. */ | |
| 542 | target: goals.get(id) ?? null, | |
| 543 | /** The calibrated range (the servo's own limits), and the narrower bounds every command is held inside. */ | |
| 544 | min: limits.get(id)?.min ?? null, | |
| 545 | max: limits.get(id)?.max ?? null, | |
| 546 | lo: b.get(id)?.min ?? null, | |
| 547 | hi: b.get(id)?.max ?? null, | |
| 520 | 548 | })); |
| 521 | 549 | metrics.sample(joints); |
| 522 | 550 | const zone = evaluate(positions); |
| @@ -532,7 +560,9 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 532 | 560 | blocked, |
| 533 | 561 | jammed: [...jams.keys()], |
| 534 | 562 | stream: streamStats, |
| 563 | held, | |
| 535 | 564 | estop, |
| 565 | machine: { run, seq: machine.seq }, | |
| 536 | 566 | }; |
| 537 | 567 | }; |
| 538 | 568 | |
| @@ -541,6 +571,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 541 | 571 | const controller = claim("move"); |
| 542 | 572 | const b = bounds(); |
| 543 | 573 | const positions = targetIds.map((id, i) => bound(b, id, requested[i]!) ?? requested[i]!); |
| 574 | targetIds.forEach((id, i) => positions[i] !== requested[i] && machine.note("clamp", "joint limit", { id, asked: requested[i]!, sent: positions[i]!, source })); | |
| 544 | 575 | try { |
| 545 | 576 | const from = await bus.syncRead(ids, STS3215.Present_Position); |
| 546 | 577 | const to = new Map(from); |
| @@ -548,10 +579,13 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 548 | 579 | const violation = checkPath(from, to); |
| 549 | 580 | if (violation) { |
| 550 | 581 | metrics.event("block", { source, what: violation.what, link: violation.link, depthMm: Math.round(violation.depth * 1000), mode: settings.zone }); |
| 582 | machine.note("clamp", "zone", { what: violation.what, link: violation.link, depthMm: Math.round(violation.depth * 1000), refused: settings.zone === "enforce", source }); | |
| 551 | 583 | if (settings.zone === "enforce") return { status: 409, body: { reached: false, error: `refused: ${describeViolation(violation)}`, violation } }; |
| 552 | 584 | } |
| 585 | const speed = number(body.speed, 300, 20, speedLimits().speed, "speed"); | |
| 586 | if (typeof body.speed === "number" && body.speed > speed) machine.note("clamp", "speed limit", { asked: body.speed, sent: speed, source }); | |
| 553 | 587 | const result = await moveToPose(bus, targetIds, positions, { |
| 554 | speed: number(body.speed, 300, 20, speedLimits().speed, "speed"), | |
| 588 | speed, | |
| 555 | 589 | torquePercent: number(body.torque, 70, 10, 100, "torque"), |
| 556 | 590 | torqueCaps: torqueCaps(), |
| 557 | 591 | signal: controller.signal, |
| @@ -758,6 +792,8 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 758 | 792 | const position = bound(bounds(), id, body.position as number)!; |
| 759 | 793 | const torque = Math.min(number(body.torque, 30, 10, 60, "torque"), settings.gripperTorquePercent); // the force limit, whatever is asked |
| 760 | 794 | const speed = Math.min(Math.round(number(body.speed, 300, 20, 300, "speed")), speedLimits().speed); // and the speed limit |
| 795 | if (position !== body.position) machine.note("clamp", "joint limit", { id, asked: body.position as number, sent: position, source: "grip" }); | |
| 796 | if (typeof body.torque === "number" && body.torque > torque) machine.note("clamp", "gripper force", { asked: body.torque, sent: torque, source: "grip" }); | |
| 761 | 797 | claim("move"); |
| 762 | 798 | try { |
| 763 | 799 | const present = await bus.syncRead([id], STS3215.Present_Position); |
| @@ -838,6 +874,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 838 | 874 | const step = largestStep(trajectory); |
| 839 | 875 | const asked = number(body.rate, 1, 0.1, 2, "rate"); |
| 840 | 876 | const rate = step > 0 ? Math.min(asked, speedLimits().speed / (step * trajectory.hz)) : asked; |
| 877 | if (rate < asked) machine.note("clamp", "speed limit", { asked, sent: Number(rate.toFixed(3)), source: `play ${name}` }); | |
| 841 | 878 | const controller = claim("play"); |
| 842 | 879 | try { |
| 843 | 880 | if (model && settings.zone !== "off") { |
| @@ -851,6 +888,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 851 | 888 | }; |
| 852 | 889 | const refuse = (v: Violation, where: string): boolean => { |
| 853 | 890 | metrics.event("block", { source: `play ${name}`, where, what: v.what, link: v.link, depthMm: Math.round(v.depth * 1000), mode: settings.zone }); |
| 891 | machine.note("clamp", "zone", { what: v.what, link: v.link, depthMm: Math.round(v.depth * 1000), refused: settings.zone === "enforce", source: `play ${name}` }); | |
| 854 | 892 | if (settings.zone !== "enforce") return false; |
| 855 | 893 | json(res, 409, { played: 0, error: `refused: ${where}: ${describeViolation(v)}`, violation: v }); |
| 856 | 894 | return true; |
| @@ -933,6 +971,8 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 933 | 971 | await bus.syncWrite(STS3215.Goal_Position, ids.filter((id) => positions.has(id)).map((id) => [id, positions.get(id)!] as const)); |
| 934 | 972 | governor.reset(positions); |
| 935 | 973 | last = null; |
| 974 | held = true; | |
| 975 | machine.note("state", "dead-man hold", { afterMs: holdAfterMs }); | |
| 936 | 976 | }); |
| 937 | 977 | const arm = () => |
| 938 | 978 | run(async () => { |
| @@ -967,6 +1007,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 967 | 1007 | jams.set(id, { position: p, direction: Math.sign(target - p) }); |
| 968 | 1008 | last?.set(id, p); |
| 969 | 1009 | metrics.event("jam", { source: "stream", id, joint: JOINTS[id] ?? null, position: p, target, load: l / 10 }); |
| 1010 | machine.note("clamp", "jam", { id, position: p, target, load: l / 10 }); | |
| 970 | 1011 | return true; |
| 971 | 1012 | }; |
| 972 | 1013 | const watch = setInterval( |
| @@ -1019,7 +1060,10 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1019 | 1060 | for (const [id, value] of frame) { |
| 1020 | 1061 | const target = bound(b, id, value); |
| 1021 | 1062 | if (target === null) continue; |
| 1022 | if (target !== Math.round(value)) stats.clamped++; | |
| 1063 | if (target !== Math.round(value)) { | |
| 1064 | stats.clamped++; | |
| 1065 | machine.note("clamp", "joint limit", { id, asked: Math.round(value), sent: target, source: "stream" }); | |
| 1066 | } | |
| 1023 | 1067 | const jam = jams.get(id); |
| 1024 | 1068 | if (jam) { |
| 1025 | 1069 | if ((target - jam.position) * jam.direction > -10) continue; // still pushing into the obstacle: wait for the leader to back off |
| @@ -1030,6 +1074,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1030 | 1074 | if (previous === undefined) ease = true; // a joint this stream has not driven yet is eased over, never jumped |
| 1031 | 1075 | else if (Math.abs(target - previous) > maxStep) { |
| 1032 | 1076 | stats.dropped++; |
| 1077 | machine.note("clamp", "too far in one frame", { id, asked: target, from: previous, maxStep }); | |
| 1033 | 1078 | const n = (drops.get(id) ?? 0) + 1; |
| 1034 | 1079 | drops.set(id, n); |
| 1035 | 1080 | if (n < RESUME_AFTER_DROPS) continue; // no hand moves that far in one frame |
| @@ -1041,6 +1086,10 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1041 | 1086 | } |
| 1042 | 1087 | if (!targets.length) return; |
| 1043 | 1088 | stats.frames++; |
| 1089 | if (held) { | |
| 1090 | held = false; | |
| 1091 | machine.note("state", "following again", {}); | |
| 1092 | } | |
| 1044 | 1093 | // The zone: the frame is judged as the whole pose it would make, with uncommanded joints where they are. |
| 1045 | 1094 | const pose = new Map(present); |
| 1046 | 1095 | for (const [id, t] of last ?? []) pose.set(id, t); |
| @@ -1051,6 +1100,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1051 | 1100 | blocked = zone.violation; |
| 1052 | 1101 | if (settings.zone === "enforce" && zone.violation.depth > heldDepth + 0.001) { |
| 1053 | 1102 | stats.refused++; |
| 1103 | machine.note("clamp", "zone", { what: zone.violation.what, link: zone.violation.link, depthMm: Math.round(zone.violation.depth * 1000), refused: true, source: "stream" }); | |
| 1054 | 1104 | return; // deeper in than the arm already is: it stays at the last good targets; a frame that backs out is let through |
| 1055 | 1105 | } |
| 1056 | 1106 | } else blocked = null; |
| @@ -1137,6 +1187,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1137 | 1187 | } |
| 1138 | 1188 | } finally { |
| 1139 | 1189 | blocked = null; |
| 1190 | held = false; | |
| 1140 | 1191 | jams.clear(); |
| 1141 | 1192 | streamStats = null; |
| 1142 | 1193 | metrics.event("stream", { seconds: Number(((Date.now() - startedAt) / 1000).toFixed(1)), ...stats, ...(lost ? { lost: code } : {}) }); |
| @@ -1153,26 +1204,42 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1153 | 1204 | const watchEveryMs = options.watchEveryMs ?? 250; |
| 1154 | 1205 | let watching: ReturnType<typeof setInterval> | undefined; |
| 1155 | 1206 | let reading = false; |
| 1207 | const machineFrame = (entries: readonly unknown[]) => JSON.stringify({ machine: entries, run }); | |
| 1156 | 1208 | const broadcast = async () => { |
| 1157 | 1209 | if (reading) return; // a slow bus read is not stacked behind another: the next tick asks again |
| 1158 | 1210 | reading = true; |
| 1159 | 1211 | try { |
| 1160 | 1212 | const text = JSON.stringify(await status()); |
| 1161 | for (const w of watchers.clients) if (w.readyState === w.OPEN) w.send(text); | |
| 1213 | for (const w of watchers.clients) { | |
| 1214 | if (w.readyState !== w.OPEN) continue; | |
| 1215 | w.send(text); | |
| 1216 | // A new watcher's first message is a status; the machine log so far comes right after it. | |
| 1217 | if (fresh.delete(w)) w.send(machineFrame(machine.recent(200))); | |
| 1218 | } | |
| 1162 | 1219 | } catch (err) { |
| 1163 | 1220 | console.error(`watch: ${err instanceof Error ? err.message : String(err)}`); |
| 1164 | 1221 | } finally { |
| 1165 | 1222 | reading = false; |
| 1166 | 1223 | } |
| 1167 | 1224 | }; |
| 1225 | /** The machine log goes out as it is written, while anyone watches; a watcher yet to get its first status gets it all then. */ | |
| 1226 | let unsubscribe: (() => void) | undefined; | |
| 1227 | const fresh = new WeakSet<WebSocket>(); | |
| 1168 | 1228 | watchers.on("connection", (ws: WebSocket) => { |
| 1169 | 1229 | watching ??= setInterval(() => void broadcast(), watchEveryMs); |
| 1230 | unsubscribe ??= machine.subscribe((batch) => { | |
| 1231 | const text = machineFrame(batch); | |
| 1232 | for (const w of watchers.clients) if (w.readyState === w.OPEN && !fresh.has(w)) w.send(text); | |
| 1233 | }); | |
| 1234 | fresh.add(ws); | |
| 1170 | 1235 | void broadcast(); |
| 1171 | 1236 | ws.on("error", () => ws.terminate()); |
| 1172 | 1237 | ws.on("close", () => { |
| 1173 | 1238 | if (watchers.clients.size > 0 || !watching) return; |
| 1174 | 1239 | clearInterval(watching); |
| 1175 | 1240 | watching = undefined; |
| 1241 | unsubscribe?.(); | |
| 1242 | unsubscribe = undefined; | |
| 1176 | 1243 | }); |
| 1177 | 1244 | }); |
| 1178 | 1245 | |
| @@ -1192,6 +1259,8 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 1192 | 1259 | close: () => |
| 1193 | 1260 | new Promise<void>((resolve) => { |
| 1194 | 1261 | clearInterval(watching); |
| 1262 | machine.close(); | |
| 1263 | bus.onSyncWrite = null; | |
| 1195 | 1264 | for (const client of [...wss.clients, ...watchers.clients]) client.terminate(); |
| 1196 | 1265 | wss.close(); |
| 1197 | 1266 | watchers.close(); |
Software/so101/src/sts3215.ts +6
| @@ -118,6 +118,12 @@ export function findRegister(name: string): [RegisterName, Register] | undefined | ||
| 118 | 118 | return undefined; |
| 119 | 119 | } |
| 120 | 120 | |
| 121 | /** A register's name in the table, for logs; the first of two names that share an address. */ | |
| 122 | export function registerName(register: Register): string { | |
| 123 | for (const key of Object.keys(STS3215) as RegisterName[]) if (STS3215[key] === register) return key; | |
| 124 | return `register ${register.address}`; | |
| 125 | } | |
| 126 | ||
| 121 | 127 | export const ticksToDegrees = (ticks: number): number => (ticks * 360) / RESOLUTION; |
| 122 | 128 | export const degreesToTicks = (degrees: number): number => Math.round((degrees * RESOLUTION) / 360); |
| 123 | 129 |
Software/so101/src/terminal.test.ts +41 −1
| @@ -12,7 +12,8 @@ import { identify, sign } from "./identity.ts"; | ||
| 12 | 12 | import { Lobby } from "./lobby.ts"; |
| 13 | 13 | import { startRelay, type RunningRelay } from "./relay.ts"; |
| 14 | 14 | import { startServer, type RunningServer } from "./server.ts"; |
| 15 | import { Door, emptyRoom, hear, liveUrl, plain, terminalHeaders, typed } from "./terminal.ts"; | |
| 15 | import { Door, emptyRoom, hear, liveUrl, machineEntry, machineLines, machineUrl, plain, terminalHeaders, typed } from "./terminal.ts"; | |
| 16 | import { jointRows } from "./ui/machine.js"; | |
| 16 | 17 | import { Turns } from "./turns.ts"; |
| 17 | 18 | |
| 18 | 19 | const KEY = "test-identity-key"; |
| @@ -85,6 +86,22 @@ describe("terminal lines", () => { | ||
| 85 | 86 | expect(typed(room, "/quit")).toEqual({ quit: true }); |
| 86 | 87 | expect(typed(room, " ")).toBeNull(); |
| 87 | 88 | expect(typed(emptyRoom(), "/end")).toEqual({ print: "nobody has control" }); |
| 89 | expect(typed(room, "/machine")).toEqual({ machine: true }); | |
| 90 | expect(typed(room, "/machine off")).toEqual({ machine: false }); | |
| 91 | expect(typed(room, "/machine now")).toEqual({ print: "usage: /machine [off]" }); | |
| 92 | }); | |
| 93 | ||
| 94 | test("the machine in the page's words, and nothing from the arm reaches the terminal as an escape", () => { | |
| 95 | expect(machineUrl("ws://127.0.0.1:4123/live")).toBe("ws://127.0.0.1:4123/machine"); | |
| 96 | const status = { joints: [{ id: 2, joint: "shoulder_lift", position: 1234, degrees: 108.5, load: -12.3, temperature: 41, torque: true, target: null, min: 818, max: 3487, lo: 848, hi: 3457 }], driving: null, held: false, estop: null }; | |
| 97 | const lines = machineLines({ status, link: { mode: "live", host: "pi:8101", rttMs: 17, fps: 4, reconnects: 0, problem: null }, room: { driver: "alice", paused: false, speedCapPercent: 100 }, skew: 0 }); | |
| 98 | expect(lines).toEqual([ | |
| 99 | "2 shoulder_lift · 1234 ticks 108.5° · target — · load -12.3% · 41 °C · torque on · limits 818–3487 · bounds 848–3457", | |
| 100 | "arm: live · pi:8101 · round trip: 17 ms · status frames: 4/s · reconnects: 0", | |
| 101 | "turn: alice · driving: nothing (idle) · held: no · E-stop: off · zone: — · blocked: no · jammed: no · speed cap: 100% · queue: open", | |
| 102 | ]); | |
| 103 | expect(machineEntry({ seq: 3, t: 0, kind: "clamp", what: "zone\x1b[2J", detail: { link: "x\x07" } }, 250)).toBe("#3 250 ms ⚠ zone[2J link=x"); | |
| 104 | expect(machineEntry({ seq: "3" }, 0)).toBeNull(); | |
| 88 | 105 | }); |
| 89 | 106 | }); |
| 90 | 107 | |
| @@ -145,6 +162,29 @@ describe("terminal door", () => { | ||
| 145 | 162 | await alice.printedLine(/^bob: hello terminal$/); |
| 146 | 163 | }); |
| 147 | 164 | |
| 165 | test("/machine at the terminal: the joints as the page shows them, then every command and clamp as it happens", async () => { | |
| 166 | const port = await start(); | |
| 167 | const owner = await terminal(port, ttyEnv("u-o", "trevato", "admin")); | |
| 168 | owner.door.input("/machine"); | |
| 169 | const row = jointRows((await (await fetch(`http://127.0.0.1:${port}/status`)).json()) as never)[0]!; | |
| 170 | await owner.printedLine(new RegExp(`^1 shoulder_pan · ${row.ticks} ticks ${row.degrees} · .* · limits ${row.limits} · bounds ${row.bounds}$`)); | |
| 171 | await owner.printedLine(/^arm: simulated · round trip: /); | |
| 172 | await owner.printedLine(/^turn: nobody · driving: nothing \(idle\)/); | |
| 173 | owner.door.input("/join"); | |
| 174 | await waitFor(() => (lobby!.turns.isDriver("u-o") ? true : undefined), "the owner's turn"); | |
| 175 | const moved = await fetch(`http://127.0.0.1:${port}/move`, { method: "POST", headers: web("u-o", "trevato", "admin"), body: JSON.stringify({ targets: { 1: 9999 } }) }); | |
| 176 | expect(moved.status).toBe(200); | |
| 177 | await owner.printedLine(/^#\d+ \S+ (ms|s) → POST \/move by=trevato$/); | |
| 178 | await owner.printedLine(/^#\d+ \S+ (ms|s) ⚠ joint limit id=1 asked=9999 sent=4065 source=move \(arm #\d+\)$/); | |
| 179 | await owner.printedLine(/^#\d+ \S+ (ms|s) ← POST \/move status=200$/); | |
| 180 | owner.door.input("/machine off"); | |
| 181 | await owner.printedLine(/^machine feed closed$/); | |
| 182 | const after = owner.printed.length; | |
| 183 | await fetch(`http://127.0.0.1:${port}/move`, { method: "POST", headers: web("u-o", "trevato", "admin"), body: JSON.stringify({ targets: { 1: 2048 } }) }); | |
| 184 | await sleep(150); | |
| 185 | expect(owner.printed.slice(after).filter((l) => /^#\d+/.test(l))).toEqual([]); | |
| 186 | }); | |
| 187 | ||
| 148 | 188 | test("a guest at the terminal watches and is refused chat and the line", async () => { |
| 149 | 189 | const port = await start(); |
| 150 | 190 | const page = await viewer(port); |
Software/so101/src/terminal.ts +98 −2
| @@ -14,6 +14,8 @@ | ||
| 14 | 14 | * /ready /extend confirm you are there when called (15 s), or add 30 s to your turn |
| 15 | 15 | * /end [who] owner: end that turn (none: whoever drives), or take them out of the line |
| 16 | 16 | * /mute <who> /unmute <who> owner |
| 17 | * /machine [off] the Machine panel (/machine, src/machine-feed.ts): the joints, the link and the server as they are, | |
| 18 | * then every command in and out as it happens, in the page's own words (src/ui/machine.js); off stops it | |
| 17 | 19 | * /who /help /quit |
| 18 | 20 | * <who> is a name the door has seen (driving, in line, in the chat) or a user id. |
| 19 | 21 | */ |
| @@ -21,6 +23,7 @@ | ||
| 21 | 23 | import WebSocket from "ws"; |
| 22 | 24 | import { UNPRINTABLE } from "./chat.ts"; |
| 23 | 25 | import { ID, NAME, sign } from "./identity.ts"; |
| 26 | import { entryLine, jointRows, linkRows, stateRows } from "./ui/machine.js"; | |
| 24 | 27 | |
| 25 | 28 | export type Env = Record<string, string | undefined>; |
| 26 | 29 | |
| @@ -90,7 +93,36 @@ const said = (m: unknown): string => { | ||
| 90 | 93 | return from ? `${plain(from.name)}: ${plain(message?.text)}` : `· ${plain(message?.text)}`; |
| 91 | 94 | }; |
| 92 | 95 | |
| 93 | export const HELP = "type to chat · /join /leave /ready /extend · /end [who] /mute <who> /unmute <who> (owner) · /who · /quit"; | |
| 96 | export const HELP = "type to chat · /join /leave /ready /extend · /end [who] /mute <who> /unmute <who> (owner) · /machine [off] · /who · /quit"; | |
| 97 | ||
| 98 | /** The Machine feed's socket beside the lobby's: same app, same port. */ | |
| 99 | export const machineUrl = (live: string): string => live.replace(/\/live$/, "/machine"); | |
| 100 | ||
| 101 | /** What the Machine feed said last: the arm's status, the link, the room. */ | |
| 102 | export interface MachineState { | |
| 103 | status: Record<string, unknown> | null; | |
| 104 | link: Record<string, unknown> | null; | |
| 105 | room: Record<string, unknown> | null; | |
| 106 | /** The feed's clock minus this one, so ages read as the page's do. */ | |
| 107 | skew: number; | |
| 108 | } | |
| 109 | ||
| 110 | /** The panel's top half as lines: one per joint, then the link and the server. */ | |
| 111 | export function machineLines(m: MachineState): string[] { | |
| 112 | const kv = (rows: Array<[string, string]>) => rows.map(([k, v]) => `${plain(k)}: ${plain(v)}`).join(" · "); | |
| 113 | const joints = jointRows(m.status as never).map((r) => | |
| 114 | plain(`${r.id} ${r.name} · ${r.ticks} ticks ${r.degrees} · target ${r.target} · load ${r.load} · ${r.temperature} · torque ${r.torque} · limits ${r.limits} · bounds ${r.bounds}`), | |
| 115 | ); | |
| 116 | return [...(joints.length ? joints : ["no status from the arm yet"]), kv(linkRows(m.link as never)), kv(stateRows(m.status as never, m.room as never))]; | |
| 117 | } | |
| 118 | ||
| 119 | /** One log entry as a terminal line: number, age, what. */ | |
| 120 | export function machineEntry(e: unknown, now: number): string | null { | |
| 121 | const x = e as { seq?: unknown; t?: unknown; kind?: unknown; what?: unknown } | null; | |
| 122 | if (!x || typeof x.seq !== "number" || typeof x.t !== "number" || typeof x.kind !== "string" || typeof x.what !== "string") return null; | |
| 123 | const line = entryLine(x as never, now); | |
| 124 | return plain(`${line.seq} ${line.age} ${line.text}`); | |
| 125 | } | |
| 94 | 126 | |
| 95 | 127 | /** Once each: "you are called, confirm" and "you are next", so a terminal driver gets what the page's strip shows. */ |
| 96 | 128 | function cues(room: Room, driver: unknown): string[] { |
| @@ -160,7 +192,7 @@ function target(room: Room, word: string): string | null { | ||
| 160 | 192 | return ID.test(word) ? word : null; |
| 161 | 193 | } |
| 162 | 194 | |
| 163 | export type Typed = { send: Frame } | { print: string } | { quit: true } | null; | |
| 195 | export type Typed = { send: Frame } | { print: string } | { machine: boolean } | { quit: true } | null; | |
| 164 | 196 | |
| 165 | 197 | /** What a typed line asks for. Validation the server repeats anyway; this only saves a round trip on a typo. */ |
| 166 | 198 | export function typed(room: Room, input: string): Typed { |
| @@ -186,6 +218,9 @@ export function typed(room: Room, input: string): Typed { | ||
| 186 | 218 | const id = target(room, arg); |
| 187 | 219 | return id ? { send: { type: "mute", id, on: verb.toLowerCase() === "mute" } } : { print: `error: who is ${plain(arg)}?` }; |
| 188 | 220 | } |
| 221 | case "machine": | |
| 222 | if (arg && arg.toLowerCase() !== "off" && arg.toLowerCase() !== "on") return { print: "usage: /machine [off]" }; | |
| 223 | return { machine: arg.toLowerCase() !== "off" }; | |
| 189 | 224 | case "who": |
| 190 | 225 | return { print: who(room) }; |
| 191 | 226 | case "help": |
| @@ -202,6 +237,8 @@ export function typed(room: Room, input: string): Typed { | ||
| 202 | 237 | export class Door { |
| 203 | 238 | readonly room = emptyRoom(); |
| 204 | 239 | private ws: WebSocket | null = null; |
| 240 | private machineWs: WebSocket | null = null; | |
| 241 | readonly machine: MachineState = { status: null, link: null, room: null, skew: 0 }; | |
| 205 | 242 | private readonly url: string; |
| 206 | 243 | private readonly headers: Record<string, string>; |
| 207 | 244 | private readonly print: (line: string) => void; |
| @@ -243,12 +280,71 @@ export class Door { | ||
| 243 | 280 | if (!t) return true; |
| 244 | 281 | if ("quit" in t) return false; |
| 245 | 282 | if ("print" in t) this.print(t.print); |
| 283 | else if ("machine" in t) this.watchMachine(t.machine); | |
| 246 | 284 | else this.send(t.send); |
| 247 | 285 | return true; |
| 248 | 286 | } |
| 249 | 287 | |
| 250 | 288 | close(): void { |
| 251 | 289 | this.ws?.close(); |
| 290 | this.machineWs?.close(); | |
| 291 | } | |
| 292 | ||
| 293 | /** On: the panel now (again, if it is open), then the log as it comes. Off: close the feed. */ | |
| 294 | private watchMachine(on: boolean): void { | |
| 295 | if (!on) { | |
| 296 | if (!this.machineWs) return this.print("the machine feed is not open"); | |
| 297 | this.machineWs.close(); | |
| 298 | this.machineWs = null; | |
| 299 | return this.print("machine feed closed"); | |
| 300 | } | |
| 301 | if (this.machineWs) return void machineLines(this.machine).forEach((l) => this.print(l)); | |
| 302 | const ws = new WebSocket(machineUrl(this.url), { headers: this.headers, maxPayload: 1 << 22 }); | |
| 303 | this.machineWs = ws; | |
| 304 | const now = () => Date.now() - this.machine.skew; | |
| 305 | let waiting = false; | |
| 306 | ws.on("message", (data, binary) => { | |
| 307 | if (binary) return; | |
| 308 | let m: Frame; | |
| 309 | try { | |
| 310 | m = JSON.parse(String(data)) as Frame; | |
| 311 | } catch { | |
| 312 | return; | |
| 313 | } | |
| 314 | if (typeof m !== "object" || m === null) return; | |
| 315 | const object = (x: unknown) => (x && typeof x === "object" && !Array.isArray(x) ? (x as Record<string, unknown>) : null); | |
| 316 | if (m.type === "hello" || m.type === "status") { | |
| 317 | this.machine.status = object(m.status) ?? this.machine.status; | |
| 318 | this.machine.link = object(m.link) ?? this.machine.link; | |
| 319 | this.machine.room = object(m.room) ?? this.machine.room; | |
| 320 | } | |
| 321 | if (m.type === "status" && waiting && this.machine.status) { | |
| 322 | // The feed had no status yet when it opened (the arm's watch was only just asked): the panel comes with the first. | |
| 323 | waiting = false; | |
| 324 | for (const line of machineLines(this.machine)) this.print(line); | |
| 325 | } | |
| 326 | if (m.type === "hello") { | |
| 327 | if (typeof m.now === "number") this.machine.skew = Date.now() - m.now; | |
| 328 | waiting = !this.machine.status; | |
| 329 | if (waiting) this.print("· waiting for the arm's first status"); | |
| 330 | else for (const line of machineLines(this.machine)) this.print(line); | |
| 331 | const log = Array.isArray(m.log) ? m.log.slice(-20) : []; | |
| 332 | for (const e of log) { | |
| 333 | const line = machineEntry(e, now()); | |
| 334 | if (line) this.print(line); | |
| 335 | } | |
| 336 | this.print("· the log follows as it happens; /machine shows the joints again, /machine off stops"); | |
| 337 | } else if (m.type === "log" && Array.isArray(m.entries)) { | |
| 338 | for (const e of m.entries) { | |
| 339 | const line = machineEntry(e, now()); | |
| 340 | if (line) this.print(line); | |
| 341 | } | |
| 342 | } | |
| 343 | }); | |
| 344 | ws.on("error", () => this.print("the machine feed is not answering")); | |
| 345 | ws.on("close", () => { | |
| 346 | if (this.machineWs === ws) this.machineWs = null; | |
| 347 | }); | |
| 252 | 348 | } |
| 253 | 349 | |
| 254 | 350 | private send(frame: Frame): void { |
Software/so101/src/ui/machine-panel.js added +157
| @@ -0,0 +1,157 @@ | ||
| 1 | // @ts-check | |
| 2 | /** | |
| 3 | * The Machine tab on the page: the joints, the link, the server and the log, from /machine behind the relay or the | |
| 4 | * arm server's own /watch. Loaded the first time the tab opens, so a first visit never pays for it; its words come | |
| 5 | * from ./machine.js, the same the terminal prints. Everything goes in with textContent. | |
| 6 | */ | |
| 7 | import { copyText, entryLine, jointRows, linkRows, stateRows } from "./machine.js"; | |
| 8 | ||
| 9 | const KEEP = 500; | |
| 10 | /** The page's document and navigator: this module only runs there (the type check has no DOM, as for src/ui/drive.js). @type {any} */ | |
| 11 | const doc = /** @type {any} */ (globalThis).document; | |
| 12 | const nav = /** @type {any} */ (globalThis).navigator; | |
| 13 | const STYLE = ` | |
| 14 | .mwrap { overflow-x: auto; margin: 0 -4px; } | |
| 15 | .mjoints { border-collapse: collapse; font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; width: 100%; } | |
| 16 | .mjoints th, .mjoints td { padding: 4px 6px; border-bottom: 1px solid var(--line); text-align: right; } .mjoints th { color: var(--dim); font-weight: 500; } | |
| 17 | .mjoints th:first-child, .mjoints td:first-child { text-align: left; } .mjoints td.off { color: var(--dim); } | |
| 18 | .kv { display: grid; grid-template-columns: max-content 1fr; gap: 2px 12px; font-size: 13px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; } .kv b { color: var(--dim); font-weight: 500; } | |
| 19 | .mlog { font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; min-height: 160px; max-height: 50svh; overflow: auto; overscroll-behavior: contain; background: var(--raised); border: 1px solid var(--line); border-radius: 8px; padding: 4px 8px; } | |
| 20 | .mlog div { display: grid; grid-template-columns: 6ch 7ch minmax(0, 1fr); gap: 8px; } .mlog div span:last-child { overflow-wrap: anywhere; } | |
| 21 | .mlog .age, .mlog .seq { color: var(--dim); text-align: right; } .mlog .clamp { color: var(--warn); } .mlog .state { color: var(--link); } .mlog .received { color: var(--fg2); } | |
| 22 | .mlog:empty::after { content: "Nothing yet."; color: var(--dim); } | |
| 23 | .mlive { color: var(--dim); font-size: 12px; }`; | |
| 24 | const COLUMNS = [["joint"], ["ticks"], ["degrees"], ["target"], ["load"], ["temp"], ["torque"], ["limits", "the servo's calibrated range"], ["bounds", "where commands are held inside"]]; | |
| 25 | ||
| 26 | /** | |
| 27 | * @param {string} tag | |
| 28 | * @param {Record<string, unknown>} [props] | |
| 29 | * @param {...any} children | |
| 30 | * @returns {any} | |
| 31 | */ | |
| 32 | const el = (tag, props = {}, ...children) => { const e = Object.assign(doc.createElement(tag), props); e.append(...children); return e; }; | |
| 33 | ||
| 34 | export class MachinePanel { | |
| 35 | /** | |
| 36 | * @param {any} root the tab: the panel is built inside it, after what is there | |
| 37 | * @param {{ url: string, direct: boolean, msg: (text: string, bad?: boolean) => void }} options | |
| 38 | */ | |
| 39 | constructor(root, options) { | |
| 40 | this.options = options; | |
| 41 | /** @type {WebSocket | null} */ | |
| 42 | this.ws = null; | |
| 43 | /** @type {Array<{ seq: number, t: number, kind: string, what: string, detail?: Record<string, unknown> }>} */ | |
| 44 | this.log = []; | |
| 45 | this.paused = false; | |
| 46 | this.skew = 0; | |
| 47 | /** @type {ReturnType<typeof setTimeout> | undefined} */ | |
| 48 | this.retry = undefined; | |
| 49 | /** @type {ReturnType<typeof setInterval> | undefined} */ | |
| 50 | this.ages = undefined; | |
| 51 | doc.head.append(el("style", { textContent: STYLE })); | |
| 52 | const head = el("tr", {}, ...COLUMNS.map(([name, title]) => el("th", { scope: "col", textContent: name, ...(title ? { title } : {}) }))); | |
| 53 | this.body = el("tbody"); | |
| 54 | this.link = el("div", { className: "kv" }); | |
| 55 | this.state = el("div", { className: "kv" }); | |
| 56 | this.live = el("span", { className: "mlive", ariaLive: "polite" }); | |
| 57 | this.box = el("div", { className: "mlog", role: "log", ariaLabel: "Commands sent and answers received" }); | |
| 58 | this.pause = el("button", { textContent: "Pause", onclick: () => this.toggle() }); | |
| 59 | this.pause.setAttribute("aria-pressed", "false"); | |
| 60 | const copy = el("button", { textContent: "Copy", onclick: () => this.copy() }); | |
| 61 | root.append( | |
| 62 | el("h2", { textContent: "Joints" }), el("div", { className: "mwrap" }, el("table", { className: "mjoints" }, el("thead", {}, head), this.body)), | |
| 63 | el("h2", { textContent: "Link" }), this.link, | |
| 64 | el("h2", { textContent: "Server" }), this.state, | |
| 65 | el("h2", { textContent: "Commands in and out" }), el("div", { className: "row" }, this.pause, copy, this.live), this.box, | |
| 66 | ); | |
| 67 | } | |
| 68 | ||
| 69 | open() { | |
| 70 | if (this.ws) return; | |
| 71 | clearTimeout(this.retry); | |
| 72 | const ws = new WebSocket(this.options.url); | |
| 73 | this.ws = ws; | |
| 74 | this.live.textContent = "connecting…"; | |
| 75 | ws.onopen = () => (this.live.textContent = "live"); | |
| 76 | ws.onmessage = (e) => { try { this.take(JSON.parse(e.data)); } catch { /* not ours */ } }; | |
| 77 | ws.onclose = () => { | |
| 78 | if (this.ws !== ws) return; | |
| 79 | this.ws = null; | |
| 80 | this.live.textContent = "disconnected · retrying"; | |
| 81 | this.retry = setTimeout(() => this.open(), 1500); | |
| 82 | }; | |
| 83 | this.ages ??= setInterval(() => this.refreshAges(), 1000); | |
| 84 | } | |
| 85 | ||
| 86 | close() { | |
| 87 | const ws = this.ws; this.ws = null; ws?.close(); | |
| 88 | clearTimeout(this.retry); clearInterval(this.ages); this.ages = undefined; | |
| 89 | } | |
| 90 | ||
| 91 | /** @param {any} m */ | |
| 92 | take(m) { | |
| 93 | if (m.type === "hello") { this.skew = Date.now() - m.now; this.log = []; this.box.replaceChildren(); this.add(m.log ?? []); this.show(m.status, m.link, m.room); } | |
| 94 | else if (m.type === "status") this.show(m.status, m.link, m.room); | |
| 95 | else if (m.type === "log") this.add(m.entries ?? []); | |
| 96 | else if (Array.isArray(m.joints)) this.show(m, null, null); // the arm server's own /watch | |
| 97 | else if (Array.isArray(m.machine)) this.add(m.machine); | |
| 98 | } | |
| 99 | ||
| 100 | /** @param {any} status @param {any} link @param {any} room */ | |
| 101 | show(status, link, room) { | |
| 102 | /** @param {any} box @param {Array<[string, string]>} rows */ | |
| 103 | const kv = (box, rows) => box.replaceChildren(...rows.flatMap(([k, v]) => [el("b", { textContent: k }), el("span", { textContent: v })])); | |
| 104 | if (status) { | |
| 105 | const rows = jointRows(status); | |
| 106 | while (this.body.rows.length > rows.length) this.body.deleteRow(-1); | |
| 107 | rows.forEach((r, i) => { | |
| 108 | const tr = this.body.rows[i] ?? this.body.insertRow(); | |
| 109 | const cells = [r.name, r.ticks, r.degrees, r.target, r.load, r.temperature, r.torque, r.limits, r.bounds]; | |
| 110 | while (tr.cells.length < cells.length) tr.insertCell(); | |
| 111 | cells.forEach((text, c) => { if (tr.cells[c].textContent !== text) tr.cells[c].textContent = text; }); | |
| 112 | tr.cells[6].className = r.torque === "on" ? "" : "off"; | |
| 113 | }); | |
| 114 | } | |
| 115 | if (link || this.options.direct) kv(this.link, link ? linkRows(link) : [["arm", "this server, directly"]]); | |
| 116 | kv(this.state, stateRows(status, room)); | |
| 117 | } | |
| 118 | ||
| 119 | now() { return Date.now() - this.skew; } | |
| 120 | ||
| 121 | /** @param {any[]} entries */ | |
| 122 | add(entries) { | |
| 123 | this.log.push(...entries); | |
| 124 | if (this.log.length > KEEP) this.log.splice(0, this.log.length - KEEP); | |
| 125 | if (!this.paused) this.draw(entries); | |
| 126 | } | |
| 127 | ||
| 128 | /** @param {any[]} entries */ | |
| 129 | draw(entries) { | |
| 130 | const now = this.now(); | |
| 131 | this.box.append(...entries.map((e) => { | |
| 132 | const line = entryLine(e, now); | |
| 133 | const row = el("div", { className: line.kind }, el("span", { className: "seq", textContent: line.seq }), el("span", { className: "age", textContent: line.age }), el("span", { textContent: line.text })); | |
| 134 | row.dataset.t = String(e.t); | |
| 135 | return row; | |
| 136 | })); | |
| 137 | while (this.box.childElementCount > KEEP) this.box.firstElementChild?.remove(); | |
| 138 | this.box.scrollTop = this.box.scrollHeight; | |
| 139 | } | |
| 140 | ||
| 141 | refreshAges() { | |
| 142 | if (this.paused) return; | |
| 143 | const now = this.now(); | |
| 144 | for (const row of this.box.children) row.children[1].textContent = entryLine({ seq: 0, t: Number(row.dataset.t), kind: "", what: "" }, now).age; | |
| 145 | } | |
| 146 | ||
| 147 | toggle() { | |
| 148 | this.paused = !this.paused; | |
| 149 | this.pause.textContent = this.paused ? "Resume" : "Pause"; this.pause.setAttribute("aria-pressed", String(this.paused)); | |
| 150 | if (!this.paused) { this.box.replaceChildren(); this.draw(this.log); } | |
| 151 | } | |
| 152 | ||
| 153 | async copy() { | |
| 154 | try { await nav.clipboard.writeText(copyText(this.log)); this.options.msg(`copied ${this.log.length} lines`); } | |
| 155 | catch { this.options.msg("this browser would not copy; select the log and copy it by hand", true); } | |
| 156 | } | |
| 157 | } |
Software/so101/src/ui/machine.js added +110
| @@ -0,0 +1,110 @@ | ||
| 1 | // @ts-check | |
| 2 | /** | |
| 3 | * The Machine panel's words: the arm's raw state, the link and the log as plain text, for the page to put in with | |
| 4 | * textContent. Nothing is rounded away or made friendly: ticks are the servo's ticks, the load its percent, the log | |
| 5 | * every entry the feed (/machine, src/machine-feed.ts) sent. | |
| 6 | * @typedef {{ id: number, joint?: string | null, position?: number | null, degrees?: number | null, load?: number | null, | |
| 7 | * temperature?: number | null, torque?: boolean | null, target?: number | null, min?: number | null, max?: number | null, | |
| 8 | * lo?: number | null, hi?: number | null }} Joint | |
| 9 | * @typedef {{ seq: number, t: number, kind: string, what: string, detail?: Record<string, unknown> }} Entry | |
| 10 | */ | |
| 11 | ||
| 12 | const DASH = "—"; | |
| 13 | const TICKS = 4096; | |
| 14 | ||
| 15 | /** @param {unknown} n */ | |
| 16 | const num = (n) => typeof n === "number" && Number.isFinite(n); | |
| 17 | /** Degrees from ticks, as the arm server counts them: 0 at tick 0, 360 at a full turn. @param {number} ticks */ | |
| 18 | export const degrees = (ticks) => `${((ticks * 360) / TICKS).toFixed(1)}°`; | |
| 19 | ||
| 20 | /** | |
| 21 | * One row per joint. | |
| 22 | * @param {{ joints?: Joint[] } | null | undefined} status | |
| 23 | */ | |
| 24 | export function jointRows(status) { | |
| 25 | return (status?.joints ?? []).map((j) => ({ | |
| 26 | id: String(j.id), | |
| 27 | name: j.joint ?? `servo ${j.id}`, | |
| 28 | ticks: num(j.position) ? String(j.position) : DASH, | |
| 29 | degrees: num(j.degrees) ? `${/** @type {number} */ (j.degrees).toFixed(1)}°` : num(j.position) ? degrees(/** @type {number} */ (j.position)) : DASH, | |
| 30 | target: num(j.target) ? `${j.target} (${degrees(/** @type {number} */ (j.target))})` : DASH, | |
| 31 | load: num(j.load) ? `${j.load}%` : DASH, | |
| 32 | temperature: num(j.temperature) ? `${j.temperature} °C` : DASH, | |
| 33 | torque: j.torque === true ? "on" : j.torque === false ? "off" : DASH, | |
| 34 | limits: num(j.min) && num(j.max) ? `${j.min}–${j.max}` : DASH, | |
| 35 | bounds: num(j.lo) && num(j.hi) ? `${j.lo}–${j.hi}` : DASH, | |
| 36 | })); | |
| 37 | } | |
| 38 | ||
| 39 | /** | |
| 40 | * The link to the arm, label and value. | |
| 41 | * @param {{ mode?: string, host?: string | null, problem?: string | null, rttMs?: number | null, fps?: number, reconnects?: number } | null | undefined} link | |
| 42 | * @returns {Array<[string, string]>} | |
| 43 | */ | |
| 44 | export function linkRows(link) { | |
| 45 | return [ | |
| 46 | ["arm", link?.mode ? `${link.mode}${link.host ? ` · ${link.host}` : ""}` : DASH], | |
| 47 | ["round trip", num(link?.rttMs) ? `${link?.rttMs} ms` : DASH], | |
| 48 | ["status frames", num(link?.fps) ? `${link?.fps}/s` : DASH], | |
| 49 | ["reconnects", num(link?.reconnects) ? String(link?.reconnects) : DASH], | |
| 50 | ...(link?.problem ? /** @type {Array<[string, string]>} */ ([["problem", link.problem]]) : []), | |
| 51 | ]; | |
| 52 | } | |
| 53 | ||
| 54 | /** | |
| 55 | * Who and what holds the arm, label and value. | |
| 56 | * @param {{ driving?: string | null, held?: boolean, estop?: { by: string, at: string } | null, jammed?: number[], blocked?: { what: string, link: string } | null, zone?: string } | null | undefined} status | |
| 57 | * @param {{ driver?: string | null, paused?: boolean, speedCapPercent?: number } | null | undefined} room | |
| 58 | * @returns {Array<[string, string]>} | |
| 59 | */ | |
| 60 | export function stateRows(status, room) { | |
| 61 | return [ | |
| 62 | ["turn", room?.driver ?? "nobody"], | |
| 63 | ["driving", status ? status.driving ?? "nothing (idle)" : DASH], | |
| 64 | ["held", status ? (status.held ? "yes: dead-man hold, no frame lately" : "no") : DASH], | |
| 65 | ["E-stop", status?.estop ? `ON · ${status.estop.by} · ${status.estop.at}` : status ? "off" : DASH], | |
| 66 | ["zone", status?.zone ?? DASH], | |
| 67 | ["blocked", status?.blocked ? `${status.blocked.link} · ${status.blocked.what}` : "no"], | |
| 68 | ["jammed", status?.jammed?.length ? status.jammed.join(", ") : "no"], | |
| 69 | ["speed cap", num(room?.speedCapPercent) ? `${room?.speedCapPercent}%` : DASH], | |
| 70 | ["queue", room?.paused ? "paused" : "open"], | |
| 71 | ]; | |
| 72 | } | |
| 73 | ||
| 74 | /** How long ago, short. @param {number} ms */ | |
| 75 | export function age(ms) { | |
| 76 | if (!(ms >= 0)) return "0 ms"; | |
| 77 | if (ms < 1000) return `${Math.round(ms)} ms`; | |
| 78 | if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`; | |
| 79 | if (ms < 3_600_000) return `${Math.floor(ms / 60_000)} min`; | |
| 80 | return `${Math.floor(ms / 3_600_000)} h`; | |
| 81 | } | |
| 82 | ||
| 83 | /** A detail value as text: a map of servo id → ticks reads "1:2048 2:2050". @param {unknown} v */ | |
| 84 | function value(v) { | |
| 85 | if (v && typeof v === "object") return Object.entries(v).map(([k, n]) => `${k}:${n}`).join(" ") || "{}"; | |
| 86 | return String(v); | |
| 87 | } | |
| 88 | ||
| 89 | /** | |
| 90 | * One log entry as the panel shows it. | |
| 91 | * @param {Entry} e | |
| 92 | * @param {number} now | |
| 93 | */ | |
| 94 | export function entryLine(e, now) { | |
| 95 | const d = e.detail ?? {}; | |
| 96 | const parts = Object.entries(d).filter(([k]) => k !== "armSeq").map(([k, v]) => (k === "values" ? value(v) : `${k}=${value(v)}`)); | |
| 97 | const arrow = e.kind === "sent" ? "→" : e.kind === "received" ? "←" : e.kind === "clamp" ? "⚠" : "•"; | |
| 98 | return { seq: `#${e.seq}`, age: age(now - e.t), kind: e.kind, text: `${arrow} ${e.what}${parts.length ? ` ${parts.join(" ")}` : ""}${num(d.armSeq) ? ` (arm #${d.armSeq})` : ""}` }; | |
| 99 | } | |
| 100 | ||
| 101 | /** | |
| 102 | * The log as text to paste somewhere: one line per entry, tab-separated, with the time in UTC. | |
| 103 | * @param {Entry[]} entries | |
| 104 | */ | |
| 105 | export function copyText(entries) { | |
| 106 | return entries.map((e) => { | |
| 107 | const line = entryLine(e, e.t); | |
| 108 | return [line.seq, new Date(e.t).toISOString(), e.kind, line.text].join("\t"); | |
| 109 | }).join("\n"); | |
| 110 | } |
Software/so101/src/ui/machine.test.ts added +28
| @@ -0,0 +1,28 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { age, copyText, entryLine, jointRows, linkRows, stateRows } from "./machine.js"; | |
| 3 | ||
| 4 | describe("the Machine panel's text", () => { | |
| 5 | test("a joint reads as the servo reports it; what is unknown is a dash", () => { | |
| 6 | expect(jointRows({ joints: [{ id: 3, joint: "elbow_flex", position: 2048, degrees: 180, load: 4.5, temperature: 33, torque: false, target: 1024, min: 900, max: 3100, lo: 930, hi: 3070 }, { id: 9 }] })).toEqual([ | |
| 7 | { id: "3", name: "elbow_flex", ticks: "2048", degrees: "180.0°", target: "1024 (90.0°)", load: "4.5%", temperature: "33 °C", torque: "off", limits: "900–3100", bounds: "930–3070" }, | |
| 8 | { id: "9", name: "servo 9", ticks: "—", degrees: "—", target: "—", load: "—", temperature: "—", torque: "—", limits: "—", bounds: "—" }, | |
| 9 | ]); | |
| 10 | expect(jointRows(null)).toEqual([]); | |
| 11 | }); | |
| 12 | ||
| 13 | test("the link and the server state", () => { | |
| 14 | expect(linkRows({ mode: "reconnecting", host: "pi:8101", problem: "pi:8101 unreachable (ECONNREFUSED)", rttMs: 17.4, fps: 4, reconnects: 2 })).toEqual([ | |
| 15 | ["arm", "reconnecting · pi:8101"], ["round trip", "17.4 ms"], ["status frames", "4/s"], ["reconnects", "2"], ["problem", "pi:8101 unreachable (ECONNREFUSED)"], | |
| 16 | ]); | |
| 17 | const rows = Object.fromEntries(stateRows({ driving: "stream", held: true, estop: { by: "ana", at: "2026-10-20T22:00:00.000Z" }, jammed: [2], zone: "enforce" }, { driver: "ana", paused: true, speedCapPercent: 40 })); | |
| 18 | expect(rows).toEqual({ turn: "ana", driving: "stream", held: "yes: dead-man hold, no frame lately", "E-stop": "ON · ana · 2026-10-20T22:00:00.000Z", zone: "enforce", blocked: "no", jammed: "2", "speed cap": "40%", queue: "paused" }); | |
| 19 | }); | |
| 20 | ||
| 21 | test("log lines: arrow, what, detail, age; copy is one tab-separated line each, in UTC", () => { | |
| 22 | const sent = { seq: 7, t: 1_000, kind: "sent", what: "Goal_Position", detail: { values: { 1: 2048, 2: 2050 }, armSeq: 3 } }; | |
| 23 | expect(entryLine(sent, 1_250)).toEqual({ seq: "#7", age: "250 ms", kind: "sent", text: "→ Goal_Position 1:2048 2:2050 (arm #3)" }); | |
| 24 | expect(entryLine({ seq: 8, t: 0, kind: "received", what: "POST /move", detail: { status: 409 } }, 2_500).text).toBe("← POST /move status=409"); | |
| 25 | expect(age(61_000)).toBe("1 min"); | |
| 26 | expect(copyText([sent])).toBe("#7\t1970-01-01T00:00:01.000Z\tsent\t→ Goal_Position 1:2048 2:2050 (arm #3)"); | |
| 27 | }); | |
| 28 | }); |
Software/so101/src/viewer.html +16
| @@ -443,11 +443,15 @@ | ||
| 443 | 443 | </div> |
| 444 | 444 | <div class="row"><button id="metricsBtn">Metrics</button><button id="calib">3D calibration</button></div> |
| 445 | 445 | </div> |
| 446 | <div class="tab" id="tab-machine" role="tabpanel" aria-labelledby="t-machine" hidden> | |
| 447 | <p class="note">The arm as its servos report it, and every command on its way in and out, pushed as it happens. Read-only.</p> | |
| 448 | </div> | |
| 446 | 449 | <nav id="tabs" role="tablist" aria-label="Sheet"> |
| 447 | 450 | <button role="tab" id="t-chat" data-tab="chat" aria-controls="tab-chat" aria-selected="true">Chat<span class="badge" id="unread"></span></button> |
| 448 | 451 | <button role="tab" id="t-queue" data-tab="queue" aria-controls="tab-queue" aria-selected="false">Queue<span class="badge" id="waiting"></span></button> |
| 449 | 452 | <button role="tab" id="t-controls" data-tab="controls" aria-controls="tab-controls" aria-selected="false" hidden>Controls</button> |
| 450 | 453 | <button role="tab" id="t-admin" data-tab="admin" aria-controls="tab-admin" aria-selected="false" hidden>Admin</button> |
| 454 | <button role="tab" id="t-machine" data-tab="machine" aria-controls="tab-machine" aria-selected="false">Machine</button> | |
| 451 | 455 | </nav> |
| 452 | 456 | </section> |
| 453 | 457 | |
| @@ -544,6 +548,8 @@ | ||
| 544 | 548 | $("sheetToggle").onclick = () => setBare(!shell.classList.contains("bare")); |
| 545 | 549 | const sideways = matchMedia("(orientation: landscape) and (max-height: 500px)"); |
| 546 | 550 | let tab = "chat"; |
| 551 | /** The Machine tab's panel, once it is loaded (below); here, because leaving any tab closes it. */ | |
| 552 | const machine = { panel: null }; | |
| 547 | 553 | function showTab(name, focus = false) { |
| 548 | 554 | if ($(`t-${name}`).hidden) name = ["controls", "chat", "admin"].find((t) => !$(`t-${t}`).hidden) ?? "chat"; |
| 549 | 555 | tab = name; |
| @@ -556,6 +562,7 @@ | ||
| 556 | 562 | if (name === "chat") { $("unread").textContent = ""; chatBox.scrollTop = chatBox.scrollHeight; } |
| 557 | 563 | if (name === "controls") load3D(); |
| 558 | 564 | if (name === "admin") loadSettings(); |
| 565 | if (name === "machine") machineOpen(); else machineClose(); | |
| 559 | 566 | } |
| 560 | 567 | for (const b of $("tabs").querySelectorAll("[role=tab]")) b.onclick = () => showTab(b.dataset.tab); |
| 561 | 568 | $("tabs").addEventListener("keydown", (e) => { |
| @@ -1831,6 +1838,15 @@ | ||
| 1831 | 1838 | } catch (err) { console.error(err); msg("the calibration panel did not load", true); } |
| 1832 | 1839 | }; |
| 1833 | 1840 | |
| 1841 | // ---------------------------------------------------------------- the machine: raw state, the link, every command in and out | |
| 1842 | // src/ui/machine-panel.js, fetched the first time the tab opens; it reads /machine behind the relay, or the arm server's /watch. | |
| 1843 | async function machineOpen() { | |
| 1844 | try { machine.panel ??= new (await import("/ui/__VERSION__/machine-panel.js")).MachinePanel($("tab-machine"), { url: `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/${relayed ? "machine" : "watch"}`, direct: !relayed, msg }); } | |
| 1845 | catch { return msg("the Machine panel did not load; open the tab again", true); } | |
| 1846 | if (tab === "machine") machine.panel.open(); | |
| 1847 | } | |
| 1848 | function machineClose() { machine.panel?.close(); } | |
| 1849 | ||
| 1834 | 1850 | // ---------------------------------------------------------------- live status, sliders and jog |
| 1835 | 1851 | const joints = $("joints"); |
| 1836 | 1852 | const built = new Map(); |
new above
offline