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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

Leader calibration: each driver calibrates their leader arm once and it maps cleanly onto the follower #27

Merged opened this in answer to

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

Merged

quill/arm:quill/19-leader-calibration-each-driver-calibrate → main 2 commits fork 2 threads · 2 unresolved

  • Merged. quill/19-leader-calibration-each-driver-calibrate was merged into main as 9c72905.

Review

Sign in to review this change.
10 files changed +508 −8
Software/README.md +28
@@ -218,6 +218,34 @@ trusts nothing else (`src/identity.ts`). Run locally (no `FORGE_APP_ENV`,
218218 no key), nobody signs in and every visitor drives, as before. Anonymous
219219 viewing needs the app set to public on the forge.
220220
221 **Your own leader arm, calibrated once.** No two leaders read the same: a
222 servo sits a few hundred ticks round its dial, a horn goes on the other way
223 round, a joint stops short. **Calibrate leader** (Chrome, with the leader
224 plugged into your computer) walks you through it. You don't need the turn,
225 and the real arm doesn't move. First connect the leader; its motors go limp.
226 Then hold it in the middle pose the 3D model shows. Then, joint by joint,
227 take it to each end the model shows. The last step shows the model following
228 your leader through the new calibration, with a **Flip** per joint in case
229 one turned the wrong way. **Save** keeps it with your forge account, so it
230 follows you to any computer. Press the button again to recalibrate any time.
231
232 For each leader joint, the calibration stores three readings: `low`,
233 `centre` and `high` (`src/leader-map.js`). From these the page gets each
234 joint's offset (the centre lands on the middle of the follower's range), its
235 direction (`low` above `high` means the joint is mounted backwards), and its
236 scale, set separately on each side of the centre. A short or lopsided leader
237 still reaches both ends of the follower, and goes no further. The gripper
238 maps closed to closed and open to open. **Live from leader** applies this in
239 the browser before a frame leaves. Without a calibration, it falls back to
240 the leader servos' stored limits. The server still clamps every frame to the
241 follower's limits. `GET`, `PUT` and `DELETE /leader/calibration` act on the
242 signed-in person's own calibration. A `PUT` is validated against the same
243 module: whole ticks only, and each end at least 100 ticks from the centre on
244 opposite sides. Calibrations are kept in
245 `$FORGE_APP_DATA/so101/leader-calibrations.json`. `src/leader-map.js` is
246 plain JavaScript with JSDoc types, so the browser imports the same file the
247 server validates with and the tests check.
248
221249 **The safe zone.** The server loads `Simulation/SO101/so101_new_calib.urdf`
222250 and its meshes (`--model <dir>`, or the repo layout, or `model/` beside the
223251 package) and runs every target through the arm's geometry: a pose that puts
Software/so101/bench/fake-serve.ts +3 −1
@@ -13,6 +13,7 @@ import { tmpdir } from "node:os";
1313 import { join } from "node:path";
1414 import { FeetechBus } from "../src/bus.ts";
1515 import { FakeBus } from "../src/fake-bus.ts";
16 import { LeaderCalibrations } from "../src/leader-calibrations.ts";
1617 import { Lobby } from "../src/lobby.ts";
1718 import { parseRemote, startRelay, type Remote } from "../src/relay.ts";
1819 import { startServer } from "../src/server.ts";
@@ -40,6 +41,7 @@ try {
4041 const identityKey = process.env.FORGE_APP_IDENTITY_KEY ?? "";
4142 const local = !identityKey && !process.env.FORGE_APP_ENV;
4243 const lobby = new Lobby({ identityKey, local, chatFile: join(dir, "chat.json") });
43 const relay = await startRelay({ host, port, simulation: `http://127.0.0.1:${simulation.port}`, remote, problem, lobby });
44 const leaders = new LeaderCalibrations({ file: join(dir, "leader-calibrations.json") });
45 const relay = await startRelay({ host, port, simulation: `http://127.0.0.1:${simulation.port}`, remote, problem, lobby, leaders });
4446 const { mode, host: armHost } = relay.link();
4547 console.log(`arm on http://${host}:${relay.port} (${mode === "live" ? `live arm ${armHost}` : "simulated"}; data in ${dir}${local ? "; local: every visitor drives as the owner" : ""})`);
Software/so101/src/leader-calibrations.ts added +70
@@ -0,0 +1,70 @@
1 /**
2 * Every driver's leader calibration, kept by their forge user id so it follows them to any computer. Validated by
3 * src/leader-map.js on the way in and again on load. One JSON file beside the chat, rewritten whole on each change
4 * (a few hundred bytes per driver).
5 */
6
7 import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
8 import { dirname } from "node:path";
9 import { parseCalibration, type LeaderCalibration } from "./leader-map.js";
10
11 export interface LeaderCalibrationsOptions {
12 /** Where they live; none keeps them in memory. */
13 file?: string;
14 now?: () => Date;
15 }
16
17 export class LeaderCalibrations {
18 private readonly byUser = new Map<string, LeaderCalibration>();
19 private readonly file: string | undefined;
20 private readonly now: () => Date;
21
22 constructor(options: LeaderCalibrationsOptions = {}) {
23 this.file = options.file;
24 this.now = options.now ?? (() => new Date());
25 if (this.file) this.load(this.file);
26 }
27
28 get(userId: string): LeaderCalibration | null {
29 return this.byUser.get(userId) ?? null;
30 }
31
32 /** Throws CalibrationError on a body that is not a calibration; returns what was stored. */
33 put(userId: string, body: unknown): LeaderCalibration {
34 const calibration = { ...parseCalibration(body), saved: this.now().toISOString() };
35 this.byUser.set(userId, calibration);
36 this.save();
37 return calibration;
38 }
39
40 delete(userId: string): boolean {
41 const had = this.byUser.delete(userId);
42 if (had) this.save();
43 return had;
44 }
45
46 private load(file: string): void {
47 let stored: unknown;
48 try {
49 stored = JSON.parse(readFileSync(file, "utf8"));
50 } catch {
51 return; // none yet, or unreadable: start over rather than refuse to start
52 }
53 if (typeof stored !== "object" || stored === null) return;
54 for (const [id, value] of Object.entries(stored)) {
55 try {
56 const saved = (value as { saved?: unknown })?.saved;
57 this.byUser.set(id, { ...parseCalibration(value), ...(typeof saved === "string" ? { saved } : {}) });
58 } catch {
59 /* a calibration this version no longer accepts: that driver calibrates again */
60 }
61 }
62 }
63
64 private save(): void {
65 if (!this.file) return;
66 mkdirSync(dirname(this.file), { recursive: true });
67 writeFileSync(`${this.file}.tmp`, JSON.stringify(Object.fromEntries(this.byUser)));
68 renameSync(`${this.file}.tmp`, this.file);
69 }
70 }
Software/so101/src/leader-map.js added +98
@@ -0,0 +1,98 @@
1 // @ts-check
2 /**
3 * A driver's own leader arm, calibrated once, mapped onto the follower. Plain JavaScript so the browser imports
4 * the very file the server validates with and the tests check (GET /leader-map.js); typed with JSDoc.
5 *
6 * A calibration names, per leader servo, three ticks read off the leader by hand: `low`, where the leader sits
7 * when the follower would be at the low end of its calibrated range; `high`, the same for the high end; and
8 * `centre`, the leader in the follower's middle pose. That carries everything a leader can differ by:
9 * offset the centre is anywhere on the leader's dial; it lands on the middle of the follower's range
10 * direction low above high is a joint mounted the other way round, and it is turned back
11 * range each side of the centre is scaled onto the follower's side, so a short or lopsided leader
12 * still reaches both of the follower's ends, and no further
13 * The gripper's centre is the middle of its travel: closed is low, open is high.
14 * The server clamps every frame to the follower's limits again; the mapping only aims inside them.
15 */
16
17 /** @typedef {{ low: number, centre: number, high: number }} JointCalibration */
18 /** @typedef {{ joints: Record<string, JointCalibration>, saved?: string }} LeaderCalibration */
19 /** @typedef {{ min: number, max: number }} Range */
20
21 export const IDS = [1, 2, 3, 4, 5, 6];
22 export const GRIPPER = 6;
23 /** Fewer ticks than this between the centre and an end (about 9°) is a capture that went wrong, not a joint. */
24 export const MIN_SPAN = 100;
25 /** How far inside the follower's limits an arm joint aims; the gripper may close all the way. */
26 export const MARGIN = 30;
27
28 const TICK = (/** @type {unknown} */ v) => typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 4095;
29
30 export class CalibrationError extends Error {}
31
32 /**
33 * A calibration from untrusted JSON, or a CalibrationError naming what is wrong. Only what is listed here survives.
34 * @param {unknown} body
35 * @returns {LeaderCalibration}
36 */
37 export function parseCalibration(body) {
38 if (typeof body !== "object" || body === null || Array.isArray(body)) throw new CalibrationError("a calibration is a JSON object");
39 const joints = /** @type {{ joints?: unknown }} */ (body).joints;
40 if (typeof joints !== "object" || joints === null || Array.isArray(joints)) throw new CalibrationError("joints: an object of servo id → {low, centre, high}");
41 /** @type {Record<string, JointCalibration>} */
42 const out = {};
43 for (const [id, joint] of Object.entries(joints)) {
44 if (!IDS.includes(Number(id)) || String(Number(id)) !== id) throw new CalibrationError(`joints: no servo ${JSON.stringify(id).slice(0, 20)}`);
45 const j = /** @type {Record<string, unknown>} */ (joint ?? {});
46 const { low, centre, high } = j;
47 if (!TICK(low) || !TICK(centre) || !TICK(high)) throw new CalibrationError(`joint ${id}: low, centre and high are whole ticks from 0 to 4095`);
48 const [l, c, h] = /** @type {[number, number, number]} */ ([low, centre, high]);
49 if (Math.abs(h - c) < MIN_SPAN || Math.abs(l - c) < MIN_SPAN) throw new CalibrationError(`joint ${id}: each end must be at least ${MIN_SPAN} ticks from the centre`);
50 if (Math.sign(h - c) === Math.sign(l - c)) throw new CalibrationError(`joint ${id}: the centre must lie between the two ends`);
51 out[id] = { low: l, centre: c, high: h };
52 }
53 if (!Object.keys(out).length) throw new CalibrationError("joints: calibrate at least one");
54 return { joints: out };
55 }
56
57 /** @param {number} v @param {number} lo @param {number} hi */
58 const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
59
60 /**
61 * One leader reading → one follower target, in ticks.
62 * @param {number} ticks the leader servo's Present_Position
63 * @param {JointCalibration} cal
64 * @param {Range} follower the follower servo's calibrated limits
65 * @param {number} margin
66 */
67 export function mapCalibrated(ticks, cal, follower, margin = MARGIN) {
68 const mid = (follower.min + follower.max) / 2;
69 const up = (ticks - cal.centre) / (cal.high - cal.centre); // 0 at the centre, 1 at the high end, negative toward low
70 const target = up >= 0 ? mid + Math.min(up, 1) * (follower.max - mid) : mid - Math.min((ticks - cal.centre) / (cal.low - cal.centre), 1) * (mid - follower.min);
71 return clamp(Math.round(target), follower.min + margin, follower.max - margin);
72 }
73
74 /**
75 * The gripper's centre is the middle of its travel, whatever was held during the centre pose.
76 * @param {JointCalibration} cal
77 * @returns {JointCalibration}
78 */
79 export const gripperCalibration = (cal) => ({ low: cal.low, high: cal.high, centre: Math.round((cal.low + cal.high) / 2) });
80
81 /**
82 * A whole leader reading → a frame for /follow. Joints without a calibration or a follower limit are left out.
83 * @param {Iterable<[number, number]>} positions leader servo id → ticks
84 * @param {LeaderCalibration} calibration
85 * @param {Record<string, Range>} followerLimits
86 * @returns {Record<string, number>}
87 */
88 export function mapLeaderFrame(positions, calibration, followerLimits) {
89 /** @type {Record<string, number>} */
90 const frame = {};
91 for (const [id, ticks] of positions) {
92 const cal = calibration.joints[String(id)];
93 const follower = followerLimits[String(id)];
94 if (!cal || !follower) continue;
95 frame[String(id)] = id === GRIPPER ? mapCalibrated(ticks, gripperCalibration(cal), follower, 0) : mapCalibrated(ticks, cal, follower);
96 }
97 return frame;
98 }
Software/so101/src/leader-map.test.ts added +94
@@ -0,0 +1,94 @@
1 import { describe, expect, test } from "bun:test";
2 import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { LeaderCalibrations } from "./leader-calibrations.ts";
6 import { mapCalibrated, mapLeaderFrame, parseCalibration, type LeaderCalibration } from "./leader-map.js";
7
8 const FOLLOWER = { "1": { min: 818, max: 3487 }, "2": { min: 813, max: 3202 }, "6": { min: 1995, max: 3525 } };
9 /** Joint 1 is mounted the usual way but 1000 ticks round the dial; joint 2 is mounted backwards and lopsided; the trigger closes upward. */
10 const CALIBRATION: LeaderCalibration = {
11 joints: {
12 "1": { low: 100, centre: 1100, high: 2100 },
13 "2": { low: 3000, centre: 2500, high: 1000 },
14 "6": { low: 3000, centre: 2900, high: 2000 },
15 },
16 };
17
18 describe("a calibrated leader → follower targets", () => {
19 test("an offset joint lands its centre on the follower's middle and scales each side onto the follower's", () => {
20 const j = CALIBRATION.joints["1"]!;
21 expect(mapCalibrated(1100, j, FOLLOWER["1"])).toBe(2153);
22 expect(mapCalibrated(1600, j, FOLLOWER["1"])).toBe(2820);
23 expect(mapCalibrated(600, j, FOLLOWER["1"])).toBe(1485);
24 });
25
26 test("an inverted joint turns back, and a short side still reaches the follower's end", () => {
27 const j = CALIBRATION.joints["2"]!;
28 expect(mapCalibrated(2500, j, FOLLOWER["2"])).toBe(2008);
29 expect(mapCalibrated(1750, j, FOLLOWER["2"])).toBe(2605); // halfway toward high, which is the lower number
30 expect(mapCalibrated(2750, j, FOLLOWER["2"])).toBe(1410); // halfway toward low, a side a third as long
31 });
32
33 test("past a captured end the target stays at the follower's limit minus the margin", () => {
34 const j = CALIBRATION.joints["2"]!;
35 expect(mapCalibrated(1000, j, FOLLOWER["2"])).toBe(3172);
36 expect(mapCalibrated(0, j, FOLLOWER["2"])).toBe(3172);
37 expect(mapCalibrated(3500, j, FOLLOWER["2"])).toBe(843);
38 });
39
40 test("a whole frame: the trigger maps closed to closed through the middle of its travel; uncalibrated joints stay out", () => {
41 const leader = new Map([[1, 1100], [2, 1750], [3, 2048], [6, 2750]]);
42 expect(mapLeaderFrame(leader, CALIBRATION, FOLLOWER)).toEqual({ "1": 2153, "2": 2605, "6": 2378 });
43 expect(mapLeaderFrame(new Map([[6, 3000]]), CALIBRATION, FOLLOWER)).toEqual({ "6": 1995 });
44 expect(mapLeaderFrame(new Map([[6, 2000]]), CALIBRATION, FOLLOWER)).toEqual({ "6": 3525 });
45 });
46 });
47
48 describe("a calibration from the browser", () => {
49 test("keeps what is valid and only that", () => {
50 expect(parseCalibration({ joints: { "1": { low: 100, centre: 1100, high: 2100, extra: 1 } }, admin: true })).toEqual({ joints: { "1": { low: 100, centre: 1100, high: 2100 } } });
51 });
52
53 test("refuses anything that is not three ticks per known servo with the centre between the ends", () => {
54 const bad: unknown[] = [
55 null,
56 [],
57 "x",
58 { joints: [] },
59 { joints: {} },
60 { joints: { "7": { low: 100, centre: 1100, high: 2100 } } },
61 { joints: { "01": { low: 100, centre: 1100, high: 2100 } } },
62 { joints: { __proto__: { low: 100, centre: 1100, high: 2100 } } },
63 { joints: { "1": { low: 100, centre: 1100 } } },
64 { joints: { "1": { low: 100.5, centre: 1100, high: 2100 } } },
65 { joints: { "1": { low: -1, centre: 1100, high: 2100 } } },
66 { joints: { "1": { low: 100, centre: 1100, high: 4096 } } },
67 { joints: { "1": { low: "100", centre: 1100, high: 2100 } } },
68 { joints: { "1": { low: 100, centre: 1100, high: 1150 } } },
69 { joints: { "1": { low: 100, centre: 1100, high: 600 } } },
70 { joints: { "1": null } },
71 ];
72 for (const body of bad) expect(() => parseCalibration(body)).toThrow();
73 });
74 });
75
76 describe("leader calibrations on disk", () => {
77 test("one per person, kept across restarts; an unreadable entry is dropped, not fatal", () => {
78 const file = join(mkdtempSync(join(tmpdir(), "so101-leaders-")), "leader-calibrations.json");
79 const now = () => new Date("2026-10-20T12:00:00Z");
80 const store = new LeaderCalibrations({ file, now });
81 expect(store.get("u-alice")).toBeNull();
82 expect(store.put("u-alice", CALIBRATION)).toEqual({ ...CALIBRATION, saved: "2026-10-20T12:00:00.000Z" });
83 expect(() => store.put("u-bob", { joints: { "1": { low: 1, centre: 2, high: 3 } } })).toThrow(/at least 100 ticks/);
84 expect(store.get("u-bob")).toBeNull();
85
86 const stored = JSON.parse(readFileSync(file, "utf8"));
87 writeFileSync(file, JSON.stringify({ ...stored, "u-mallory": { joints: { "1": { low: "x" } } } }));
88 const again = new LeaderCalibrations({ file });
89 expect(again.get("u-alice")).toEqual({ ...CALIBRATION, saved: "2026-10-20T12:00:00.000Z" });
90 expect(again.get("u-mallory")).toBeNull();
91 expect(again.delete("u-alice")).toBe(true);
92 expect(new LeaderCalibrations({ file }).get("u-alice")).toBeNull();
93 });
94 });
Software/so101/src/lobby.test.ts +27
@@ -181,6 +181,33 @@ describe("lobby", () => {
181181 await alice.next(drivingIs(null));
182182 });
183183
184 test("leader calibration: each signed-in person keeps their own, any time, turn or no turn", async () => {
185 const port = await start();
186 const url = `http://127.0.0.1:${port}/leader/calibration`;
187 const put = (headers: Record<string, string>, body: unknown) => fetch(url, { method: "PUT", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body) });
188 const get = async (headers: Record<string, string>) => (await fetch(url, { headers })).json();
189 const mine = { joints: { "2": { low: 3000, centre: 2500, high: 1000 } } };
190
191 expect((await fetch(url)).status).toBe(401);
192 expect((await put({}, mine)).status).toBe(401);
193 const stored = await put(ALICE, mine); // nobody drives: calibrating is not driving
194 expect(stored.status).toBe(200);
195 expect(await stored.json()).toMatchObject(mine);
196 expect(await get(ALICE)).toMatchObject(mine);
197 expect(await get(BOB)).toBeNull();
198
199 const bad = await put(BOB, { joints: { "2": { low: 2400, centre: 2500, high: 1000 } } });
200 expect(bad.status).toBe(400);
201 expect(((await bad.json()) as { error: string }).error).toContain("joint 2");
202 expect((await fetch(url, { method: "PUT", headers: BOB, body: "{" })).status).toBe(400);
203 expect((await put({ ...BOB, origin: "https://evil.example" }, mine)).status).toBe(403);
204 expect((await fetch(url, { method: "POST", headers: BOB })).status).toBe(405);
205
206 expect(await (await fetch(url, { method: "DELETE", headers: ALICE })).json()).toEqual({ deleted: true });
207 expect(await get(ALICE)).toBeNull();
208 expect((await fetch(`http://127.0.0.1:${port}/leader-map.js`)).headers.get("content-type")).toBe("text/javascript");
209 });
210
184211 test("chat: everyone reads, signed-in people post once per 2 s, the owner deletes and mutes", async () => {
185212 const port = await start();
186213 const anon = await join(port);
Software/so101/src/relay.ts +39 −1
@@ -13,6 +13,8 @@
1313 * WS /live the lobby: the turn, the queue, the chat
1414 * GET /link {"mode": "live"|"simulated", "host": "<host:port>"|null, "problem": "…"|null}
1515 * GET /camera/<1|2>/<stream|state|snapshot> the arm machine's camera (µStreamer on :8080 and :8081 by default)
16 * GET|PUT|DELETE /leader/calibration the signed-in person's own leader calibration (src/leader-map.js), any time,
17 * turn or no turn: GET answers it or null, PUT {"joints": {...}} stores it
1618 */
1719
1820 import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
@@ -20,6 +22,9 @@ import type { Duplex } from "node:stream";
2022 import { Readable } from "node:stream";
2123 import { pipeline } from "node:stream/promises";
2224 import WebSocket, { WebSocketServer } from "ws";
25 import { LOCAL as LOCAL_PERSON } from "./identity.ts";
26 import { LeaderCalibrations } from "./leader-calibrations.ts";
27 import { CalibrationError } from "./leader-map.js";
2328 import type { Lobby } from "./lobby.ts";
2429
2530 export interface Remote {
@@ -57,6 +62,8 @@ export interface RelayOptions {
5762 readTimeoutMs?: number;
5863 /** Who may command the arm; without one, anyone who reaches the relay may (a run on one's own machine). */
5964 lobby?: Lobby | null;
65 /** Every driver's leader calibration; without one they are kept in memory. */
66 leaders?: LeaderCalibrations;
6067 }
6168
6269 export interface RunningRelay {
@@ -68,7 +75,8 @@ export interface RunningRelay {
6875 const SCHEMES: Record<string, "http:" | "https:"> = { "http:": "http:", "https:": "https:", "ws:": "http:", "wss:": "https:" };
6976 const MAX_BODY = 1_000_000;
7077 /** Served from this process whichever arm is live: they describe the app, not the arm. */
71 const LOCAL = /^\/(?:index\.html)?$|^\/(?:model|vendor|printables)(?:\/|$)/;
78 const LOCAL = /^\/(?:index\.html|leader-map\.js)?$|^\/(?:model|vendor|printables)(?:\/|$)/;
79 const LEADER = "/leader/calibration";
7280 const CAMERA = /^\/camera\/([12])\/(stream|state|snapshot)$/;
7381 const FLOOR = {
7482 "x-content-type-options": "nosniff",
@@ -129,6 +137,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
129137 const probeEveryMs = options.probeEveryMs ?? 5000;
130138 const readTimeoutMs = options.readTimeoutMs ?? 2500;
131139 const lobby = options.lobby ?? null;
140 const leaders = options.leaders ?? new LeaderCalibrations();
132141
133142 // ------------------------------------------------------------------ the link
134143 let live = false;
@@ -218,6 +227,34 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
218227 }
219228 };
220229
230 /** A person's own calibration: signed in is enough, it never touches the arm. */
231 const leaderCalibration = async (req: IncomingMessage, res: ServerResponse) => {
232 const who = lobby ? lobby.who(req) : LOCAL_PERSON;
233 if (!who) return json(res, 401, { error: "sign in to keep a leader calibration" });
234 switch (req.method) {
235 case "GET":

Nit: PUT rewrites the whole file for every signed-in user with no limit. A per-identity limit (lobby.who id, never a header) would keep one noisy account from hammering the disk.

236 return json(res, 200, leaders.get(who.id));
237 case "PUT": {
238 let body: unknown;
239 try {
240 body = JSON.parse((await readBody(req)).toString("utf8"));
241 } catch {
242 return json(res, 400, { error: "a calibration is a JSON object" });
243 }
244 try {
245 return json(res, 200, leaders.put(who.id, body));
246 } catch (err) {
247 if (err instanceof CalibrationError) return json(res, 400, { error: err.message });
248 throw err;
249 }
250 }
251 case "DELETE":
252 return json(res, 200, { deleted: leaders.delete(who.id) });
253 }
254 res.setHeader("allow", "GET, PUT, DELETE");
255 return json(res, 405, { error: "GET, PUT or DELETE" });
256 };
257
221258 const http = createServer(async (req, res) => {
222259 for (const [name, value] of Object.entries(FLOOR)) res.setHeader(name, value);
223260 try {
@@ -225,6 +262,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
225262 const path = url.pathname + url.search;
226263 const reading = req.method === "GET" || req.method === "HEAD";
227264 if (!reading && !sameOrigin(req)) return json(res, 403, { error: "only this page may change the arm" });
265 if (url.pathname === LEADER) return await leaderCalibration(req, res);
228266 if (!reading && lobby) {
229267 const who = lobby.who(req);
230268 // Stop is the owner's at any time; everything else is the driver's alone.
Software/so101/src/server.ts +3
@@ -24,6 +24,7 @@
2424 * PUT /settings change any of those
2525 * GET /metrics jams, blocks, stalls, peak load and temperature per joint, recent events
2626 * GET /model.json the arm model: joints, the table plane, where the URDF is served
27 * GET /leader-map.js the leader calibration mapping, for the browser (src/leader-map.js)
2728 * GET /model/<file> the URDF and its meshes; GET /vendor/<pkg>/<file> three.js and the URDF loader
2829 * GET /printables the sheets to print for the vision quest (board, cube markers, gripper marker); GET /printables/<file>
2930 * WS /follow client sends {"1": ticks, "2": ticks, ...} frames; the server drives the arm
@@ -490,6 +491,8 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
490491 case "GET /index.html":
491492 res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
492493 return res.end(readFileSync(viewerPath)); // read per request: a viewer change deploys with rsync alone
494 case "GET /leader-map.js":
495 return file(res, join(here, "leader-map.js"), "no-cache");
493496 case "GET /status":
494497 return json(res, 200, await status());
495498 case "GET /limits":
Software/so101/src/viewer.html +144 −6
@@ -101,6 +101,13 @@
101101 #say { display: flex; gap: 6px; padding: 8px 12px calc(8px + env(safe-area-inset-bottom)); border-top: 1px solid var(--line); }
102102 #say input { flex: 1; min-width: 0; font: inherit; padding: 6px 10px; border-radius: 6px; border: 1px solid var(--line); background: var(--bg); color: var(--fg); }
103103 #sayNote { color: var(--dim); font-size: 12px; padding: 0 12px 8px; } #sayNote:empty { display: none; }
104 /* the leader calibration: a card over the stage, so the 3D model can show the pose to copy */
105 #leaderDlg { position: absolute; left: 12px; top: 12px; margin: 0; z-index: 8; width: min(400px, calc(100% - 24px)); max-height: calc(100% - 24px); overflow: auto; }
106 #lcRead { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px 10px; margin: 10px 0; font-size: 12px; color: var(--dim); font-variant-numeric: tabular-nums; }
107 #lcRead span.on { color: var(--fg); font-weight: 600; }
108 #lcFlips { display: grid; grid-template-columns: 1fr auto auto; gap: 4px 10px; align-items: center; font-size: 13px; margin: 8px 0; }
109 #lcErr { color: var(--bad); } #lcErr:empty { display: none; }
110 #lcFlips button { min-height: 28px; padding: 0 10px; } #lcFlips small { color: var(--dim); font-variant-numeric: tabular-nums; }
104111 @media (prefers-reduced-motion: reduce) { * { transition: none !important; scroll-behavior: auto !important; } }
105112 </style>
106113 </head>
@@ -131,6 +138,7 @@
131138 <button id="play">▶ Play…</button>
132139 <button id="liveBtn" class="go" hidden title="read the leader arm through this computer's USB port and stream it (Chrome)">Live from leader</button>
133140 </span>
141 <button id="leaderCal" hidden title="teach this page your own leader arm: once, kept with your sign-in">Calibrate leader</button>
134142 <button id="metricsBtn">Metrics</button>
135143 <button id="settingsBtn">Settings</button>
136144 <button id="calib">3D calibration</button>
@@ -216,6 +224,14 @@
216224 <div class="actions"><button value="cancel">Cancel</button><button value="start" class="rec">Start</button></div>
217225 </form>
218226 </dialog>
227 <dialog id="leaderDlg" aria-labelledby="lcTitle">
228 <h3 id="lcTitle">Calibrate your leader arm</h3>
229 <p id="lcStep"></p>
230 <div id="lcRead" aria-live="off"></div>
231 <div id="lcFlips" hidden></div>
232 <p id="lcErr" class="bad" role="alert"></p>

The card opens with non-modal show() and focus stays on the Calibrate leader button, so a keyboard user has to tab through the stage to reach Capture. Focus the primary button on open and restore it on close. Give #lcStep role="status" (or aria-live="polite") so each step change is announced.

233 <div class="actions"><button id="lcCancel">Cancel</button><button id="lcBack" hidden>Back</button><button id="lcNext" class="go">Connect</button></div>
234 </dialog>
219235 <dialog id="playDlg">
220236 <h3>Play a recording</h3>
221237 <p>The arm first moves slowly to the recording's first pose. Keep the workspace clear.</p>
@@ -240,6 +256,7 @@
240256 import * as THREE from "three";
241257 import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";
242258 import URDFManipulator from "urdf-loader/manipulator";
259 import { mapLeaderFrame, parseCalibration } from "/leader-map.js";
243260 customElements.define("urdf-viewer", URDFManipulator);
244261
245262 const $ = (id) => document.getElementById(id);
@@ -519,7 +536,7 @@
519536 }
520537 }
521538 }
522 let live = null;
539 let live = null, calib = null;
523540 const midOf = (r) => (r.min + r.max) / 2;
524541 const clampTo = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
525542 const mapLeader = (positions, leaderLimits) => {
@@ -532,14 +549,18 @@
532549 return frame;
533550 };
534551 async function startLive() {
552 if (calib) return msg("finish or cancel the leader calibration first", true);
535553 const port = await navigator.serial.requestPort({ filters: [{ usbVendorId: 0x1a86 }] }).catch(() => null);
536554 if (!port) return;
537555 const bus = new SerialBus(port);
538556 try {
539557 await bus.open();
540558 const ids = [1, 2, 3, 4, 5, 6];
559 // The driver's own calibration when they have one; otherwise the leader servos' stored limits, LeRobot's way.
560 const mine = await api("/leader/calibration").catch(() => null);
561 const calibration = mine?.ok && mine.joints ? mine : null;
541562 const leaderLimits = {};
542 for (const id of ids) leaderLimits[id] = { min: await bus.read(id, REG.Min_Position_Limit), max: await bus.read(id, REG.Max_Position_Limit) };
563 if (!calibration) for (const id of ids) leaderLimits[id] = { min: await bus.read(id, REG.Min_Position_Limit), max: await bus.read(id, REG.Max_Position_Limit) };
543564 await bus.syncWrite(REG.Torque_Enable, ids.map((id) => [id, 0])); // the leader is moved by hand
544565 const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/follow`);
545566 await new Promise((resolve, reject) => { ws.onopen = resolve; ws.onerror = () => reject(new Error("no stream socket")); });
@@ -550,13 +571,13 @@
550571 live.busy = true;
551572 try {
552573 const positions = await bus.syncRead(ids, REG.Present_Position);
553 const frame = mapLeader(positions, leaderLimits);
574 const frame = calibration ? mapLeaderFrame(positions, calibration, limits) : mapLeader(positions, leaderLimits);
554575 if (ws.readyState === 1 && Object.keys(frame).length) { ws.send(JSON.stringify(frame)); live.frames++; }
555576 } catch { /* a missed read; the next tick tries again */ }
556577 live.busy = false;
557578 }, 16);
558579 $("liveBtn").textContent = "■ Stop live";
559 msg("live: the follower follows the leader. CAUTION: it first eases over to the leader's pose.");
580 msg(`live${calibration ? ", with your calibration" : "; Calibrate leader for a clean mapping"}: the follower follows the leader. CAUTION: it first eases over to the leader's pose.`);
560581 } catch (err) {
561582 await bus.close();
562583 msg(`live mode: ${err.message}`, true);
@@ -571,10 +592,127 @@
571592 $("liveBtn").textContent = "Live from leader";
572593 msg(`live mode ended${reason ? `: ${reason}` : ""}; the follower holds (${l.frames} frames)`);
573594 }
595 // ---------------------------------------------------------------- leader calibration (src/leader-map.js)
596 // Once per driver: the leader in the follower's middle pose, then each joint at each end the model shows. The ends
597 // carry the direction (a joint whose low end reads higher is mounted backwards) and each side's length; the centre
598 // carries the offset. Kept on the server under the driver's sign-in; Live from leader applies it before sending.
599 const LABELS = { 1: "Base rotation", 2: "Shoulder", 3: "Elbow", 4: "Wrist bend", 5: "Wrist roll", 6: "Gripper trigger" };
600 const LEADER_IDS = [1, 2, 3, 4, 5, 6];
601 const STEPS = ["connect", "centre", ...LEADER_IDS.flatMap((id) => [{ id, end: "low" }, { id, end: "high" }]), "check"];
602 /** Follower ticks the model shows for a step: every joint in the middle, the one being taught at its end. */
603 const previewOf = (step) => Object.fromEntries(Object.keys(limits).map((k) => {
604 const id = Number(k);
605 if (typeof step !== "object" || step.id !== id) return [id, id === 6 ? limits[id].min + (limits[id].max - limits[id].min) / 2 : mid(id)];
606 return [id, step.end === "low" ? limits[id].min + (id === 6 ? 0 : 30) : limits[id].max - (id === 6 ? 0 : 30)];
607 }));
608 const showOnModel = (ticks) => { if (viewer.robot) for (const [id, t] of Object.entries(ticks)) if (NAMES[id] && limits[id]) viewer.setJointValue(NAMES[id], toRad(Number(id), t)); };
609 const draft = () => ({ joints: Object.fromEntries(LEADER_IDS.filter((id) => calib.joints[id]?.high !== undefined).map((id) => {
610 const j = calib.joints[id];
611 return [id, id === 6 ? { low: j.low, high: j.high, centre: Math.round((j.low + j.high) / 2) } : { low: j.low, centre: j.centre, high: j.high }];
612 })) });
613 function renderCalib() {
614 const step = STEPS[calib.step];
615 const t = typeof step === "object" ? step : null;
616 $("lcErr").textContent = calib.error ?? "";
617 $("lcBack").hidden = calib.step < 2;
618 $("lcFlips").hidden = step !== "check";
619 $("lcRead").hidden = step === "connect";
620 $("lcNext").textContent = step === "connect" ? "Connect" : step === "check" ? "Save" : "Capture";
621 $("lcStep").textContent =
622 step === "connect" ? "Plug your leader arm into this computer and power its board, then press Connect and pick its port. Its motors go limp so you can move it by hand. Nothing moves the real arm while you calibrate."
623 : step === "centre" ? "Hold the leader in the pose the 3D model shows: every joint in the middle of its travel, the gripper half open. Then press Capture."
624 : step === "check" ? "Move the leader: the model follows through your calibration. If a joint turns the wrong way, flip it. Save keeps it with your sign-in, for every computer you drive from."
625 : `${LABELS[t.id]} (${calib.step - 1} of 12): move it to the ${t.id === 6 ? (t.end === "low" ? "closed" : "open") : "end"} the model shows, as far as it goes, and press Capture.`;
626 $("lcRead").replaceChildren(...LEADER_IDS.map((id) => el("span", { className: t?.id === id ? "on" : "", textContent: `${LABELS[id].split(" ")[0]} ${calib.reading.get(id) ?? "–"}` })));
627 if (step === "check") {
628 $("lcFlips").replaceChildren(...LEADER_IDS.flatMap((id) => {
629 const j = calib.joints[id];
630 return [el("span", { textContent: LABELS[id] }), el("small", { textContent: `${j.low} · ${id === 6 ? "–" : j.centre} · ${j.high}${j.low > j.high ? " (reversed)" : ""}` }),
631 el("button", { textContent: "Flip", title: "swap this joint's ends", onclick: () => { [j.low, j.high] = [j.high, j.low]; renderCalib(); } })];
632 }));
633 }
634 if (step !== "check") showOnModel(previewOf(step));
635 }
636 async function openCalib() {
637 if (!Object.keys(limits).length) return msg("the arm's limits have not loaded yet", true);
638 const mine = await api("/leader/calibration").catch(() => null);
639 if (mine?.status === 401) return msg("sign in to calibrate your leader: the calibration is kept with your account", true);
640 if (live) await stopLive("calibrating the leader");
641 calib = { step: 0, joints: {}, reading: new Map(), bus: null, timer: null, busy: false, error: null, had: Boolean(mine?.joints) };
642 $("leaderDlg").show();
643 renderCalib();
644 }
645 async function closeCalib(note) {
646 const c = calib; if (!c) return;
647 calib = null;
648 clearInterval(c.timer);
649 await c.bus?.close();
650 $("leaderDlg").close();
651 if (status) applyModel(status);
652 if (note) msg(note);
653 }
654 async function connectCalib() {
655 const port = await navigator.serial.requestPort({ filters: [{ usbVendorId: 0x1a86 }] }).catch(() => null);
656 if (!port || !calib) return;
657 const bus = new SerialBus(port);
658 try {
659 await bus.open();
660 await bus.syncWrite(REG.Torque_Enable, LEADER_IDS.map((id) => [id, 0]));
661 } catch (err) {
662 await bus.close();
663 calib.error = `could not open the leader: ${err.message}`;
664 return renderCalib();
665 }
666 calib.bus = bus;
667 calib.timer = setInterval(async () => {
668 const c = calib; if (!c || c.busy) return;
669 c.busy = true;
670 try {
671 const got = await bus.syncRead(LEADER_IDS, REG.Present_Position);
672 for (const [id, t] of got) c.reading.set(id, t);
673 if (calib !== c) return;
674 if (STEPS[c.step] === "check") showOnModel(mapLeaderFrame(c.reading, draft(), limits));
675 for (const [i, span] of [...$("lcRead").children].entries()) span.textContent = `${LABELS[LEADER_IDS[i]].split(" ")[0]} ${c.reading.get(LEADER_IDS[i]) ?? "–"}`;
676 } catch { /* a missed read; the next tick tries again */ } finally { c.busy = false; }
677 }, 33);
678 calib.step = 1;
679 renderCalib();
680 }
681 async function nextCalib() {
682 const c = calib; if (!c) return;
683 const step = STEPS[c.step];
684 c.error = null;
685 if (step === "connect") return connectCalib();
686 if (step === "check") {
687 const r = await api("/leader/calibration", draft(), "PUT");
688 if (!r.ok) { c.error = r.error ?? "the calibration was not saved"; return renderCalib(); }
689 return closeCalib("leader calibrated and saved; Live from leader now uses it");
690 }
691 const missing = LEADER_IDS.filter((id) => !c.reading.has(id));
692 if (missing.length) { c.error = `no reading from leader servo ${missing.join(", ")}: is every joint plugged in?`; return renderCalib(); }
693 if (step === "centre") for (const id of LEADER_IDS) c.joints[id] = { centre: c.reading.get(id) };
694 else {
695 const j = c.joints[step.id];
696 j[step.end] = c.reading.get(step.id);
697 if (step.end === "high") {
698 try { parseCalibration({ joints: { [step.id]: step.id === 6 ? { low: j.low, high: j.high, centre: Math.round((j.low + j.high) / 2) } : j } }); }
699 catch (err) { delete j.low; delete j.high; c.step--; c.error = `${err.message.replace(/^joint \d+: /, "")}. Try ${LABELS[step.id].toLowerCase()} again.`; return renderCalib(); }
700 }
701 }
702 c.step++;
703 renderCalib();
704 }
705 $("lcNext").onclick = () => void nextCalib();
706 $("lcBack").onclick = () => { if (calib && calib.step > 1) { calib.step--; calib.error = null; renderCalib(); } };
707 $("lcCancel").onclick = () => void closeCalib(calib?.had ? "calibration cancelled; your saved one still applies" : "calibration cancelled");
708 $("leaderDlg").addEventListener("cancel", (e) => { e.preventDefault(); void closeCalib("calibration cancelled"); });
709
574710 if (navigator.serial) {
711 $("leaderCal").hidden = false;
712 $("leaderCal").onclick = () => (calib ? undefined : void openCalib());
575713 $("liveBtn").hidden = false;
576714 $("liveBtn").onclick = () => (live ? stopLive() : startLive());
577 navigator.serial.addEventListener("disconnect", () => { if (live) stopLive("the leader was unplugged"); });
715 navigator.serial.addEventListener("disconnect", () => { if (live) stopLive("the leader was unplugged"); if (calib?.bus) closeCalib("calibration stopped: the leader was unplugged"); });
578716 }
579717
580718 // ---------------------------------------------------------------- the 3D model
@@ -619,7 +757,7 @@
619757 stream.send({ [id]: clampTicks(id, toTicks(id, viewer.robot.joints[e.detail].angle)) });
620758 });
621759 function applyModel(d) {
622 if (!viewer.robot) return;
760 if (!viewer.robot || calib) return; // while calibrating, the model shows the pose to copy
623761 for (const j of d.joints) {
624762 const name = NAMES[j.id];
625763 if (!name || j.position == null || name === dragging || !limits[j.id]) continue;
Software/so101/tsconfig.json +2
@@ -7,6 +7,8 @@
77 "allowImportingTsExtensions": true,
88 "verbatimModuleSyntax": true,
99 "noEmit": true,
10 "allowJs": true,
11 "checkJs": true,
1012 "strict": true,
1113 "skipLibCheck": true,
1214 "noUncheckedIndexedAccess": true,

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs