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

Merged opened this in answer to

Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.

Merged

vesper/arm:vesper/67-the-machine-not-a-magic-box-a-machine-pa → main 3 commits fork

  • Merged. vesper/67-the-machine-not-a-magic-box-a-machine-pa was merged into main as 21032a6.

Review

Sign in to review this change.
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
135135 `/recording/delete`, `/play`;
136136 `PUT /calibration/camera|handeye`; the WebSocket `/follow` taking
137137 `{"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
139143 goes through the joint supervisor; `/stop` ends a move, a playback, a
140144 recording, or a stream, and the arm holds. The stream is clamped to the
141145 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
266270 stream) are only accepted from the app's own page, so another site can't
267271 drive the arm through it.
268272
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
269306 **Drive with your own leader arm.** Plug an SO-101 leader (its
270307 bus board on USB, and on its own power supply) into the computer or Android
271308 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 `/`:
384421 - `/end [name]`, owner: end that turn (no name: whoever drives), or take
385422 them out of the line.
386423 - `/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.
387429 - `/who` (who drives, who waits), `/help`, `/quit`.
388430
389431 The terminal is a client of the running server, like the page: it opens
Software/so101/src/bus.ts +5 −1
@@ -81,6 +81,8 @@ export class FeetechBus {
8181 #echo: boolean;
8282 #echoPending = false;
8383 #failure: 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;
8486
8587 constructor(transport: Transport, { echo = false }: BusOptions = {}) {
8688 this.#port = transport;
@@ -191,8 +193,10 @@ export class FeetechBus {
191193
192194 /** Write the same register on many servos in one bus transaction. No status comes back. */
193195 async syncWrite(register: Register, values: Iterable<readonly [number, number]>): Promise<void> {
196 const list = [...values];
197 this.onSyncWrite?.(register, list);
194198 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));
196200 await this.#transact(encodeInstruction(BROADCAST_ID, Instruction.SyncWrite, params), [], 0);
197201 }
198202
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: Status | null = null;
70 #signature = "";
71 #driver: 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 #armRun = "";
74 #armSeq = 0;
75 readonly #wss = new WebSocketServer({ noServer: true, maxPayload: 256 });
76 readonly #o: MachineFeedOptions;
77 readonly #unsubscribe: () => void;
78
79 constructor(o: MachineFeedOptions) {
80 this.#o = o;
81 this.log = o.log ?? new MachineLog();
82 this.#unsubscribe = this.log.subscribe((entries) => this.#send({ type: "log", entries }, false));
83 this.#wss.on("connection", (ws: WebSocket) => {
84 ws.on("error", () => ws.terminate());
85 ws.on("close", () => this.#o.onViewers?.(this.#wss.clients.size));
86 ws.send(JSON.stringify({ type: "hello", now: Date.now(), log: this.log.recent(HELLO_ENTRIES), status: this.#status, link: o.link(), room: o.room() }));
87 this.#o.onViewers?.(this.#wss.clients.size);
88 });
89 }
90
91 get viewers(): number {
92 return this.#wss.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 = status;
103 const room = this.#o.room();
104 if (room.driver !== this.#driver) {
105 if (this.#driver !== undefined) this.log.note("state", "turn", { driver: room.driver });
106 this.#driver = room.driver;
107 }
108 const sig = signature(status);
109 if (sig !== this.#signature) {
110 this.#signature = sig;
111 this.log.note("received", "status", { positions: positions(status), driving: typeof status.driving === "string" ? status.driving : null });
112 }
113 if (this.#wss.clients.size) this.#send({ type: "status", status, link: this.#o.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.#armRun) {
119 this.#armRun = run;
120 this.#armSeq = 0;
121 }
122 for (const e of entries) {
123 if (e.seq <= this.#armSeq) continue;
124 this.#armSeq = 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.#wss.handleUpgrade(req, socket, head, (ws) => this.#wss.emit("connection", ws, req));
131 }
132
133 close(): void {
134 this.#unsubscribe();
135 for (const ws of this.#wss.clients) ws.terminate();
136 this.#wss.close();
137 }
138
139 #send(message: unknown, droppable: boolean) {
140 if (!this.#wss.clients.size) return;
141 const text = JSON.stringify(message);
142 for (const ws of this.#wss.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 #seq = 0;
36 readonly #entries: MachineEntry[] = [];
37 readonly #listeners = new Set<(batch: readonly MachineEntry[]) => void>();
38 readonly #flushMs: number;
39 #pending: MachineEntry[] = [];
40 #timer: ReturnType<typeof setTimeout> | undefined;
41
42 constructor({ size = 500, flushMs = 50 }: { size?: number; flushMs?: number } = {}) {
43 this.size = size;
44 this.#flushMs = flushMs;
45 }
46
47 /** The last sequence number given out; 0 before the first entry. */
48 get seq(): number {
49 return this.#seq;
50 }
51
52 note(kind: EntryKind, what: string, detail: Record<string, DetailValue> = {}, t = Date.now()): MachineEntry {
53 const entry: MachineEntry = { seq: ++this.#seq, t, kind, what: what.slice(0, MAX_WHAT), detail };
54 this.#entries.push(entry);
55 if (this.#entries.length > this.size) this.#entries.shift();
56 if (this.#listeners.size) {
57 this.#pending.push(entry);
58 this.#timer ??= setTimeout(() => this.#flush(), this.#flushMs);
59 }
60 return entry;
61 }
62
63 /** The last `n` entries, oldest first. */
64 recent(n = this.size): MachineEntry[] {
65 return this.#entries.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.#listeners.add(listener);
71 return () => {
72 this.#listeners.delete(listener);
73 if (!this.#listeners.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.#timer);
80 this.#timer = undefined;
81 this.#pending = [];
82 }
83
84 #flush() {
85 this.#timer = undefined;
86 const batch = this.#pending;
87 this.#pending = [];
88 if (batch.length) for (const listener of this.#listeners) 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 @@
2222 * The owner's speed cap (src/speed-cap.ts) is applied here too, to moves, poses, grips, playbacks and every stream frame.
2323 *
2424 * 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)
2527 * POST /join {"name": "…"}: become someone here, no forge account needed (src/accounts.ts); the answer
2628 * sets the HttpOnly session cookie and names you: {"you": {"id", "name", "owner"}}
2729 * 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";
4547 import { pipeline } from "node:stream/promises";
4648 import WebSocket, { WebSocketServer } from "ws";
4749 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";
4853 import { acceptsGzip, GzipCache, worthCompressing } from "./compress.ts";
4954 import { AccountError, sessionCookie, visitor } from "./accounts.ts";
5055 import { AdminError, changeFromForm } from "./admin.ts";
@@ -212,6 +217,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
212217
213218 // ------------------------------------------------------------------ the link
214219 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;
215222 let problem: string | null = options.problem ?? null;
216223 /** Requests in flight to the arm server: cut when the link drops, so nothing waits on a dead one. */
217224 const inFlight = new Set<AbortController>();
@@ -224,6 +231,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
224231 remote,
225232 open: (url, timeoutMs) => open(url, timeoutMs),
226233 timings: options.link,
234 onStatus: (status) => onArm() && machine.status(status),
235 onMachine: (entries, run) => onArm() && machine.arm(entries, run),
227236 onChange: (state, previous) => {
228237 if (state === "live") console.log(`arm server ${host}: live`);
229238 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> {
246255 /** Whether the arm server, not the simulation, is the arm right now: live, or only briefly gone. */
247256 const onArm = () => mode() === "live" || mode() === "reconnecting";
248257 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 });
249280 const source = () => {
250281 const m = mode();
251282 if (m === "live") return `live ${remote!.host}`;
@@ -591,14 +622,25 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
591622 // 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.
592623 const raw = reading || route === "POST /estop" || route === "POST /estop/clear" ? undefined : await readBody(req);
593624 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 }
595633 if (mode() === "reconnecting" && !reading && !STOPS.has(route)) {
634 machine.note("clamp", "not passed on", { route, why: RECONNECTING });
596635 return json(res, 503, { error: `${RECONNECTING} at ${remote.host}…; driving resumes when it answers`, reconnecting: true });
597636 }
598637 try {
599638 // 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);
601642 } catch (err) {
643 if (logged) machine.note("received", route, { error: reason(err) });
602644 return json(res, mode() === "reconnecting" ? 503 : 502, { error: `the arm server at ${remote.host} did not answer (${reason(err)})`, reconnecting: mode() === "reconnecting" });
603645 }
604646 } catch (err) {
@@ -663,22 +705,30 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
663705 .finally(() => (asking = false));
664706 };
665707 seed();
708 /** A frame as the panel shows it: servo id → ticks. */
709 const values = (text: string) => perServo(parseFrame(text) ?? []);
666710 browser.on("message", (data, binary) => {
667711 if (driver !== null) {
668712 // 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" });
670714 lobby?.activity(driver);
671715 }
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 });
673718 const percent = lobby?.maxSpeedPercent ?? 100;
719 const text = String(data);
674720 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) });
676723 arm.send(data, { binary });
677724 return;
678725 }
679726 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);
682732 });
683733 arm.on("close", (code, why) => browser.close(sendable(code) ? code : 1011, why.length ? why.toString() : "the arm server went away"));
684734 // 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> {
699749 };
700750 http.on("upgrade", (req: IncomingMessage, socket: Duplex, head: Buffer) => {
701751 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");
703753 if (!sameOrigin(req)) return refuse(socket, "403 Forbidden");
704754 socket.on("error", () => socket.destroy());
705755 if (url.pathname === "/live") return lobby!.upgrade(req, socket, head);
756 if (url.pathname === "/machine") return machine.upgrade(req, socket, head);
706757 let driver: string | null = null;
707758 if (lobby) {
708759 const who = lobby.who(req);
@@ -769,6 +820,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
769820 turnEnded?.();
770821 arrived?.();
771822 armLink?.close();
823 simLink?.close();
824 machine.close();
772825 if (!options.cameras) cameras.close();
773826 for (const c of inFlight) c.abort();
774827 for (const client of wss.clients) client.terminate();
Software/so101/src/server.test.ts +3 −2
@@ -147,10 +147,11 @@ describe("viewer page", () => {
147147 bytes += gzipSync(Buffer.from(await r.arrayBuffer()), { level: 6 }).length;
148148 }
149149 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);
152152 expect(script).toContain('import("/leader-map.js")');
153153 expect(script).toMatch(/import\("\/ui\/[0-9a-f]{12}\/calibration\.js"\)/);
154 expect(script).toMatch(/import\("\/ui\/[0-9a-f]{12}\/machine-panel\.js"\)/);
154155 });
155156
156157 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 @@
3333 * GET /printables the sheets to print for the vision quest (board, cube markers, gripper marker); GET /printables/<file>
3434 * WS /follow client sends {"1": ticks, "2": ticks, ...} frames; the server drives the arm
3535 * 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.
3740 *
3841 * One thing drives the arm at a time. Every target is pulled inside the joint limits and every motion held to the speed and
3942 * 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,
4649 import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
4750 import { dirname, extname, join, resolve } from "node:path";
4851 import type { Duplex } from "node:stream";
49 import { createHash } from "node:crypto";
52 import { createHash, randomUUID } from "node:crypto";
5053 import { fileURLToPath } from "node:url";
5154 import { WebSocketServer, type WebSocket } from "ws";
5255 import { browserModule } from "./browser-modules.ts";
5356 import type { FeetechBus } from "./bus.ts";
5457 import { ArmModel, gripperTicksToRadians, ticksToRadians, type Violation } from "./kinematics.ts";
5558 import { clamp, type Frame } from "./mapping.ts";
59 import { MachineLog, perServo } from "./machine-log.ts";
5660 import { Metrics } from "./metrics.ts";
5761 import { MotionError, moveToPose, playTrajectory, recordTrajectory, STALL_SPAN_TICKS } from "./motion.ts";
5862 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";
6064 import { largestStep, parseTrajectory, serializeTrajectory, type Trajectory } from "./trajectory.ts";
6165 import { accelRegister, bound, DEFAULT_SAFETY, Governor, jointBounds, motionLimits, parseFrame, SAFETY_KEYS, SafetyError, TICKS_PER_DEGREE, validateSafety, type SafetySettings } from "./safety.ts";
6266
@@ -165,6 +169,16 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
165169 throw new Error(`safety options: ${(err as Error).message}`);
166170 }
167171 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;
168182
169183 const limits = new Map<number, { min: number; max: number }>();
170184 for (const id of ids) {
@@ -251,9 +265,11 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
251265 if (driver) throw new HttpError(409, `${describe(driver)} is driving the arm`);
252266 driver = kind;
253267 current = new AbortController();
268 machine.note("state", "driver", { driving: kind });
254269 return current;
255270 };
256271 const release = () => {
272 if (driver) machine.note("state", "driver", { driving: null });
257273 driver = null;
258274 current = null;
259275 };
@@ -293,6 +309,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
293309 estop = { by, at: new Date().toISOString() };
294310 writeAtomic(estopFile, JSON.stringify(estop));
295311 metrics.event("estop", { by });
312 machine.note("state", "emergency stop", { by });
296313 }
297314 const was = driver;
298315 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 = {}):
314331 /* already gone */
315332 }
316333 metrics.event("estop-clear", { by });
334 machine.note("state", "emergency stop cleared", { by });
317335 return true;
318336 };
319337
@@ -335,6 +353,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
335353 const violation = checkPath(from, new Map([...from, ...targets]));
336354 if (violation && settings.zone === "enforce") {
337355 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" });
338357 return;
339358 }
340359 await moveToPose(bus, targets.map(([id]) => id), targets.map(([, t]) => t), {
@@ -344,6 +363,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
344363 signal: controller.signal,
345364 });
346365 metrics.event("park", { why, parked: true, pose: pose ? settings.parkPose : "middle" });
366 machine.note("state", "parked", { why, pose: pose ? settings.parkPose : "middle" });
347367 } catch (err) {
348368 metrics.event("park", { why, parked: false, error: err instanceof Error ? err.message : String(err) });
349369 } finally {
@@ -509,6 +529,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
509529 const loads = await bus.syncRead(ids, STS3215.Present_Load);
510530 const temps = await bus.syncRead(ids, STS3215.Present_Temperature);
511531 const torque = await bus.syncRead(ids, STS3215.Torque_Enable);
532 const b = bounds();
512533 const joints = ids.map((id) => ({
513534 id,
514535 joint: JOINTS[id] ?? null,
@@ -517,6 +538,13 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
517538 load: loads.has(id) ? loads.get(id)! / 10 : null,
518539 temperature: temps.get(id) ?? null,
519540 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,
520548 }));
521549 metrics.sample(joints);
522550 const zone = evaluate(positions);
@@ -532,7 +560,9 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
532560 blocked,
533561 jammed: [...jams.keys()],
534562 stream: streamStats,
563 held,
535564 estop,
565 machine: { run, seq: machine.seq },
536566 };
537567 };
538568
@@ -541,6 +571,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
541571 const controller = claim("move");
542572 const b = bounds();
543573 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 }));
544575 try {
545576 const from = await bus.syncRead(ids, STS3215.Present_Position);
546577 const to = new Map(from);
@@ -548,10 +579,13 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
548579 const violation = checkPath(from, to);
549580 if (violation) {
550581 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 });
551583 if (settings.zone === "enforce") return { status: 409, body: { reached: false, error: `refused: ${describeViolation(violation)}`, violation } };
552584 }
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 });
553587 const result = await moveToPose(bus, targetIds, positions, {
554 speed: number(body.speed, 300, 20, speedLimits().speed, "speed"),
588 speed,
555589 torquePercent: number(body.torque, 70, 10, 100, "torque"),
556590 torqueCaps: torqueCaps(),
557591 signal: controller.signal,
@@ -758,6 +792,8 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
758792 const position = bound(bounds(), id, body.position as number)!;
759793 const torque = Math.min(number(body.torque, 30, 10, 60, "torque"), settings.gripperTorquePercent); // the force limit, whatever is asked
760794 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" });
761797 claim("move");
762798 try {
763799 const present = await bus.syncRead([id], STS3215.Present_Position);
@@ -838,6 +874,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
838874 const step = largestStep(trajectory);
839875 const asked = number(body.rate, 1, 0.1, 2, "rate");
840876 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}` });
841878 const controller = claim("play");
842879 try {
843880 if (model && settings.zone !== "off") {
@@ -851,6 +888,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
851888 };
852889 const refuse = (v: Violation, where: string): boolean => {
853890 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}` });
854892 if (settings.zone !== "enforce") return false;
855893 json(res, 409, { played: 0, error: `refused: ${where}: ${describeViolation(v)}`, violation: v });
856894 return true;
@@ -933,6 +971,8 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
933971 await bus.syncWrite(STS3215.Goal_Position, ids.filter((id) => positions.has(id)).map((id) => [id, positions.get(id)!] as const));
934972 governor.reset(positions);
935973 last = null;
974 held = true;
975 machine.note("state", "dead-man hold", { afterMs: holdAfterMs });
936976 });
937977 const arm = () =>
938978 run(async () => {
@@ -967,6 +1007,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
9671007 jams.set(id, { position: p, direction: Math.sign(target - p) });
9681008 last?.set(id, p);
9691009 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 });
9701011 return true;
9711012 };
9721013 const watch = setInterval(
@@ -1019,7 +1060,10 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
10191060 for (const [id, value] of frame) {
10201061 const target = bound(b, id, value);
10211062 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 }
10231067 const jam = jams.get(id);
10241068 if (jam) {
10251069 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 = {}):
10301074 if (previous === undefined) ease = true; // a joint this stream has not driven yet is eased over, never jumped
10311075 else if (Math.abs(target - previous) > maxStep) {
10321076 stats.dropped++;
1077 machine.note("clamp", "too far in one frame", { id, asked: target, from: previous, maxStep });
10331078 const n = (drops.get(id) ?? 0) + 1;
10341079 drops.set(id, n);
10351080 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 = {}):
10411086 }
10421087 if (!targets.length) return;
10431088 stats.frames++;
1089 if (held) {
1090 held = false;
1091 machine.note("state", "following again", {});
1092 }
10441093 // The zone: the frame is judged as the whole pose it would make, with uncommanded joints where they are.
10451094 const pose = new Map(present);
10461095 for (const [id, t] of last ?? []) pose.set(id, t);
@@ -1051,6 +1100,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
10511100 blocked = zone.violation;
10521101 if (settings.zone === "enforce" && zone.violation.depth > heldDepth + 0.001) {
10531102 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" });
10541104 return; // deeper in than the arm already is: it stays at the last good targets; a frame that backs out is let through
10551105 }
10561106 } else blocked = null;
@@ -1137,6 +1187,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
11371187 }
11381188 } finally {
11391189 blocked = null;
1190 held = false;
11401191 jams.clear();
11411192 streamStats = null;
11421193 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 = {}):
11531204 const watchEveryMs = options.watchEveryMs ?? 250;
11541205 let watching: ReturnType<typeof setInterval> | undefined;
11551206 let reading = false;
1207 const machineFrame = (entries: readonly unknown[]) => JSON.stringify({ machine: entries, run });
11561208 const broadcast = async () => {
11571209 if (reading) return; // a slow bus read is not stacked behind another: the next tick asks again
11581210 reading = true;
11591211 try {
11601212 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 }
11621219 } catch (err) {
11631220 console.error(`watch: ${err instanceof Error ? err.message : String(err)}`);
11641221 } finally {
11651222 reading = false;
11661223 }
11671224 };
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>();
11681228 watchers.on("connection", (ws: WebSocket) => {
11691229 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);
11701235 void broadcast();
11711236 ws.on("error", () => ws.terminate());
11721237 ws.on("close", () => {
11731238 if (watchers.clients.size > 0 || !watching) return;
11741239 clearInterval(watching);
11751240 watching = undefined;
1241 unsubscribe?.();
1242 unsubscribe = undefined;
11761243 });
11771244 });
11781245
@@ -1192,6 +1259,8 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
11921259 close: () =>
11931260 new Promise<void>((resolve) => {
11941261 clearInterval(watching);
1262 machine.close();
1263 bus.onSyncWrite = null;
11951264 for (const client of [...wss.clients, ...watchers.clients]) client.terminate();
11961265 wss.close();
11971266 watchers.close();
Software/so101/src/sts3215.ts +6
@@ -118,6 +118,12 @@ export function findRegister(name: string): [RegisterName, Register] | undefined
118118 return undefined;
119119 }
120120
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
121127 export const ticksToDegrees = (ticks: number): number => (ticks * 360) / RESOLUTION;
122128 export const degreesToTicks = (degrees: number): number => Math.round((degrees * RESOLUTION) / 360);
123129
Software/so101/src/terminal.test.ts +41 −1
@@ -12,7 +12,8 @@ import { identify, sign } from "./identity.ts";
1212 import { Lobby } from "./lobby.ts";
1313 import { startRelay, type RunningRelay } from "./relay.ts";
1414 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";
1617 import { Turns } from "./turns.ts";
1718
1819 const KEY = "test-identity-key";
@@ -85,6 +86,22 @@ describe("terminal lines", () => {
8586 expect(typed(room, "/quit")).toEqual({ quit: true });
8687 expect(typed(room, " ")).toBeNull();
8788 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();
88105 });
89106 });
90107
@@ -145,6 +162,29 @@ describe("terminal door", () => {
145162 await alice.printedLine(/^bob: hello terminal$/);
146163 });
147164
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
148188 test("a guest at the terminal watches and is refused chat and the line", async () => {
149189 const port = await start();
150190 const page = await viewer(port);
Software/so101/src/terminal.ts +98 −2
@@ -14,6 +14,8 @@
1414 * /ready /extend confirm you are there when called (15 s), or add 30 s to your turn
1515 * /end [who] owner: end that turn (none: whoever drives), or take them out of the line
1616 * /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
1719 * /who /help /quit
1820 * <who> is a name the door has seen (driving, in line, in the chat) or a user id.
1921 */
@@ -21,6 +23,7 @@
2123 import WebSocket from "ws";
2224 import { UNPRINTABLE } from "./chat.ts";
2325 import { ID, NAME, sign } from "./identity.ts";
26 import { entryLine, jointRows, linkRows, stateRows } from "./ui/machine.js";
2427
2528 export type Env = Record<string, string | undefined>;
2629
@@ -90,7 +93,36 @@ const said = (m: unknown): string => {
9093 return from ? `${plain(from.name)}: ${plain(message?.text)}` : `· ${plain(message?.text)}`;
9194 };
9295
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 }
94126
95127 /** Once each: "you are called, confirm" and "you are next", so a terminal driver gets what the page's strip shows. */
96128 function cues(room: Room, driver: unknown): string[] {
@@ -160,7 +192,7 @@ function target(room: Room, word: string): string | null {
160192 return ID.test(word) ? word : null;
161193 }
162194
163 export type Typed = { send: Frame } | { print: string } | { quit: true } | null;
195 export type Typed = { send: Frame } | { print: string } | { machine: boolean } | { quit: true } | null;
164196
165197 /** What a typed line asks for. Validation the server repeats anyway; this only saves a round trip on a typo. */
166198 export function typed(room: Room, input: string): Typed {
@@ -186,6 +218,9 @@ export function typed(room: Room, input: string): Typed {
186218 const id = target(room, arg);
187219 return id ? { send: { type: "mute", id, on: verb.toLowerCase() === "mute" } } : { print: `error: who is ${plain(arg)}?` };
188220 }
221 case "machine":
222 if (arg && arg.toLowerCase() !== "off" && arg.toLowerCase() !== "on") return { print: "usage: /machine [off]" };
223 return { machine: arg.toLowerCase() !== "off" };
189224 case "who":
190225 return { print: who(room) };
191226 case "help":
@@ -202,6 +237,8 @@ export function typed(room: Room, input: string): Typed {
202237 export class Door {
203238 readonly room = emptyRoom();
204239 private ws: WebSocket | null = null;
240 private machineWs: WebSocket | null = null;
241 readonly machine: MachineState = { status: null, link: null, room: null, skew: 0 };
205242 private readonly url: string;
206243 private readonly headers: Record<string, string>;
207244 private readonly print: (line: string) => void;
@@ -243,12 +280,71 @@ export class Door {
243280 if (!t) return true;
244281 if ("quit" in t) return false;
245282 if ("print" in t) this.print(t.print);
283 else if ("machine" in t) this.watchMachine(t.machine);
246284 else this.send(t.send);
247285 return true;
248286 }
249287
250288 close(): void {
251289 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 });
252348 }
253349
254350 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 @@
443443 </div>
444444 <div class="row"><button id="metricsBtn">Metrics</button><button id="calib">3D calibration</button></div>
445445 </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>
446449 <nav id="tabs" role="tablist" aria-label="Sheet">
447450 <button role="tab" id="t-chat" data-tab="chat" aria-controls="tab-chat" aria-selected="true">Chat<span class="badge" id="unread"></span></button>
448451 <button role="tab" id="t-queue" data-tab="queue" aria-controls="tab-queue" aria-selected="false">Queue<span class="badge" id="waiting"></span></button>
449452 <button role="tab" id="t-controls" data-tab="controls" aria-controls="tab-controls" aria-selected="false" hidden>Controls</button>
450453 <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>
451455 </nav>
452456 </section>
453457
@@ -544,6 +548,8 @@
544548 $("sheetToggle").onclick = () => setBare(!shell.classList.contains("bare"));
545549 const sideways = matchMedia("(orientation: landscape) and (max-height: 500px)");
546550 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 };
547553 function showTab(name, focus = false) {
548554 if ($(`t-${name}`).hidden) name = ["controls", "chat", "admin"].find((t) => !$(`t-${t}`).hidden) ?? "chat";
549555 tab = name;
@@ -556,6 +562,7 @@
556562 if (name === "chat") { $("unread").textContent = ""; chatBox.scrollTop = chatBox.scrollHeight; }
557563 if (name === "controls") load3D();
558564 if (name === "admin") loadSettings();
565 if (name === "machine") machineOpen(); else machineClose();
559566 }
560567 for (const b of $("tabs").querySelectorAll("[role=tab]")) b.onclick = () => showTab(b.dataset.tab);
561568 $("tabs").addEventListener("keydown", (e) => {
@@ -1831,6 +1838,15 @@
18311838 } catch (err) { console.error(err); msg("the calibration panel did not load", true); }
18321839 };
18331840
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
18341850 // ---------------------------------------------------------------- live status, sliders and jog
18351851 const joints = $("joints");
18361852 const built = new Map();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs