Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
workbenchthis machine
/admin walks the owner through aligning each joint to its mechanical reference #492
Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.
smith/arm:smith/446-admin-walks-the-owner-through-aligning-e → main 4 commits fork 1 thread · 1 unresolved
9 files
changed +265
−9
Software/README.md +11
| @@ -632,6 +632,17 @@ or from the **Admin** tab that only the owner sees: | ||
| 632 | 632 | - **Visitors** (owner only; a moderator's page has no such section, anyone else gets the 404) shows today's peak viewers and joins per hour for the last 24 hours, oldest first, as a text chart with no script. In the terminal the owner types `/visitors` for the same two numbers (anyone else is refused). Counts only, no names or addresses: the lobby counts every `/live` connect and disconnect and keeps them in `$FORGE_APP_DATA/so101/visitors.json` (saved at most once a minute and on close), so they survive a restart; the peak is per day and the hours roll off after 24. |
| 633 | 633 | - **Table height** (-100..100 mm, `tableOffsetMm`) is a number field under Table height on `/admin`: |
| 634 | 634 | Save sends `PUT /settings` and shows the saved value or the server's error. |
| 635 | - **Align joints** (owner only) lists each joint with its reference angle, the offset it holds now and a **Record** button | |
| 636 | that posts `POST /settings/joint-zero`; the row then reads the next `/status` and says **Done** when the model is within | |
| 637 | 0.5° of the reference, else to record again. In the terminal the owner types `/align` for the same list (joint, pose, offset) and | |
| 638 | `/align <joint>` to record that joint at its reference and read the same Done / record-again verdict (both doors share one rule, | |
| 639 | `alignment()` in `src/joint-reference.ts`). The references, one pose each (all 0°): | |
| 640 | - `shoulder_pan`: the arm pointing straight ahead, along the base's centre mark. | |
| 641 | - `shoulder_lift`: the upper arm upright, against its vertical mark. | |
| 642 | - `elbow_flex`: the forearm at a right angle to the upper arm, against its stop. | |
| 643 | - `wrist_flex`: the wrist in line with the forearm. | |
| 644 | - `wrist_roll`: the gripper's jaws level, matching the mark on the wrist. | |
| 645 | - `gripper`: the jaws fully closed. | |
| 635 | 646 | - **Pause the queue** for maintenance. The driver's turn ends (unless it is |
| 636 | 647 | the owner's), nobody new gets a turn, and everyone sees "Paused for |
| 637 | 648 | maintenance". People can still join the queue, and it keeps its order. |
Software/so101/src/admin-page.test.ts +33 −1
| @@ -62,6 +62,18 @@ test("a moderator sees no Unmute or Unban beside a moderator's mute or ban; the | ||
| 62 | 62 | expect(owner).toContain("Unban"); |
| 63 | 63 | }); |
| 64 | 64 | |
| 65 | test("Align joints lists every joint with its reference and a Record button, for the owner alone", () => { | |
| 66 | const owner = page(true); | |
| 67 | expect(owner).toContain('id="align"'); | |
| 68 | for (const joint of ["shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper"]) expect(owner).toContain(`data-align="${joint}" data-reference="0"`); | |
| 69 | expect(owner.match(/data-record aria-label/g)?.length).toBe(6); | |
| 70 | expect(owner).toContain("/settings/joint-zero"); | |
| 71 | expect(owner).toContain('class="offset"'); | |
| 72 | const mod = page(false); | |
| 73 | expect(mod).not.toContain("Align joints"); | |
| 74 | expect(mod).not.toContain("joint-zero"); | |
| 75 | }); | |
| 76 | ||
| 65 | 77 | test("the three touch steps post n=1,2,3 and the third shows height and tilt, or the refusal; moderators get none", async () => { |
| 66 | 78 | const owner = page(true); |
| 67 | 79 | for (const n of [1, 2, 3]) expect(owner).toContain(`id="touch-${n}"`); |
| @@ -79,7 +91,7 @@ test("the three touch steps post n=1,2,3 and the third shows height and tilt, or | ||
| 79 | 91 | return refuse ? { ok: false, status: 409, json: async () => ({ error: "the table tilts 9° (over 3°): not applied" }) } |
| 80 | 92 | : { ok: true, json: async () => ({ tableOffsetMm: 12, heightMm: 11.5, tiltDeg: 0.2, applied: true }) }; |
| 81 | 93 | }; |
| 82 | new Function("document", "fetch", "setInterval", code)({ getElementById: el }, fetchFake, () => 0); | |
| 94 | new Function("document", "fetch", "setInterval", code)({ getElementById: el, querySelectorAll: () => [] }, fetchFake, () => 0); | |
| 83 | 95 | await Bun.sleep(0); |
| 84 | 96 | await el("touch-1").on.click(); |
| 85 | 97 | expect(el("touch-note").textContent).toContain("Touch 1 stored"); |
| @@ -92,3 +104,23 @@ test("the three touch steps post n=1,2,3 and the third shows height and tilt, or | ||
| 92 | 104 | await el("touch-3").on.click(); |
| 93 | 105 | expect(el("touch-note").textContent).toContain("tilts 9°"); |
| 94 | 106 | }); |
| 107 | ||
| 108 | test("the Record button runs the shared alignment rule: Done within the tolerance, else record again", async () => { | |
| 109 | const code = /<script>([\s\S]*?)<\/script>/.exec(page(true))![1]!; | |
| 110 | const note = { textContent: "" }; | |
| 111 | const row = { dataset: { align: "wrist_flex", reference: "0" }, querySelector: (q: string) => (q === ".note" ? note : { textContent: "" }) }; | |
| 112 | let click: () => Promise<void> = async () => {}; | |
| 113 | const button = { addEventListener: (_: string, f: () => Promise<void>) => (click = f), closest: () => row }; | |
| 114 | const els = new Map<string, any>(); | |
| 115 | const el = (id: string) => els.get(id) ?? (els.set(id, { id, textContent: "", value: "", on: {}, addEventListener(t: string, f: unknown) { this.on[t] = f; } }), els.get(id)); | |
| 116 | const document = { getElementById: el, querySelectorAll: (q: string) => (q === "[data-record]" ? [button] : q === "[data-align]" ? [row] : []) }; | |
| 117 | let modelDeg = 0.3; | |
| 118 | const fetchFake = async (url: string) => ({ ok: true, json: async () => (url === "/status" ? { joints: [{ joint: "wrist_flex", modelDeg }] } : { jointOffsetsDeg: {} }) }); | |
| 119 | new Function("document", "fetch", "setInterval", code)(document, fetchFake, () => 0); | |
| 120 | await Bun.sleep(0); | |
| 121 | await click(); | |
| 122 | expect(note.textContent).toBe("Done: the model is 0.3° from the reference."); | |
| 123 | modelDeg = 2; | |
| 124 | await click(); | |
| 125 | expect(note.textContent).toBe("The model is 2° from the reference: record again."); | |
| 126 | }); |
Software/so101/src/admin-page.ts +45 −2
| @@ -13,6 +13,7 @@ import type { Snapshot } from "./turns.ts"; | ||
| 13 | 13 | import type { ViewerRow } from "./viewer-reports.ts"; |
| 14 | 14 | import type { Versions } from "./pi-deploy.ts"; |
| 15 | 15 | import { precisionSection, type PrecisionPanel } from "./precision-panel.ts"; |
| 16 | import { ALIGNED_DEG, REFERENCES, alignment } from "./joint-reference.ts"; | |
| 16 | 17 | import { servosSection, type ServoPanel } from "./servo-panel.ts"; |
| 17 | 18 | import { videoSection, type VideoCard } from "./video-panel.ts"; |
| 18 | 19 | |
| @@ -136,8 +137,43 @@ const TABLE_SCRIPT = ` | ||
| 136 | 137 | } |
| 137 | 138 | `; |
| 138 | 139 | |
| 139 | /** The page's one script: the Health refresh, and for the owner the table height saver. */ | |
| 140 | const scriptFor = (canEdit: boolean): string => (canEdit ? HEALTH_SCRIPT + TABLE_SCRIPT : HEALTH_SCRIPT); | |
| 140 | /** The owner's Align joints rows: shows each joint's offset from GET /settings, injects `alignment()` so the page and the terminal share one rule, records one with POST /settings/joint-zero, then reads the next GET /status and says how far the model is from the reference. All text, no markup. */ | |
| 141 | const ALIGN_SCRIPT = ` | |
| 142 | { | |
| 143 | const ALIGNED_DEG = ${ALIGNED_DEG}; | |
| 144 | const alignment = ${alignment.toString()}; | |
| 145 | const get = async (url) => { | |
| 146 | const r = await fetch(url, { cache: "no-store", credentials: "same-origin" }); | |
| 147 | const data = await r.json().catch(() => ({})); | |
| 148 | if (!r.ok) throw new Error(typeof data.error === "string" ? data.error : "HTTP " + r.status); | |
| 149 | return data; | |
| 150 | }; | |
| 151 | const offsets = (s) => { for (const row of document.querySelectorAll("[data-align]")) row.querySelector(".offset").textContent = (s.jointOffsetsDeg[row.dataset.align] ?? 0) + "°"; }; | |
| 152 | get("/settings").then(offsets).catch(() => {}); | |
| 153 | for (const button of document.querySelectorAll("[data-record]")) { | |
| 154 | button.addEventListener("click", async () => { | |
| 155 | const row = button.closest("[data-align]"); | |
| 156 | const note = row.querySelector(".note"); | |
| 157 | const reference = Number(row.dataset.reference); | |
| 158 | note.textContent = "Recording…"; | |
| 159 | try { | |
| 160 | const r = await fetch("/settings/joint-zero", { method: "POST", credentials: "same-origin", headers: { "content-type": "application/json" }, body: JSON.stringify({ joint: row.dataset.align, referenceDeg: reference }) }); | |
| 161 | const data = await r.json().catch(() => ({})); | |
| 162 | if (!r.ok) throw new Error(typeof data.error === "string" ? data.error : "HTTP " + r.status); | |
| 163 | offsets(data); | |
| 164 | const status = await get("/status"); | |
| 165 | const joint = (status.joints || []).find((j) => j.joint === row.dataset.align); | |
| 166 | if (!joint || typeof joint.modelDeg !== "number") { note.textContent = "Recorded; the arm gave no model angle to check."; return; } | |
| 167 | const a = alignment(joint.modelDeg, reference); | |
| 168 | note.textContent = a.done ? "Done: the model is " + a.diffDeg + "° from the reference." : "The model is " + a.diffDeg + "° from the reference: record again."; | |
| 169 | } catch (e) { note.textContent = e.message; } | |
| 170 | }); | |
| 171 | } | |
| 172 | } | |
| 173 | `; | |
| 174 | ||
| 175 | /** The page's one script: the Health refresh, and for the owner the table height saver and the joint aligner. */ | |
| 176 | const scriptFor = (canEdit: boolean): string => (canEdit ? HEALTH_SCRIPT + TABLE_SCRIPT + ALIGN_SCRIPT : HEALTH_SCRIPT); | |
| 141 | 177 | |
| 142 | 178 | const sha = (text: string) => createHash("sha256").update(text).digest("base64"); |
| 143 | 179 | |
| @@ -255,6 +291,12 @@ const visitorsSection = (v: { peak: number; hours: readonly number[] }): string | ||
| 255 | 291 | return `<section aria-labelledby="visitors"><h2 id="visitors">Visitors</h2><p>Peak viewers today: <b>${v.peak}</b></p><ol class="bars" aria-label="Joins per hour, last 24 hours, oldest first">${bars}</ol></section>`; |
| 256 | 292 | }; |
| 257 | 293 | |
| 294 | /** The owner's Align joints table: each joint's reference pose and offset, with a Record button the page script wires up. */ | |
| 295 | const alignSection = (): string => { | |
| 296 | const rows = REFERENCES.map((r) => `<tr data-align="${esc(r.joint)}" data-reference="${r.referenceDeg}"><th scope="row">${esc(r.joint.replaceAll("_", " "))}</th><td>${r.referenceDeg}°: ${esc(r.pose)}</td><td class="offset">…</td><td><button type="button" data-record aria-label="Record ${esc(r.joint.replaceAll("_", " "))} at its reference">Record</button></td><td class="note" role="status"></td></tr>`).join(""); | |
| 297 | return `<section aria-labelledby="align"><h2 id="align">Align joints</h2><p class="empty">Put a joint at its reference by hand, then press Record: the model reads that angle from then on. Done is within ${ALIGNED_DEG}°.</p><div class="scroll"><table aria-label="Align joints"><thead><tr><th scope="col">Joint</th><th scope="col">Reference</th><th scope="col">Offset</th><th scope="col">Record</th><th scope="col">Check</th></tr></thead><tbody>${rows}</tbody></table></div></section>`; | |
| 298 | }; | |
| 299 | ||
| 258 | 300 | /** The two commits side by side; a mismatch says so, with what the last attempt to fix it came to. */ |
| 259 | 301 | function versionsSection(v: Versions): string { |
| 260 | 302 | const same = v.pi === v.app; |
| @@ -313,6 +355,7 @@ ${p.canEdit ? `<section aria-labelledby="table"><h2 id="table">Table height</h2> | ||
| 313 | 355 | </ol> |
| 314 | 356 | <p id="touch-note" role="status">Each touch must come within a minute of the last; the third sets the table height and reports its tilt.</p> |
| 315 | 357 | </section>` : ""} |
| 358 | ${p.canEdit ? alignSection() : ""} | |
| 316 | 359 | ${p.canEdit && p.visitors ? visitorsSection(p.visitors) : ""} |
| 317 | 360 | ${p.versions ? versionsSection(p.versions) : ""} |
| 318 | 361 | ${p.precision !== undefined ? precisionSection(p.precision, esc) : ""} |
Software/so101/src/joint-reference.ts added +34
| @@ -0,0 +1,34 @@ | ||
| 1 | /** The mechanical references the owner aligns each joint to on /admin, one pose per joint. */ | |
| 2 | ||
| 3 | /** Within this many degrees of the reference, a joint counts as aligned. */ | |
| 4 | export const ALIGNED_DEG = 0.5; | |
| 5 | ||
| 6 | export interface Reference { joint: string; referenceDeg: number; pose: string } | |
| 7 | ||
| 8 | export const REFERENCES: readonly Reference[] = [ | |
| 9 | { joint: "shoulder_pan", referenceDeg: 0, pose: "the arm pointing straight ahead, along the base's centre mark" }, | |
| 10 | { joint: "shoulder_lift", referenceDeg: 0, pose: "the upper arm upright, against its vertical mark" }, | |
| 11 | { joint: "elbow_flex", referenceDeg: 0, pose: "the forearm at a right angle to the upper arm, against its stop" }, | |
| 12 | { joint: "wrist_flex", referenceDeg: 0, pose: "the wrist in line with the forearm" }, | |
| 13 | { joint: "wrist_roll", referenceDeg: 0, pose: "the gripper's jaws level, matching the mark on the wrist" }, | |
| 14 | { joint: "gripper", referenceDeg: 0, pose: "the jaws fully closed" }, | |
| 15 | ]; | |
| 16 | ||
| 17 | /** How far the model's angle is from the reference now, and whether that is aligned; null when the model gave no angle. */ | |
| 18 | export function alignment(modelDeg: number | null | undefined, referenceDeg: number): { diffDeg: number; done: boolean } | null { | |
| 19 | if (typeof modelDeg !== "number" || !Number.isFinite(modelDeg)) return null; | |
| 20 | const diffDeg = Math.round((modelDeg - referenceDeg) * 100) / 100 + 0; | |
| 21 | return { diffDeg, done: Math.abs(diffDeg) <= ALIGNED_DEG }; | |
| 22 | } | |
| 23 | ||
| 24 | /** One line per joint for the terminal's /align: the reference, the pose and the offset it holds now. */ | |
| 25 | export function referenceLines(offsets: Record<string, number>): string[] { | |
| 26 | return REFERENCES.map((r) => `${r.joint}: ${r.referenceDeg}° is ${r.pose}; offset ${offsets[r.joint] ?? 0}°`); | |
| 27 | } | |
| 28 | ||
| 29 | /** What to tell the owner after a record, from the same rule as the page: Done, or record again. */ | |
| 30 | export function verdictLine(joint: string, referenceDeg: number, modelDeg: number | null | undefined): string { | |
| 31 | const a = alignment(modelDeg, referenceDeg); | |
| 32 | if (!a) return `${joint} recorded; the arm gave no model angle to check`; | |
| 33 | return a.done ? `${joint} done: the model is ${a.diffDeg}° from the reference` : `${joint}: the model is ${a.diffDeg}° from the reference; record again`; | |
| 34 | } |
Software/so101/src/server.test.ts +23
| @@ -9,6 +9,7 @@ import { FeetechBus } from "./bus.ts"; | ||
| 9 | 9 | import { FakeBus } from "./fake-bus.ts"; |
| 10 | 10 | import { mapFrame } from "./leader.ts"; |
| 11 | 11 | import { startServer, type RunningServer } from "./server.ts"; |
| 12 | import { alignment, REFERENCES } from "./joint-reference.ts"; | |
| 12 | 13 | |
| 13 | 14 | const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); |
| 14 | 15 | let fake: FakeBus; |
| @@ -759,6 +760,28 @@ describe("the safe zone, the jam watch, and the model routes", () => { | ||
| 759 | 760 | await zcall("/settings", { zone: "enforce" }, "PUT"); |
| 760 | 761 | }); |
| 761 | 762 | |
| 763 | test("recording a joint reference leaves the next status reading the reference, which /admin calls aligned", async () => { | |
| 764 | const saved = (await (await fetch(`${zurl}/settings`)).json()) as { jointOffsetsDeg: Record<string, number> }; | |
| 765 | const pan = 1; | |
| 766 | try { | |
| 767 | fake6.servos.get(pan)!.set([ticks(pan, 2) & 0xff, ticks(pan, 2) >> 8], 56); // 2° off the model's zero | |
| 768 | const reference = REFERENCES.find((r) => r.joint === "shoulder_pan")!; | |
| 769 | const res = await zcall("/settings/joint-zero", { joint: reference.joint, referenceDeg: reference.referenceDeg }); | |
| 770 | expect(res.status).toBe(200); | |
| 771 | const status = (await (await fetch(`${zurl}/status`)).json()) as { joints: Array<{ joint: string; modelDeg: number | null }> }; | |
| 772 | const verdict = alignment(status.joints.find((j) => j.joint === reference.joint)!.modelDeg, reference.referenceDeg); | |
| 773 | expect(verdict?.done).toBe(true); | |
| 774 | expect(Math.abs(verdict!.diffDeg)).toBeLessThanOrEqual(0.5); | |
| 775 | // the arm moves 3° after the record: the model is no longer at the reference | |
| 776 | fake6.servos.get(pan)!.set([ticks(pan, 5) & 0xff, ticks(pan, 5) >> 8], 56); | |
| 777 | const moved = (await (await fetch(`${zurl}/status`)).json()) as { joints: Array<{ joint: string; modelDeg: number | null }> }; | |
| 778 | expect(alignment(moved.joints.find((j) => j.joint === reference.joint)!.modelDeg, reference.referenceDeg)?.done).toBe(false); | |
| 779 | } finally { | |
| 780 | fake6.servos.get(pan)!.set([mid(pan) & 0xff, mid(pan) >> 8], 56); | |
| 781 | await zcall("/settings", { jointOffsetsDeg: { shoulder_pan: saved.jointOffsetsDeg.shoulder_pan ?? 0 } }, "PUT"); | |
| 782 | } | |
| 783 | }); | |
| 784 | ||
| 762 | 785 | test("joint-zero trims one joint so the model reads the reference; a block still fires at the same physical pose", async () => { |
| 763 | 786 | const saved = (await (await fetch(`${zurl}/settings`)).json()) as { zone: string; jointOffsetsDeg: Record<string, number> }; |
| 764 | 787 | const lift = 2; // shoulder_lift |
Software/so101/src/server.ts +3
| @@ -598,11 +598,14 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}): | ||
| 598 | 598 | torqueAt = performance.now(); |
| 599 | 599 | } |
| 600 | 600 | const b = bounds(); |
| 601 | const q = model ? toQ(positions) : null; | |
| 601 | 602 | const joints = ids.map((id) => ({ |
| 602 | 603 | id, |
| 603 | 604 | joint: JOINTS[id] ?? null, |
| 604 | 605 | position: positions.get(id) ?? null, |
| 605 | 606 | degrees: positions.has(id) ? Number(ticksToDegrees(positions.get(id)!).toFixed(1)) : null, |
| 607 | /** The angle the model reads for this joint, trims applied, degrees; null without a model. */ | |
| 608 | modelDeg: q?.has(JOINTS[id] ?? "") ? Number(((q.get(JOINTS[id]!)! * 180) / Math.PI).toFixed(2)) : null, | |
| 606 | 609 | load: loads.has(id) ? loads.get(id)! / 10 : null, |
| 607 | 610 | temperature: temps.get(id) ?? null, |
| 608 | 611 | torque: torque.has(id) ? torque.get(id) === 1 : null, |
Software/so101/src/terminal.test.ts +58 −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, servosLines, servosReader, emptyRoom, hear, precisionLines, liveUrl, machineEntry, machineLines, machineUrl, healthLines, plain, poster, reader, terminalHeaders, typed } from "./terminal.ts"; | |
| 15 | import { alignReader, 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 | |
| @@ -154,6 +154,63 @@ describe("terminal table", () => { | ||
| 154 | 154 | expect(asked).toEqual([["/settings/joint-zero", { joint: "shoulder_pan", referenceDeg: 5 }], ["/settings/joint-zero", { joint: "elbow_flex", referenceDeg: 0 }]]); |
| 155 | 155 | }); |
| 156 | 156 | |
| 157 | test("/align lists the references and offsets; /align <joint> records at the reference and gives the verdict", async () => { | |
| 158 | const room = emptyRoom(); | |
| 159 | expect(typed(room, "/align")).toEqual({ align: null }); | |
| 160 | expect(typed(room, "/align wrist_flex")).toEqual({ align: "wrist_flex" }); | |
| 161 | for (const bad of ["/align nope", "/align wrist_flex 1"]) expect(typed(room, bad)).toEqual({ print: expect.stringContaining("usage: /align") }); | |
| 162 | const printed: string[] = []; | |
| 163 | const asked: unknown[] = []; | |
| 164 | let modelDeg: number | null = 0.2; | |
| 165 | const door = new Door("ws://127.0.0.1:1/live", {}, (l) => printed.push(l), async (path, body) => { | |
| 166 | asked.push([path, body]); | |
| 167 | return { status: 200, error: null, offsetDeg: 1 }; | |
| 168 | }, null, null, null, null, async () => ({ error: null, offsets: { wrist_flex: 1.5 }, modelDeg: { wrist_flex: modelDeg } })); | |
| 169 | door.input("/align"); | |
| 170 | await Bun.sleep(20); | |
| 171 | expect(printed).toHaveLength(6); | |
| 172 | expect(printed).toContain("wrist_flex: 0° is the wrist in line with the forearm; offset 1.5°"); | |
| 173 | expect(printed).toContain("shoulder_pan: 0° is the arm pointing straight ahead, along the base's centre mark; offset 0°"); | |
| 174 | printed.length = 0; | |
| 175 | door.input("/align wrist_flex"); | |
| 176 | await Bun.sleep(20); | |
| 177 | expect(asked).toEqual([["/settings/joint-zero", { joint: "wrist_flex", referenceDeg: 0 }]]); | |
| 178 | expect(printed).toEqual(["wrist_flex done: the model is 0.2° from the reference"]); | |
| 179 | printed.length = 0; | |
| 180 | modelDeg = 3; | |
| 181 | door.input("/align wrist_flex"); | |
| 182 | await Bun.sleep(20); | |
| 183 | expect(printed).toEqual(["wrist_flex: the model is 3° from the reference; record again"]); | |
| 184 | const refused = new Door("ws://127.0.0.1:1/live", {}, (l) => printed.push(l), async () => ({ status: 404, error: "not found" }), null, null, null, null, async () => ({ error: "not found", offsets: {}, modelDeg: {} })); | |
| 185 | printed.length = 0; | |
| 186 | refused.input("/align"); | |
| 187 | refused.input("/align wrist_flex"); | |
| 188 | await Bun.sleep(20); | |
| 189 | expect(printed).toEqual(["error: not found", "error: not found"]); | |
| 190 | }); | |
| 191 | ||
| 192 | test("alignReader signs GET /settings and /status, merges them, drops non-numbers, and turns a refusal or a thrown fetch into an error", async () => { | |
| 193 | const env = { PORT: "9", FORGE_APP_IDENTITY_KEY: "k".repeat(32), FORGE_APP_USER_ID: "u-owner", FORGE_APP_USER: "owner", FORGE_APP_USER_ROLE: "admin" }; | |
| 194 | const seen: Array<{ url: string; signed: boolean }> = []; | |
| 195 | const answer = (routes: Record<string, [number, unknown]>) => (async (url: unknown, init: RequestInit = {}) => { | |
| 196 | const path = new URL(String(url)).pathname; | |
| 197 | seen.push({ url: path, signed: Boolean((init.headers as Record<string, string>)["x-forge-signature"]) }); | |
| 198 | const [status, body] = routes[path]!; | |
| 199 | return new Response(JSON.stringify(body), { status }); | |
| 200 | }) as never; | |
| 201 | const good = { "/settings": [200, { jointOffsetsDeg: { wrist_flex: 1.5, elbow_flex: "x" } }], "/status": [200, { joints: [{ joint: "wrist_flex", modelDeg: 0.2 }, { joint: "gripper", modelDeg: "no" }, { joint: "elbow_flex" }, { id: 9 }] }] } as Record<string, [number, unknown]>; | |
| 202 | expect(await alignReader(env, answer(good))()).toEqual({ error: null, offsets: { wrist_flex: 1.5 }, modelDeg: { wrist_flex: 0.2, gripper: null, elbow_flex: null } }); | |
| 203 | expect(seen.map((x) => x.url).sort()).toEqual(["/settings", "/status"]); | |
| 204 | expect(seen.every((x) => x.signed)).toBe(true); | |
| 205 | for (const [route, status] of [["/settings", 404], ["/settings", 403], ["/status", 404], ["/status", 403]] as const) { | |
| 206 | const r = await alignReader(env, answer({ ...good, [route]: [status, { error: "no" }] }))(); | |
| 207 | expect(r).toEqual({ error: "no", offsets: {}, modelDeg: {} }); | |
| 208 | } | |
| 209 | expect(await alignReader(env, answer({ ...good, "/settings": [404, null] }))()).toEqual({ error: "status 404", offsets: {}, modelDeg: {} }); | |
| 210 | const thrown = (async () => { throw new Error("down"); }) as never; | |
| 211 | expect(await alignReader(env, thrown)()).toEqual({ error: "down", offsets: {}, modelDeg: {} }); | |
| 212 | }); | |
| 213 | ||
| 157 | 214 | test("the poster returns the offset joint-zero applied", async () => { |
| 158 | 215 | const env = { PORT: "9", FORGE_APP_IDENTITY_KEY: "k".repeat(32), FORGE_APP_USER_ID: "u-owner", FORGE_APP_USER: "owner", FORGE_APP_USER_ROLE: "admin" }; |
| 159 | 216 | const fetcher = (async () => new Response(JSON.stringify({ offsetDeg: 2.5 }), { status: 200 })) as never; |
Software/so101/src/terminal.ts +56 −3
| @@ -32,6 +32,7 @@ | ||
| 32 | 32 | * /table touch 1|2|3 admin: touch the table with the gripper tip at three points; the third fits the plane (POST /settings/table-touch) |
| 33 | 33 | * /table <mm> admin: set the table offset, -100..100 mm (PUT /settings tableOffsetMm) |
| 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 | * /align [joint] admin: list each joint's reference pose and offset; with a joint, record it at its reference (POST /settings/joint-zero) and say Done or record again | |
| 35 | 36 | * /health owner or moderator: each open page's link as it last reported it (GET /admin/health, the page's Admin -> Health) |
| 36 | 37 | * /versions owner or moderator: the app's and the Pi's commits and the last sync (GET /admin/versions) |
| 37 | 38 | * /precision owner or moderator: the precision scorecard /admin shows (GET /precision, src/precision-panel.ts) |
| @@ -43,6 +44,7 @@ | ||
| 43 | 44 | */ |
| 44 | 45 | |
| 45 | 46 | import WebSocket from "ws"; |
| 47 | import { REFERENCES, referenceLines, verdictLine } from "./joint-reference.ts"; | |
| 46 | 48 | import { UNPRINTABLE } from "./chat.ts"; |
| 47 | 49 | import { ID, NAME, sign } from "./identity.ts"; |
| 48 | 50 | import { readServos, type ServoPanel } from "./servo-panel.ts"; |
| @@ -137,6 +139,34 @@ export function versionsReader(env: Env, fetcher: typeof fetch = fetch): ReadVer | ||
| 137 | 139 | }; |
| 138 | 140 | } |
| 139 | 141 | |
| 142 | /** The offsets GET /settings holds and the angles GET /status says the model reads, or why not. */ | |
| 143 | export type Aligned = { error: string | null; offsets: Record<string, number>; modelDeg: Record<string, number | null> }; | |
| 144 | export type ReadAlign = () => Promise<Aligned>; | |
| 145 | ||
| 146 | /** GET /settings and /status as the Align joints rows do, signed afresh; the server decides who may. */ | |
| 147 | export function alignReader(env: Env, fetcher: typeof fetch = fetch): ReadAlign { | |
| 148 | const get = async (path: string): Promise<{ ok: boolean; status: number; body: Record<string, unknown> }> => { | |
| 149 | const r = await fetcher(`${appUrl(env)}${path}`, { headers: terminalHeaders(env), signal: AbortSignal.timeout(5000) }); | |
| 150 | return { ok: r.ok, status: r.status, body: ((await r.json().catch(() => null)) as Record<string, unknown> | null) ?? {} }; | |
| 151 | }; | |
| 152 | return async () => { | |
| 153 | try { | |
| 154 | const [settings, status] = await Promise.all([get("/settings"), get("/status")]); | |
| 155 | if (!settings.ok || !status.ok) { | |
| 156 | const bad = settings.ok ? status : settings; | |
| 157 | return { error: plain(bad.body.error ?? `status ${bad.status}`), offsets: {}, modelDeg: {} }; | |
| 158 | } | |
| 159 | const offsets: Record<string, number> = {}; | |
| 160 | for (const [k, v] of Object.entries((settings.body.jointOffsetsDeg ?? {}) as Record<string, unknown>)) if (typeof v === "number") offsets[k] = v; | |
| 161 | const modelDeg: Record<string, number | null> = {}; | |
| 162 | if (Array.isArray(status.body.joints)) for (const j of status.body.joints as { joint?: unknown; modelDeg?: unknown }[]) if (typeof j.joint === "string") modelDeg[j.joint] = typeof j.modelDeg === "number" ? j.modelDeg : null; | |
| 163 | return { error: null, offsets, modelDeg }; | |
| 164 | } catch (err) { | |
| 165 | return { error: plain((err as Error).message), offsets: {}, modelDeg: {} }; | |
| 166 | } | |
| 167 | }; | |
| 168 | } | |
| 169 | ||
| 140 | 170 | /** 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). */ |
| 141 | 171 | export type Servos = { status: number; error: string | null; panel: ServoPanel | null }; |
| 142 | 172 | export type ReadServos = () => Promise<Servos>; |
| @@ -265,7 +295,7 @@ const said = (room: Room, m: unknown): string => { | ||
| 265 | 295 | }; |
| 266 | 296 | |
| 267 | 297 | const ZERO_USAGE = "usage: /zero <joint, e.g. shoulder_pan> [degrees the model should read, default 0]"; |
| 268 | 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 /versions (owner, moderator) · /servos (owner) · /machine [off] · /who · /quit"; | |
| 298 | 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] /align [joint] (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 /versions (owner, moderator) · /servos (owner) · /machine [off] · /who · /quit"; | |
| 269 | 299 | |
| 270 | 300 | /** The Machine feed's socket beside the lobby's: same app, same port. */ |
| 271 | 301 | export const machineUrl = (live: string): string => live.replace(/\/live$/, "/machine"); |
| @@ -408,7 +438,7 @@ function target(room: Room, word: string): string | null { | ||
| 408 | 438 | return ID.test(word) ? word : null; |
| 409 | 439 | } |
| 410 | 440 | |
| 411 | 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 } | { versions: true } | { quit: true } | null; | |
| 441 | export type Typed = { send: Frame } | { post: "/stop" | "/resume" } | { table: "here" | number | { touch: 1 | 2 | 3 } } | { zero: { joint: string; referenceDeg: number } } | { align: string | null } | { print: string } | { lines: string[] } | { machine: boolean } | { health: true } | { precision: true } | { servos: true } | { versions: true } | { quit: true } | null; | |
| 412 | 442 | |
| 413 | 443 | /** What a typed line asks for. Validation the server repeats anyway; this only saves a round trip on a typo. */ |
| 414 | 444 | export function typed(room: Room, input: string): Typed { |
| @@ -416,6 +446,10 @@ export function typed(room: Room, input: string): Typed { | ||
| 416 | 446 | if (!line) return null; |
| 417 | 447 | if (!line.startsWith("/")) return { send: { type: "post", text: line } }; |
| 418 | 448 | const [verb = "", arg = "", ...rest] = line.slice(1).split(/\s+/); |
| 449 | if (/^align$/i.test(verb)) { | |
| 450 | if (rest.length || (arg && !REFERENCES.some((r) => r.joint === arg))) return { print: `usage: /align [${REFERENCES.map((r) => r.joint).join("|")}]` }; | |
| 451 | return { align: arg || null }; | |
| 452 | } | |
| 419 | 453 | if (/^zero$/i.test(verb)) { |
| 420 | 454 | const [deg = "0", ...extra] = rest.length ? [rest[0]!, ...rest.slice(1)] : []; |
| 421 | 455 | if (!/^[a-z_]{1,24}$/.test(arg) || extra.length || !/^-?\d{1,3}(\.\d{1,3})?$/.test(deg)) return { print: ZERO_USAGE }; |
| @@ -518,9 +552,11 @@ export class Door { | ||
| 518 | 552 | private readonly readCard: ReadCard | null; |
| 519 | 553 | private readonly readServos: ReadServos | null; |
| 520 | 554 | private readonly readVersions: ReadVersions | null; |
| 555 | private readonly readAlign: ReadAlign | null; | |
| 521 | 556 | |
| 522 | 557 | /** `post` reaches the app's /stop and /resume, `read` its /admin/health, `readCard` its /precision; without them, the door says it cannot. */ |
| 523 | 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, readVersions: ReadVersions | null = null) { | |
| 558 | 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, readVersions: ReadVersions | null = null, readAlign: ReadAlign | null = null) { | |
| 559 | this.readAlign = readAlign; | |
| 524 | 560 | this.readVersions = readVersions; |
| 525 | 561 | this.read = read; |
| 526 | 562 | this.readCard = readCard; |
| @@ -566,6 +602,7 @@ export class Door { | ||
| 566 | 602 | else if ("post" in t) void this.ask(t.post); |
| 567 | 603 | else if ("table" in t) void this.table(t.table); |
| 568 | 604 | else if ("zero" in t) void this.zero(t.zero.joint, t.zero.referenceDeg); |
| 605 | else if ("align" in t) void this.align(t.align); | |
| 569 | 606 | else if ("health" in t) void this.health(); |
| 570 | 607 | else if ("precision" in t) void this.precision(); |
| 571 | 608 | else if ("servos" in t) void this.servos(); |
| @@ -629,6 +666,22 @@ export class Door { | ||
| 629 | 666 | else this.print(r.offsetDeg === undefined ? `${joint} zeroed` : `${joint} offset is ${r.offsetDeg}°`); |
| 630 | 667 | } |
| 631 | 668 | |
| 669 | /** The server decides who may. Without a joint: the references and offsets. With one: record it at its reference, then say Done or record again from the next status. */ | |
| 670 | private async align(joint: string | null): Promise<void> { | |
| 671 | if (!this.readAlign) return this.print("error: aligning is not available here"); | |
| 672 | if (joint === null) { | |
| 673 | const r = await this.readAlign(); | |
| 674 | for (const line of r.error ? [`error: ${r.error}`] : referenceLines(r.offsets)) this.print(line); | |
| 675 | return; | |
| 676 | } | |
| 677 | if (!this.post) return this.print("error: aligning is not available here"); | |
| 678 | const reference = REFERENCES.find((x) => x.joint === joint)!.referenceDeg; | |
| 679 | const z = await this.post("/settings/joint-zero", { joint, referenceDeg: reference }); | |
| 680 | if (z.error) return this.print(`error: ${z.error}`); | |
| 681 | const r = await this.readAlign(); | |
| 682 | this.print(r.error ? `error: ${r.error}` : verdictLine(joint, reference, r.modelDeg[joint])); | |
| 683 | } | |
| 684 | ||
| 632 | 685 | close(): void { |
| 633 | 686 | this.ws?.close(); |
| 634 | 687 | this.machineWs?.close(); |
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, servosReader, terminalHeaders, versionsReader } from "./terminal.ts"; | |
| 7 | import { alignReader, cardReader, Door, HELP, liveUrl, poster, reader, servosReader, terminalHeaders, versionsReader } 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), servosReader(env), versionsReader(env)); | |
| 20 | const door = new Door(liveUrl(env), terminalHeaders(env), print, poster(env), reader(env), cardReader(env), servosReader(env), versionsReader(env), alignReader(env)); | |
| 21 | 21 | print(`\x1b[1mSO-101 arm\x1b[0m · ${where} · ${HELP}`); |
| 22 | 22 | try { |
| 23 | 23 | await door.open(() => { |
new above
offline
Only the tests call this. The page script duplicates the rule and the terminal does not use it. Make it the single source of the verdict, used by the terminal and the page, or remove it.