Public: anyone can read this; the crew can change it.

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

/admin shows each joint's servo control registers in one read-only table #472

Merged opened this

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

Merged

smith/arm:smith/443-admin-shows-each-joint-s-servo-control-r → main 4 commits fork

  • Merged. smith/443-admin-shows-each-joint-s-servo-control-r was merged into main as 83e9b68.

Review

Sign in to review this change.
9 files changed +218 −12
Software/README.md +5 −1
@@ -957,7 +957,11 @@ anyone else gets a 404 through the relay.
957957
958958 - `GET /servo-params` lists each servo's delay, P/D/I, startup force, dead
959959 zones and velocity loop, and records the first complete reading of the
960 writable ones in `servo-factory.json` next to the settings.
960 writable ones in `servo-factory.json` next to the settings. The owner sees it
961 read-only in the Servos section of `/admin` (one row per joint, one column per
962 register, a silent servo's error in its row) and as `/servos` in the terminal;
963 both show one sentence instead of a table while someone drives (the 409) or
964 when the arm server does not answer. Moderators and everyone else see neither.
961965 - `PUT /servo-params {"id": n, "P"?, "D"?, "I"?, "cwDeadZone"?, "ccwDeadZone"?,
962966 "minStartupForce"?}` writes one joint (EEPROM, with the Lock dance) and answers
963967 with the read-back. Whole numbers only: P 1-64, D 0-64, I 0-32, dead zones
Software/so101/src/admin-page.ts +4
@@ -12,6 +12,7 @@ import type { Person, Who } from "./identity.ts";
1212 import type { Snapshot } from "./turns.ts";
1313 import type { ViewerRow } from "./viewer-reports.ts";
1414 import { precisionSection, type PrecisionPanel } from "./precision-panel.ts";
15 import { servosSection, type ServoPanel } from "./servo-panel.ts";
1516
1617 export const esc = (text: string): string => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
1718
@@ -155,6 +156,8 @@ export interface AdminPage {
155156 visitors?: { peak: number; hours: readonly number[] };
156157 /** The arm's precision scorecard (src/precision-panel.ts); null when the arm did not answer, absent when not asked. */
157158 precision?: PrecisionPanel | null;
159 /** Owner only: the servos' control registers (src/servo-panel.ts); null when the arm did not answer, absent when not asked. */
160 servos?: ServoPanel | null;
158161 done?: Done | null;
159162 error?: string | null;
160163 }
@@ -279,6 +282,7 @@ ${p.canEdit ? `<section aria-labelledby="table"><h2 id="table">Table height</h2>
279282 </section>` : ""}
280283 ${p.canEdit && p.visitors ? visitorsSection(p.visitors) : ""}
281284 ${p.precision !== undefined ? precisionSection(p.precision, esc) : ""}
285 ${p.canEdit && p.servos !== undefined ? servosSection(p.servos, esc) : ""}
282286 <section aria-labelledby="health"><h2 id="health">Health</h2>${health(p.health ?? [])}</section>
283287 <section aria-labelledby="mods"><h2 id="mods">Moderators</h2>${mods}</section>
284288 <section aria-labelledby="moderation"><h2 id="moderation">Moderation</h2>${inForce("mute", p.muted ?? [], canLift)}${inForce("ban", p.banned ?? [], canLift)}${actions}</section>
Software/so101/src/admin-routes.ts +9 −4
@@ -6,10 +6,14 @@ import { AdminError, changeFromForm } from "./admin.ts";
66 import { sameOrigin } from "./relay.ts";
77 import { adminCsp, DONE, renderAdmin, renderRefusal, type Done } from "./admin-page.ts";
88 import type { PrecisionPanel } from "./precision-panel.ts";
9 import type { ServoPanel } from "./servo-panel.ts";
910
1011 /** Asks the arm for its precision scorecard; only called for someone allowed on the page. */
1112 export type AskPrecision = () => Promise<PrecisionPanel | null>;
1213
14 /** Asks the arm for its servos' control registers; only called for the owner. */
15 export type AskServos = () => Promise<ServoPanel | null>;
16
1317 /** What a POST needs once the caller is known to be allowed on the page. */
1418 export interface AdminSession {
1519 who: Person;
@@ -24,7 +28,7 @@ export interface AdminSession {
2428 * Answer 404 to anyone not allowed, and the page itself to GET and HEAD. Returns the session for any other
2529 * method by an allowed caller, and null when the response has been sent.
2630 */
27 export async function serveAdminPage(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL, askPrecision?: AskPrecision): Promise<AdminSession | null> {
31 export async function serveAdminPage(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL, askPrecision?: AskPrecision, askServos?: AskServos): Promise<AdminSession | null> {
2832 const who = lobby.who(req);
2933 const html = (status: number, text: string, edit = false) => {
3034 res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": adminCsp(edit) });
@@ -48,8 +52,9 @@ export async function serveAdminPage(lobby: Lobby, req: IncomingMessage, res: Se
4852 return null;
4953 }
5054 const precision = (req.method === "GET" || req.method === "HEAD") && askPrecision ? await askPrecision() : undefined;
55 const servos = canEdit && (req.method === "GET" || req.method === "HEAD") && askServos ? await askServos() : undefined;
5156 const show = (status: number, done: Done | null, error: string | null) =>
52 html(status, renderAdmin({ precision, who, canEdit, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, removed: lobby.chat.removed, muted: lobby.chat.mutedList(), banned: lobby.accounts.bans(), health: lobby.reports.rows(), reports: lobby.lineReports.list(), visitors: canEdit ? { peak: lobby.visitors.peakToday(), hours: lobby.visitors.joinsPerHour() } : undefined, done, error }), canEdit);
57 html(status, renderAdmin({ precision, servos, who, canEdit, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, removed: lobby.chat.removed, muted: lobby.chat.mutedList(), banned: lobby.accounts.bans(), health: lobby.reports.rows(), reports: lobby.lineReports.list(), visitors: canEdit ? { peak: lobby.visitors.peakToday(), hours: lobby.visitors.joinsPerHour() } : undefined, done, error }), canEdit);
5358 if (req.method === "GET" || req.method === "HEAD") {
5459 const done = url.searchParams.get("done");
5560 show(200, done && Object.hasOwn(DONE, done) ? (done as Done) : null, null);
@@ -68,8 +73,8 @@ const REPORT_ACTIONS = new Set(["report-remove", "report-mute", "report-dismiss"
6873 type ReadBody = (req: IncomingMessage, limit?: number) => Promise<Buffer>;
6974
7075 /** The owner's page. Anyone else is told so; a change is a form post, answered with a redirect back. */
71 export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL, readBody: ReadBody, askPrecision?: AskPrecision): Promise<void> {
72 const session = await serveAdminPage(lobby, req, res, url, askPrecision);
76 export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL, readBody: ReadBody, askPrecision?: AskPrecision, askServos?: AskServos): Promise<void> {
77 const session = await serveAdminPage(lobby, req, res, url, askPrecision, askServos);
7378 if (!session) return;
7479 const { who, canEdit, show } = session;
7580 if (req.method !== "POST") {
Software/so101/src/relay.ts +11 −1
@@ -74,6 +74,7 @@ import { OFFLINE_FRAME } from "./offline-frame.ts";
7474 import { ServoBaseline } from "./servo-baseline.ts";
7575 import { handleAdmin, handleLift } from "./admin-routes.ts";
7676 import { readPrecision } from "./precision-panel.ts";
77 import { readServos } from "./servo-panel.ts";
7778 import { parseFps, type FeedOptions } from "./camera-feed.ts";
7879 import { CameraError, CameraHub } from "./cameras.ts";
7980 import { VideoFeed, type VideoSources } from "./video-feed.ts";
@@ -462,6 +463,15 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
462463 return null;
463464 }
464465 };
466 /** The arm's servo registers for the owner's admin page; null when the arm does not answer in time. */
467 const askServos = async () => {
468 try {
469 const answer = await fetch(`${remote && onArm() ? remote.http : simulation}/servo-params`, { cache: "no-store", signal: AbortSignal.timeout(Math.min(readTimeoutMs, 3000)) });
470 return readServos(answer.status, await answer.json().catch(() => null));
471 } catch {
472 return null;
473 }
474 };
465475 /** GET /precision: the scorecard as JSON, for the owner and moderators, who see it on /admin; to anyone else there is no such route. */
466476 const precisionRead = async (req: IncomingMessage, res: ServerResponse, url: URL) => {
467477 if (!lobby || !lobby.who(req) || !lobby.moderates(req)) return json(res, 404, { error: "no such route" });
@@ -679,7 +689,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
679689 const cameraAdmin = ADMIN_CAMERA.exec(url.pathname);
680690 if (cameraAdmin) return await administer(req, res, cameraAdmin[1] === undefined ? null : Number(cameraAdmin[1]));
681691 if (lobby && url.pathname === "/admin/lift") return await handleLift(lobby, req, res, readBody);
682 if (lobby && (url.pathname === "/admin" || url.pathname === "/admin/health")) return await handleAdmin(lobby, req, res, url, readBody, askPrecision);
692 if (lobby && (url.pathname === "/admin" || url.pathname === "/admin/health")) return await handleAdmin(lobby, req, res, url, readBody, askPrecision, askServos);
683693 if (url.pathname === "/precision") return await precisionRead(req, res, url);
684694 if (url.pathname === LEADER) return await leaderCalibration(req, res);
685695 if (url.pathname === "/join") {
Software/so101/src/servo-panel.test.ts added +77
@@ -0,0 +1,77 @@
1 import { afterEach, expect, test } from "bun:test";
2 import { mkdtempSync, rmSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { esc } from "./admin-page.ts";
6 import { sign } from "./identity.ts";
7 import { Lobby } from "./lobby.ts";
8 import { startRelay, type RunningRelay } from "./relay.ts";
9 import { readServos, servosSection } from "./servo-panel.ts";
10
11 const fixture = [
12 { id: 1, joint: "shoulder_pan", registers: { P_Coefficient: 32, D_Coefficient: 32 } },
13 { id: 2, joint: "<b>x</b>", registers: {}, error: "no answer" },
14 { id: 3, joint: "elbow_flex", registers: { P_Coefficient: 16 }, error: "no answer for D_Coefficient" },
15 ];
16
17 test("one row per joint, one column per register, errors in the row, everything escaped", () => {
18 const html = servosSection(readServos(200, fixture), esc);
19 expect(html).toContain("<th scope=\"row\">shoulder_pan (1)</th><td>32</td><td>32</td>");
20 expect(html).toContain("<th scope=\"col\">P Coefficient</th>");
21 expect(html).toContain("<b>no answer</b>");
22 expect(html).toContain("<td>16</td><td>—</td><td><b>no answer for D_Coefficient</b>");
23 expect(html).not.toContain("<b>x</b>");
24 expect(html).toContain("&#60;b&#62;x");
25 });
26
27 test("a 409 is a sentence, other trouble is told, and nothing is a blank table", () => {
28 expect(servosSection(readServos(409, { error: "bob is driving the arm" }), esc)).toContain("Someone is driving the arm");
29 expect(servosSection(readServos(500, null), esc)).toContain("status 500");
30 expect(servosSection(readServos(200, { not: "a list" }), esc)).toContain("did not answer");
31 expect(servosSection(null, esc)).toContain("did not answer");
32 expect(servosSection(readServos(200, []), esc)).toContain("no servos");
33 });
34
35 const KEY = "k".repeat(64);
36 const later = Date.now() + 600_000;
37 const as = (name: string, role: "user" | "admin") => {
38 const identity = `id-${name}|${name}|${role}|${later}`;
39 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
40 };
41 let dir = "";
42 let relay: RunningRelay | undefined;
43 let lobby: Lobby | undefined;
44 let arm: ReturnType<typeof Bun.serve> | undefined;
45 afterEach(async () => {
46 await relay?.close();
47 lobby?.close();
48 arm?.stop(true);
49 if (dir) rmSync(dir, { recursive: true, force: true });
50 dir = "";
51 relay = lobby = arm = undefined;
52 });
53
54 test("/admin shows the servos to the owner only; anyone else gets 404", async () => {
55 dir = mkdtempSync(join(tmpdir(), "so101-servo-panel-"));
56 arm = Bun.serve({ port: 0, fetch: () => Response.json(fixture) });
57 lobby = new Lobby({ identityKey: KEY, adminFile: join(dir, "admin.json") });
58 relay = await startRelay({ port: 0, simulation: `http://127.0.0.1:${arm.port}`, lobby });
59 const base = `http://127.0.0.1:${relay.port}`;
60 const page = await fetch(`${base}/admin`, { headers: as("trevato", "admin") });
61 expect(page.status).toBe(200);
62 expect(await page.text()).toContain("shoulder_pan (1)");
63 expect((await fetch(`${base}/admin`, { headers: as("bob", "user") })).status).toBe(404);
64 expect((await fetch(`${base}/admin`)).status).toBe(404);
65 await fetch(`${base}/admin`, { method: "POST", redirect: "manual", headers: { ...as("trevato", "admin"), "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ action: "mod-add", name: "bob" }) });
66 const seen = await (await fetch(`${base}/admin`, { headers: as("bob", "user") })).text();
67 expect(seen).not.toContain("shoulder_pan");
68 });
69
70 test("while someone drives, the owner reads a sentence", async () => {
71 dir = mkdtempSync(join(tmpdir(), "so101-servo-panel-"));
72 arm = Bun.serve({ port: 0, fetch: () => Response.json({ error: "bob is driving the arm" }, { status: 409 }) });
73 lobby = new Lobby({ identityKey: KEY, adminFile: join(dir, "admin.json") });
74 relay = await startRelay({ port: 0, simulation: `http://127.0.0.1:${arm.port}`, lobby });
75 const text = await (await fetch(`http://127.0.0.1:${relay.port}/admin`, { headers: as("trevato", "admin") })).text();
76 expect(text).toContain("Someone is driving the arm");
77 });
Software/so101/src/servo-panel.ts added +49
@@ -0,0 +1,49 @@
1 /**
2 * The Servos section of /admin: the arm server's GET /servo-params read field by field, for the answer comes over the
3 * network from another machine, and drawn as one row per joint and one column per register. A servo that did not
4 * answer shows its error in its row; a 409 (someone is driving) or an unreachable arm is one sentence. No script.
5 */
6
7 export interface ServoRow {
8 id: number;
9 joint: string | null;
10 registers: Record<string, number>;
11 error: string | null;
12 }
13
14 /** Either the joints as read, or why there is nothing to show. */
15 export type ServoPanel = { rows: ServoRow[] } | { notice: string };
16
17 const MAX_ROWS = 32;
18 const obj = (v: unknown): Record<string, unknown> => (typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
19 const short = (v: unknown, max = 120): string => [...String(v).replace(/[\p{Cc}\p{Cf}]/gu, "")].slice(0, max).join("");
20
21 /** The panel for what /servo-params answered: its status and parsed body (null when it was not JSON). */
22 export function readServos(status: number, body: unknown): ServoPanel {
23 if (status === 409) return { notice: `Someone is driving the arm, so the servos are not read now${typeof obj(body).error === "string" ? ` (${short(obj(body).error)})` : ""}. They are read when nobody has a turn.` };
24 if (status !== 200 || !Array.isArray(body)) return { notice: `The arm server did not answer /servo-params with the servos (status ${status || "none"}).` };
25 const rows = body.slice(0, MAX_ROWS).map((item): ServoRow => {
26 const r = obj(item), regs = obj(r.registers);
27 return {
28 id: typeof r.id === "number" && Number.isFinite(r.id) ? r.id : -1,
29 joint: typeof r.joint === "string" && r.joint ? short(r.joint, 40) : null,
30 registers: Object.fromEntries(Object.entries(regs).filter(([, v]) => typeof v === "number" && Number.isFinite(v)).slice(0, 32).map(([k, v]) => [short(k, 60), v as number])),
31 error: typeof r.error === "string" && r.error ? short(r.error) : null,
32 };
33 });
34 return { rows };
35 }
36
37 /** The section; `esc` is the page's own escaping, applied to everything that came over the wire. */
38 export function servosSection(p: ServoPanel | null | undefined, esc: (s: string) => string): string {
39 const head = `<section aria-labelledby="servos"><h2 id="servos">Servos</h2>`;
40 if (!p) return `${head}<p class="empty">The arm server did not answer <code>/servo-params</code>.</p></section>`;
41 if ("notice" in p) return `${head}<p class="empty">${esc(p.notice)}</p></section>`;
42 if (!p.rows.length) return `${head}<p class="empty">The arm server listed no servos.</p></section>`;
43 const cols = [...new Set(p.rows.flatMap((r) => Object.keys(r.registers)))];
44 const th = cols.map((c) => `<th scope="col">${esc(c.replaceAll("_", " "))}</th>`).join("");
45 const body = p.rows
46 .map((r) => `<tr><th scope="row">${esc(r.joint ?? "?")} (${r.id})</th>${cols.map((c) => `<td>${c in r.registers ? r.registers[c] : "—"}</td>`).join("")}<td>${r.error ? `<b>${esc(r.error)}</b>` : ""}</td></tr>`)
47 .join("");
48 return `${head}<div class="scroll"><table aria-label="Servo control registers"><caption>Each joint's control registers, read just now; read-only.</caption><thead><tr><th scope="col">Joint</th>${th}<th scope="col">Error</th></tr></thead><tbody>${body}</tbody></table></div></section>`;
49 }
Software/so101/src/terminal.test.ts +19 −1
@@ -12,7 +12,7 @@ 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 { cardReader, Door, emptyRoom, hear, precisionLines, liveUrl, machineEntry, machineLines, machineUrl, healthLines, plain, poster, reader, terminalHeaders, typed } from "./terminal.ts";
15 import { cardReader, Door, servosLines, servosReader, emptyRoom, hear, precisionLines, liveUrl, machineEntry, machineLines, machineUrl, healthLines, plain, poster, reader, terminalHeaders, typed } from "./terminal.ts";
1616 import { jointRows } from "./ui/machine.js";
1717 import { Turns } from "./turns.ts";
1818
@@ -230,6 +230,24 @@ describe("terminal table", () => {
230230 expect(printed).toContain("error: precision is not available here");
231231 });
232232
233 test("/servos prints each joint's registers as /admin shows them, a sentence while someone drives, and nothing to a guest", async () => {
234 expect(typed(emptyRoom(), "/servos")).toEqual({ servos: true });
235 const body = [{ id: 1, joint: "shoulder_pan", registers: { P_Coefficient: 32 } }, { id: 2, joint: "elbow\x1b[31m", registers: {}, error: "no answer" }];
236 const asked: string[] = [];
237 const ok = await servosReader({ PORT: "8102" }, (async (url: string) => (asked.push(url), Response.json(body))) as unknown as typeof fetch)();
238 expect(asked[0]).toBe("http://127.0.0.1:8102/servo-params");
239 expect(servosLines(ok.panel!)).toEqual(["shoulder_pan (1) P_Coefficient=32", "elbow[31m (2) · no answer"]);
240 const busy = await servosReader({ PORT: "8102" }, (async () => Response.json({ error: "bob is driving the arm" }, { status: 409 })) as unknown as typeof fetch)();
241 expect(servosLines(busy.panel!)[0]).toContain("Someone is driving the arm");
242 const guest = await servosReader({ PORT: "8102" }, (async () => Response.json({ error: "no such route" }, { status: 404 })) as unknown as typeof fetch)();
243 expect(guest).toEqual({ status: 404, error: "servos are for the owner", panel: null });
244 const printed: string[] = [];
245 new Door("ws://127.0.0.1:1/live", {}, (l) => printed.push(l), null, null, null, async () => guest).input("/servos");
246 new Door("ws://127.0.0.1:1/live", {}, (l) => printed.push(l)).input("/servos");
247 await Bun.sleep(50);
248 expect(printed.sort()).toEqual(["error: servos are for the owner", "error: servos are not available here"]);
249 });
250
233251 test("/health asks the reader, prints a line per viewer as text, or the refusal; without a reader it says so", async () => {
234252 expect(typed(emptyRoom(), "/health")).toEqual({ health: true });
235253 const row = { viewer: "v1", name: "al\x1b[31mice", rttP50: 40, rttP95: 90, sentPerS: 30, droppedPerS: 2, camFps: 14.5, frameAgeMs: 120, stalls: 1, reconnects: 2 };
Software/so101/src/terminal.ts +42 −3
@@ -34,6 +34,7 @@
3434 * /zero <joint> [deg] admin: make the model read deg (default 0) for that joint at the pose it is in now (POST /settings/joint-zero)
3535 * /health owner or moderator: each open page's link as it last reported it (GET /admin/health, the page's Admin -> Health)
3636 * /precision owner or moderator: the precision scorecard /admin shows (GET /precision, src/precision-panel.ts)
37 * /servos owner: each joint's servo control registers /admin shows (GET /servo-params, src/servo-panel.ts); 404 to anyone else
3738 * /machine [off] the Machine panel (/machine, src/machine-feed.ts): the joints, the link and the server as they are,
3839 * then every command in and out as it happens, in the page's own words (src/ui/machine.js); off stops it
3940 * /who /help /quit
@@ -43,6 +44,7 @@
4344 import WebSocket from "ws";
4445 import { UNPRINTABLE } from "./chat.ts";
4546 import { ID, NAME, sign } from "./identity.ts";
47 import { readServos, type ServoPanel } from "./servo-panel.ts";
4648 import { headlineValue, readPrecision, sparkline, type PrecisionPanel } from "./precision-panel.ts";
4749 import { presenceText } from "./ui/lobby-panel.js";
4850 import { entryLine, jointRows, linkRows, stateRows } from "./ui/machine.js";
@@ -116,6 +118,31 @@ export function reader(env: Env, fetcher: typeof fetch = fetch): Read {
116118 };
117119 }
118120
121 /** What GET /servo-params answered, read as the admin panel reads it; or why not (anyone but the owner is told there is no such route). */
122 export type Servos = { status: number; error: string | null; panel: ServoPanel | null };
123 export type ReadServos = () => Promise<Servos>;
124
125 /** GET the servo registers as /admin shows them, signed afresh; the server decides who may. */
126 export function servosReader(env: Env, fetcher: typeof fetch = fetch): ReadServos {
127 return async () => {
128 try {
129 const r = await fetcher(`${appUrl(env)}/servo-params`, { headers: terminalHeaders(env), signal: AbortSignal.timeout(5000) });
130 const body = (await r.json().catch(() => null)) as unknown;
131 if (r.status === 404) return { status: 404, error: "servos are for the owner", panel: null };
132 return { status: r.status, error: null, panel: readServos(r.status, body) };
133 } catch (err) {
134 return { status: 0, error: plain((err as Error).message), panel: null };
135 }
136 };
137 }
138
139 /** One line per joint: its registers, then its error if the servo did not answer; or the one sentence. */
140 export function servosLines(p: ServoPanel): string[] {
141 if ("notice" in p) return [plain(p.notice)];
142 if (!p.rows.length) return ["the arm server listed no servos"];
143 return p.rows.map((r) => plain(`${r.joint ?? "?"} (${r.id}) ${Object.entries(r.registers).map(([k, v]) => `${k}=${v}`).join(" ")}${r.error ? ` · ${r.error}` : ""}`));
144 }
145
119146 /** What GET /precision answered, read as the admin panel reads it; or why not (a guest is told there is no such route). */
120147 export type Card = { status: number; error: string | null; panel: PrecisionPanel | null };
121148 export type ReadCard = () => Promise<Card>;
@@ -212,7 +239,7 @@ const said = (room: Room, m: unknown): string => {
212239 };
213240
214241 const ZERO_USAGE = "usage: /zero <joint, e.g. shoulder_pan> [degrees the model should read, default 0]";
215 export const HELP = "type to chat · /join /leave /ready /extend · /stop /resume (driver, owner) · /end [who] /table here|touch 1|2|3|<mm> /zero <joint> [deg] (owner) · /mute <who> /unmute <who> (owner, moderator) · /delete <who|#id> (owner, moderator) · /report <who|#id> · /reports /dismiss #<id> (owner, moderator) · /removed /restore #<id> /visitors (owner) · /health /precision (owner, moderator) · /machine [off] · /who · /quit";
242 export const HELP = "type to chat · /join /leave /ready /extend · /stop /resume (driver, owner) · /end [who] /table here|touch 1|2|3|<mm> /zero <joint> [deg] (owner) · /mute <who> /unmute <who> (owner, moderator) · /delete <who|#id> (owner, moderator) · /report <who|#id> · /reports /dismiss #<id> (owner, moderator) · /removed /restore #<id> /visitors (owner) · /health /precision (owner, moderator) · /servos (owner) · /machine [off] · /who · /quit";
216243
217244 /** The Machine feed's socket beside the lobby's: same app, same port. */
218245 export const machineUrl = (live: string): string => live.replace(/\/live$/, "/machine");
@@ -355,7 +382,7 @@ function target(room: Room, word: string): string | null {
355382 return ID.test(word) ? word : null;
356383 }
357384
358 export type Typed = { send: Frame } | { post: "/stop" | "/resume" } | { table: "here" | number | { touch: 1 | 2 | 3 } } | { zero: { joint: string; referenceDeg: number } } | { print: string } | { lines: string[] } | { machine: boolean } | { health: true } | { precision: true } | { quit: true } | null;
385 export type Typed = { send: Frame } | { post: "/stop" | "/resume" } | { table: "here" | number | { touch: 1 | 2 | 3 } } | { zero: { joint: string; referenceDeg: number } } | { print: string } | { lines: string[] } | { machine: boolean } | { health: true } | { precision: true } | { servos: true } | { quit: true } | null;
359386
360387 /** What a typed line asks for. Validation the server repeats anyway; this only saves a round trip on a typo. */
361388 export function typed(room: Room, input: string): Typed {
@@ -432,6 +459,8 @@ export function typed(room: Room, input: string): Typed {
432459 return { health: true };
433460 case "precision":
434461 return { precision: true };
462 case "servos":
463 return { servos: true };
435464 case "machine":
436465 if (arg && arg.toLowerCase() !== "off" && arg.toLowerCase() !== "on") return { print: "usage: /machine [off]" };
437466 return { machine: arg.toLowerCase() !== "off" };
@@ -459,11 +488,13 @@ export class Door {
459488 private readonly post: Post | null;
460489 private readonly read: Read | null;
461490 private readonly readCard: ReadCard | null;
491 private readonly readServos: ReadServos | null;
462492
463493 /** `post` reaches the app's /stop and /resume, `read` its /admin/health, `readCard` its /precision; without them, the door says it cannot. */
464 constructor(url: string, headers: Record<string, string>, print: (line: string) => void, post: Post | null = null, read: Read | null = null, readCard: ReadCard | null = null) {
494 constructor(url: string, headers: Record<string, string>, print: (line: string) => void, post: Post | null = null, read: Read | null = null, readCard: ReadCard | null = null, readServos: ReadServos | null = null) {
465495 this.read = read;
466496 this.readCard = readCard;
497 this.readServos = readServos;
467498 this.url = url;
468499 this.headers = headers;
469500 this.print = print;
@@ -507,6 +538,7 @@ export class Door {
507538 else if ("zero" in t) void this.zero(t.zero.joint, t.zero.referenceDeg);
508539 else if ("health" in t) void this.health();
509540 else if ("precision" in t) void this.precision();
541 else if ("servos" in t) void this.servos();
510542 else if ("machine" in t) this.watchMachine(t.machine);
511543 else this.send(t.send);
512544 return true;
@@ -535,6 +567,13 @@ export class Door {
535567 for (const line of r.error || !r.panel ? [`error: ${r.error ?? "no scorecard"}`] : precisionLines(r.panel)) this.print(line);
536568 }
537569
570 /** The server decides who may; a refusal is printed, else the joints' registers. */
571 private async servos(): Promise<void> {
572 if (!this.readServos) return this.print("error: servos are not available here");
573 const r = await this.readServos();
574 for (const line of r.error || !r.panel ? [`error: ${r.error ?? "no servos"}`] : servosLines(r.panel)) this.print(line);
575 }
576
538577 /** The server decides who may; a refusal is printed, success says the offset the server now holds. */
539578 private async table(what: "here" | number | { touch: 1 | 2 | 3 }): Promise<void> {
540579 if (!this.post) return this.print("error: the table is not available here");
Software/so101/src/tty.ts +2 −2
@@ -4,7 +4,7 @@
44 */
55
66 import { createInterface, type Interface } from "node:readline";
7 import { cardReader, Door, HELP, liveUrl, poster, reader, terminalHeaders } from "./terminal.ts";
7 import { cardReader, Door, HELP, liveUrl, poster, reader, servosReader, terminalHeaders } from "./terminal.ts";
88
99 const env = process.env;
1010 const where = env.FORGE_APP_ENV === "preview" ? `preview of #${env.FORGE_APP_PULL ?? "?"}` : (env.FORGE_APP_ENV ?? "local");
@@ -17,7 +17,7 @@ const print = (line: string) => {
1717 rl?.prompt(true);
1818 };
1919
20 const door = new Door(liveUrl(env), terminalHeaders(env), print, poster(env), reader(env), cardReader(env));
20 const door = new Door(liveUrl(env), terminalHeaders(env), print, poster(env), reader(env), cardReader(env), servosReader(env));
2121 print(`\x1b[1mSO-101 arm\x1b[0m · ${where} · ${HELP}`);
2222 try {
2323 await door.open(() => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs