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
Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.
smith/arm:smith/443-admin-shows-each-joint-s-servo-control-r → main 4 commits fork
9 files
changed +218
−12
Software/README.md +5 −1
| @@ -957,7 +957,11 @@ anyone else gets a 404 through the relay. | ||
| 957 | 957 | |
| 958 | 958 | - `GET /servo-params` lists each servo's delay, P/D/I, startup force, dead |
| 959 | 959 | 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. | |
| 961 | 965 | - `PUT /servo-params {"id": n, "P"?, "D"?, "I"?, "cwDeadZone"?, "ccwDeadZone"?, |
| 962 | 966 | "minStartupForce"?}` writes one joint (EEPROM, with the Lock dance) and answers |
| 963 | 967 | 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"; | ||
| 12 | 12 | import type { Snapshot } from "./turns.ts"; |
| 13 | 13 | import type { ViewerRow } from "./viewer-reports.ts"; |
| 14 | 14 | import { precisionSection, type PrecisionPanel } from "./precision-panel.ts"; |
| 15 | import { servosSection, type ServoPanel } from "./servo-panel.ts"; | |
| 15 | 16 | |
| 16 | 17 | export const esc = (text: string): string => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); |
| 17 | 18 | |
| @@ -155,6 +156,8 @@ export interface AdminPage { | ||
| 155 | 156 | visitors?: { peak: number; hours: readonly number[] }; |
| 156 | 157 | /** The arm's precision scorecard (src/precision-panel.ts); null when the arm did not answer, absent when not asked. */ |
| 157 | 158 | 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; | |
| 158 | 161 | done?: Done | null; |
| 159 | 162 | error?: string | null; |
| 160 | 163 | } |
| @@ -279,6 +282,7 @@ ${p.canEdit ? `<section aria-labelledby="table"><h2 id="table">Table height</h2> | ||
| 279 | 282 | </section>` : ""} |
| 280 | 283 | ${p.canEdit && p.visitors ? visitorsSection(p.visitors) : ""} |
| 281 | 284 | ${p.precision !== undefined ? precisionSection(p.precision, esc) : ""} |
| 285 | ${p.canEdit && p.servos !== undefined ? servosSection(p.servos, esc) : ""} | |
| 282 | 286 | <section aria-labelledby="health"><h2 id="health">Health</h2>${health(p.health ?? [])}</section> |
| 283 | 287 | <section aria-labelledby="mods"><h2 id="mods">Moderators</h2>${mods}</section> |
| 284 | 288 | <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"; | ||
| 6 | 6 | import { sameOrigin } from "./relay.ts"; |
| 7 | 7 | import { adminCsp, DONE, renderAdmin, renderRefusal, type Done } from "./admin-page.ts"; |
| 8 | 8 | import type { PrecisionPanel } from "./precision-panel.ts"; |
| 9 | import type { ServoPanel } from "./servo-panel.ts"; | |
| 9 | 10 | |
| 10 | 11 | /** Asks the arm for its precision scorecard; only called for someone allowed on the page. */ |
| 11 | 12 | export type AskPrecision = () => Promise<PrecisionPanel | null>; |
| 12 | 13 | |
| 14 | /** Asks the arm for its servos' control registers; only called for the owner. */ | |
| 15 | export type AskServos = () => Promise<ServoPanel | null>; | |
| 16 | ||
| 13 | 17 | /** What a POST needs once the caller is known to be allowed on the page. */ |
| 14 | 18 | export interface AdminSession { |
| 15 | 19 | who: Person; |
| @@ -24,7 +28,7 @@ export interface AdminSession { | ||
| 24 | 28 | * Answer 404 to anyone not allowed, and the page itself to GET and HEAD. Returns the session for any other |
| 25 | 29 | * method by an allowed caller, and null when the response has been sent. |
| 26 | 30 | */ |
| 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> { | |
| 28 | 32 | const who = lobby.who(req); |
| 29 | 33 | const html = (status: number, text: string, edit = false) => { |
| 30 | 34 | 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 | ||
| 48 | 52 | return null; |
| 49 | 53 | } |
| 50 | 54 | 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; | |
| 51 | 56 | 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); | |
| 53 | 58 | if (req.method === "GET" || req.method === "HEAD") { |
| 54 | 59 | const done = url.searchParams.get("done"); |
| 55 | 60 | 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" | ||
| 68 | 73 | type ReadBody = (req: IncomingMessage, limit?: number) => Promise<Buffer>; |
| 69 | 74 | |
| 70 | 75 | /** 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); | |
| 73 | 78 | if (!session) return; |
| 74 | 79 | const { who, canEdit, show } = session; |
| 75 | 80 | if (req.method !== "POST") { |
Software/so101/src/relay.ts +11 −1
| @@ -74,6 +74,7 @@ import { OFFLINE_FRAME } from "./offline-frame.ts"; | ||
| 74 | 74 | import { ServoBaseline } from "./servo-baseline.ts"; |
| 75 | 75 | import { handleAdmin, handleLift } from "./admin-routes.ts"; |
| 76 | 76 | import { readPrecision } from "./precision-panel.ts"; |
| 77 | import { readServos } from "./servo-panel.ts"; | |
| 77 | 78 | import { parseFps, type FeedOptions } from "./camera-feed.ts"; |
| 78 | 79 | import { CameraError, CameraHub } from "./cameras.ts"; |
| 79 | 80 | import { VideoFeed, type VideoSources } from "./video-feed.ts"; |
| @@ -462,6 +463,15 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 462 | 463 | return null; |
| 463 | 464 | } |
| 464 | 465 | }; |
| 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 | }; | |
| 465 | 475 | /** GET /precision: the scorecard as JSON, for the owner and moderators, who see it on /admin; to anyone else there is no such route. */ |
| 466 | 476 | const precisionRead = async (req: IncomingMessage, res: ServerResponse, url: URL) => { |
| 467 | 477 | 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> { | ||
| 679 | 689 | const cameraAdmin = ADMIN_CAMERA.exec(url.pathname); |
| 680 | 690 | if (cameraAdmin) return await administer(req, res, cameraAdmin[1] === undefined ? null : Number(cameraAdmin[1])); |
| 681 | 691 | 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); | |
| 683 | 693 | if (url.pathname === "/precision") return await precisionRead(req, res, url); |
| 684 | 694 | if (url.pathname === LEADER) return await leaderCalibration(req, res); |
| 685 | 695 | 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("<b>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"; | ||
| 12 | 12 | import { Lobby } from "./lobby.ts"; |
| 13 | 13 | import { startRelay, type RunningRelay } from "./relay.ts"; |
| 14 | 14 | import { startServer, type RunningServer } from "./server.ts"; |
| 15 | import { 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"; | |
| 16 | 16 | import { jointRows } from "./ui/machine.js"; |
| 17 | 17 | import { Turns } from "./turns.ts"; |
| 18 | 18 | |
| @@ -230,6 +230,24 @@ describe("terminal table", () => { | ||
| 230 | 230 | expect(printed).toContain("error: precision is not available here"); |
| 231 | 231 | }); |
| 232 | 232 | |
| 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 | ||
| 233 | 251 | test("/health asks the reader, prints a line per viewer as text, or the refusal; without a reader it says so", async () => { |
| 234 | 252 | expect(typed(emptyRoom(), "/health")).toEqual({ health: true }); |
| 235 | 253 | 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 @@ | ||
| 34 | 34 | * /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) |
| 35 | 35 | * /health owner or moderator: each open page's link as it last reported it (GET /admin/health, the page's Admin -> Health) |
| 36 | 36 | * /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 | |
| 37 | 38 | * /machine [off] the Machine panel (/machine, src/machine-feed.ts): the joints, the link and the server as they are, |
| 38 | 39 | * then every command in and out as it happens, in the page's own words (src/ui/machine.js); off stops it |
| 39 | 40 | * /who /help /quit |
| @@ -43,6 +44,7 @@ | ||
| 43 | 44 | import WebSocket from "ws"; |
| 44 | 45 | import { UNPRINTABLE } from "./chat.ts"; |
| 45 | 46 | import { ID, NAME, sign } from "./identity.ts"; |
| 47 | import { readServos, type ServoPanel } from "./servo-panel.ts"; | |
| 46 | 48 | import { headlineValue, readPrecision, sparkline, type PrecisionPanel } from "./precision-panel.ts"; |
| 47 | 49 | import { presenceText } from "./ui/lobby-panel.js"; |
| 48 | 50 | import { entryLine, jointRows, linkRows, stateRows } from "./ui/machine.js"; |
| @@ -116,6 +118,31 @@ export function reader(env: Env, fetcher: typeof fetch = fetch): Read { | ||
| 116 | 118 | }; |
| 117 | 119 | } |
| 118 | 120 | |
| 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 | ||
| 119 | 146 | /** What GET /precision answered, read as the admin panel reads it; or why not (a guest is told there is no such route). */ |
| 120 | 147 | export type Card = { status: number; error: string | null; panel: PrecisionPanel | null }; |
| 121 | 148 | export type ReadCard = () => Promise<Card>; |
| @@ -212,7 +239,7 @@ const said = (room: Room, m: unknown): string => { | ||
| 212 | 239 | }; |
| 213 | 240 | |
| 214 | 241 | 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"; | |
| 216 | 243 | |
| 217 | 244 | /** The Machine feed's socket beside the lobby's: same app, same port. */ |
| 218 | 245 | export const machineUrl = (live: string): string => live.replace(/\/live$/, "/machine"); |
| @@ -355,7 +382,7 @@ function target(room: Room, word: string): string | null { | ||
| 355 | 382 | return ID.test(word) ? word : null; |
| 356 | 383 | } |
| 357 | 384 | |
| 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; | |
| 359 | 386 | |
| 360 | 387 | /** What a typed line asks for. Validation the server repeats anyway; this only saves a round trip on a typo. */ |
| 361 | 388 | export function typed(room: Room, input: string): Typed { |
| @@ -432,6 +459,8 @@ export function typed(room: Room, input: string): Typed { | ||
| 432 | 459 | return { health: true }; |
| 433 | 460 | case "precision": |
| 434 | 461 | return { precision: true }; |
| 462 | case "servos": | |
| 463 | return { servos: true }; | |
| 435 | 464 | case "machine": |
| 436 | 465 | if (arg && arg.toLowerCase() !== "off" && arg.toLowerCase() !== "on") return { print: "usage: /machine [off]" }; |
| 437 | 466 | return { machine: arg.toLowerCase() !== "off" }; |
| @@ -459,11 +488,13 @@ export class Door { | ||
| 459 | 488 | private readonly post: Post | null; |
| 460 | 489 | private readonly read: Read | null; |
| 461 | 490 | private readonly readCard: ReadCard | null; |
| 491 | private readonly readServos: ReadServos | null; | |
| 462 | 492 | |
| 463 | 493 | /** `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) { | |
| 465 | 495 | this.read = read; |
| 466 | 496 | this.readCard = readCard; |
| 497 | this.readServos = readServos; | |
| 467 | 498 | this.url = url; |
| 468 | 499 | this.headers = headers; |
| 469 | 500 | this.print = print; |
| @@ -507,6 +538,7 @@ export class Door { | ||
| 507 | 538 | else if ("zero" in t) void this.zero(t.zero.joint, t.zero.referenceDeg); |
| 508 | 539 | else if ("health" in t) void this.health(); |
| 509 | 540 | else if ("precision" in t) void this.precision(); |
| 541 | else if ("servos" in t) void this.servos(); | |
| 510 | 542 | else if ("machine" in t) this.watchMachine(t.machine); |
| 511 | 543 | else this.send(t.send); |
| 512 | 544 | return true; |
| @@ -535,6 +567,13 @@ export class Door { | ||
| 535 | 567 | for (const line of r.error || !r.panel ? [`error: ${r.error ?? "no scorecard"}`] : precisionLines(r.panel)) this.print(line); |
| 536 | 568 | } |
| 537 | 569 | |
| 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 | ||
| 538 | 577 | /** The server decides who may; a refusal is printed, success says the offset the server now holds. */ |
| 539 | 578 | private async table(what: "here" | number | { touch: 1 | 2 | 3 }): Promise<void> { |
| 540 | 579 | if (!this.post) return this.print("error: the table is not available here"); |
Software/so101/src/tty.ts +2 −2
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | 6 | 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"; | |
| 8 | 8 | |
| 9 | 9 | const env = process.env; |
| 10 | 10 | 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) => { | ||
| 17 | 17 | rl?.prompt(true); |
| 18 | 18 | }; |
| 19 | 19 | |
| 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)); | |
| 21 | 21 | print(`\x1b[1mSO-101 arm\x1b[0m · ${where} · ${HELP}`); |
| 22 | 22 | try { |
| 23 | 23 | await door.open(() => { |
new above
offline