Files
led-controller/led-simulator/web/app.js
T
jimmyandClaude Opus 5.5 698c1463c0 chore: move led-simulator in from its submodule
Merges led-simulator (sim-bridge, 4d8aeb5) under led-simulator/ with its history,
in place of the submodule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:08:49 +13:00

817 lines
23 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* led-simulator page: the rig of simulated led-drivers behind the bridge.
*
* Each strip is a web worker running led-driver/src/main.py in Pyodide
* (driver-worker.js). The page is the radio between them and the bridge
* (server.py, WebSocket /sim):
* server -> page binary dest_mac(6) + ESP-NOW packet (bridge transmit)
* page -> server binary src_mac(6) + ESP-NOW packet (driver transmit)
* server -> page text {"t":"status","controllers":n} | {"t":"takeover"}
* page -> server text {"t":"flash","n":i,"path":..,"data":..}
* Received packets reach a driver through its SharedArrayBuffer ring.
*/
/* global SimRing, RigLayout */
(function () {
'use strict';
const OFF_COLOUR = '#1d1f24';
const LABEL = '#8a909c';
const LABEL_LIT = '#d6dae2';
const CENTRE = '#2c3038';
const SELECT = '#5aa9ff';
const STATE_COLOUR = {
off: '#4b505b',
queued: '#f2b84b',
loading: '#f2b84b',
running: '#3ecf8e',
crashed: '#ff6b6b',
};
const LOG_LINES = 600;
const BROADCAST = 'ff:ff:ff:ff:ff:ff';
const AUTO_KEY = 'ledsim.autoPower';
const $ = (id) => document.getElementById(id);
const params = new URLSearchParams(location.search);
// Test hook: a stand-in worker script under /web/.
const workerUrl = /^\/web\/[\w.-]+\.js$/.test(params.get('worker') || '')
? params.get('worker')
: '/web/driver-worker.js';
const app = {
cfg: null,
bundle: null,
bundleAt: 0,
bootPy: '',
bridgeMac: null,
strips: [],
byMac: new Map(),
ws: null,
wsOpen: false,
takenOver: false,
controllers: 0,
queue: [],
booting: 0,
geo: null,
fullRedraw: true,
selected: null,
canvas: null,
ctx: null,
dpr: 1,
};
// ----- helpers -----------------------------------------------------------
function macBytes(s) {
return new Uint8Array(s.split(':').map((h) => parseInt(h, 16)));
}
function macOf(u8, off = 0) {
const parts = [];
for (let i = off; i < off + 6; i += 1) {
parts.push(u8[i].toString(16).padStart(2, '0'));
}
return parts.join(':');
}
function banner(text, kind) {
const el = $('banner');
if (!text) {
el.hidden = true;
return;
}
el.textContent = text;
el.className = `banner${kind ? ` ${kind}` : ''}`;
el.hidden = false;
}
function readAuto() {
try {
const v = localStorage.getItem(AUTO_KEY);
return v === null ? true : v === '1';
} catch (_e) {
return true;
}
}
function writeAuto(on) {
try {
localStorage.setItem(AUTO_KEY, on ? '1' : '0');
} catch (_e) {
// storage unavailable: setting lasts for this page only
}
}
// ----- strips: power and workers ------------------------------------------
function validPlace(p) {
return Array.isArray(p) && p.length === 4 && p.every((v) => typeof v === 'number') ? p : null;
}
/** A driver's settings.json changed (or was read): pick up its place in the rig. */
function notePlace(s, settingsText) {
let place = null;
try {
place = validPlace(JSON.parse(settingsText).place);
} catch (_e) {
return;
}
if (JSON.stringify(place) !== JSON.stringify(s.place)) {
s.place = place;
resize();
}
}
function makeStrip(info) {
return {
info,
index: info.index,
mac: info.mac,
macBytes: macBytes(info.mac),
name: info.default_name,
state: 'off',
worker: null,
ring: null,
frame: new Uint8Array(info.leds * 3),
place: validPlace(info.place),
lit: false,
dirty: true,
logs: [],
rx: 0,
tx: 0,
error: '',
};
}
function setState(s, state, error = '') {
s.state = state;
s.error = error;
s.dirty = true;
updateChips();
if (app.selected === s) {
renderDrawer();
}
}
function addLog(s, text) {
const lines = String(text).split('\n');
for (const line of lines) {
s.logs.push(line);
}
if (s.logs.length > LOG_LINES) {
s.logs.splice(0, s.logs.length - LOG_LINES);
}
if (app.selected === s) {
const el = $('d-log');
const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 8;
el.textContent = s.logs.join('\n');
if (atBottom) {
el.scrollTop = el.scrollHeight;
}
}
}
function powerOn(s) {
if (!self.crossOriginIsolated || app.takenOver) {
return;
}
if (s.state !== 'off' && s.state !== 'crashed') {
return;
}
setState(s, 'queued');
app.queue.push(s);
pumpQueue();
}
function powerOff(s) {
const i = app.queue.indexOf(s);
if (i >= 0) {
app.queue.splice(i, 1);
}
if (s.worker) {
s.worker.terminate();
s.worker = null;
if (s.state === 'loading') {
app.booting = Math.max(0, app.booting - 1);
}
}
s.ring = null;
s.frame = new Uint8Array(s.info.leds * 3);
setState(s, 'off');
pumpQueue();
}
function reset(s) {
powerOff(s);
addLog(s, '--- reset ---');
powerOn(s);
}
async function ensureBundle() {
// Re-read led-driver/src (main.py, patterns/) for each batch of boots.
if (app.bundle && Date.now() - app.bundleAt < 3000) {
return;
}
const [bundle, bootPy] = await Promise.all([
fetch('/api/bundle').then((r) => r.json()),
fetch('/web/driver_boot.py').then((r) => r.text()),
]);
app.bundle = bundle;
app.bootPy = bootPy;
app.bundleAt = Date.now();
}
async function pumpQueue() {
const limit = Math.max(1, Number(app.cfg.drivers.boot_concurrency) || 4);
while (app.queue.length && app.booting < limit) {
const s = app.queue.shift();
app.booting += 1;
try {
await ensureBundle();
if (s.state !== 'queued') {
app.booting -= 1;
continue;
}
await startWorker(s);
} catch (err) {
app.booting = Math.max(0, app.booting - 1);
addLog(s, `boot failed: ${err}`);
setState(s, 'crashed', String(err));
}
}
}
async function startWorker(s) {
const flash = await fetch(`/api/flash/${s.index}`).then((r) => r.json());
notePlace(s, flash['settings.json']);
try {
s.name = JSON.parse(flash['settings.json']).name || s.name;
} catch (_e) {
// keep the default name
}
if (s.state !== 'queued') {
app.booting -= 1;
return;
}
s.ring = SimRing.create(64 * 1024);
const worker = new Worker(workerUrl);
s.worker = worker;
setState(s, 'loading');
worker.onmessage = (ev) => onWorkerMessage(s, worker, ev.data || {});
worker.onerror = (ev) => {
if (s.worker !== worker) {
return;
}
ev.preventDefault();
addLog(s, `worker error: ${ev.message || ev}`);
driverStopped(s, worker, String(ev.message || 'worker error'), false);
};
worker.postMessage({
t: 'boot',
index: s.index,
ringSab: s.ring.sab,
sleepSab: new SharedArrayBuffer(4),
pyodideUrl: app.cfg.pyodide_url,
files: app.bundle,
flash: { 'settings.json': flash['settings.json'], 'presets.json': flash['presets.json'] },
bootPy: app.bootPy,
env: {
LED_SIM_MAC: s.mac.replace(/:/g, ''),
LED_SIM_FPS: String(app.cfg.drivers.fps ?? 30),
LED_SIM_LOOP_SLEEP_MS: String(app.cfg.drivers.loop_sleep_ms ?? 2),
LED_SIM_FLASH: '/flash',
LED_SIM_STUBS: '/stubs',
},
});
}
function driverStopped(s, worker, error, isReset) {
if (s.worker !== worker) {
return;
}
if (s.state === 'loading') {
app.booting = Math.max(0, app.booting - 1);
}
worker.terminate();
s.worker = null;
s.ring = null;
if (isReset) {
s.frame = new Uint8Array(s.info.leds * 3);
setState(s, 'off');
addLog(s, '--- machine.reset() ---');
powerOn(s);
return;
}
setState(s, 'crashed', error);
pumpQueue();
}
function onWorkerMessage(s, worker, m) {
if (s.worker !== worker) {
return;
}
switch (m.t) {
case 'state':
if (m.state === 'running' && s.state === 'loading') {
app.booting = Math.max(0, app.booting - 1);
setState(s, 'running');
pumpQueue();
}
break;
case 'log':
addLog(s, m.text);
break;
case 'tx': {
// dest(6) + packet. The bridge forwards everything it hears upstream.
const data = m.data;
if (data.length <= 6) {
break;
}
s.tx += 1;
const up = new Uint8Array(data.length);
up.set(s.macBytes, 0);
up.set(data.subarray(6), 6);
if (app.wsOpen) {
app.ws.send(up);
}
if (app.selected === s) {
renderFacts();
}
break;
}
case 'px':
s.frame = m.data;
s.dirty = true;
break;
case 'flash':
if (app.wsOpen) {
app.ws.send(JSON.stringify({ t: 'flash', n: s.index, path: m.path, data: m.data }));
}
if (m.path === 'settings.json') {
notePlace(s, m.data);
try {
const name = JSON.parse(m.data).name;
if (name && name !== s.name) {
s.name = name;
s.dirty = true;
app.fullRedraw = true;
}
} catch (_e) {
// ignore
}
}
break;
case 'exit':
driverStopped(s, worker, m.error || 'stopped', Boolean(m.reset));
break;
default:
break;
}
}
// ----- bridge link ---------------------------------------------------------
function deliver(s, payload) {
if (s.state !== 'running' || !s.ring) {
return; // powered off or still booting: the packet is lost, as on air
}
if (s.ring.push(payload)) {
s.rx += 1;
if (app.selected === s) {
renderFacts();
}
}
}
function onDownlink(u8) {
if (u8.length < 7) {
return;
}
const dest = macOf(u8, 0);
// The driver sees the bridge as the sender.
const payload = new Uint8Array(u8.length);
payload.set(app.bridgeMac, 0);
payload.set(u8.subarray(6), 6);
if (dest === BROADCAST) {
for (const s of app.strips) {
deliver(s, payload);
}
return;
}
const s = app.byMac.get(dest);
if (s) {
deliver(s, payload);
}
}
function connectBridge() {
if (app.takenOver) {
return;
}
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
const ws = new WebSocket(`${proto}://${location.host}/sim`);
ws.binaryType = 'arraybuffer';
app.ws = ws;
ws.onopen = () => {
app.wsOpen = true;
if (!app.takenOver && self.crossOriginIsolated) {
banner('');
}
updateChips();
};
ws.onmessage = (ev) => {
if (typeof ev.data === 'string') {
let m = null;
try {
m = JSON.parse(ev.data);
} catch (_e) {
return;
}
if (m.t === 'status') {
app.controllers = Number(m.controllers) || 0;
updateChips();
} else if (m.t === 'takeover') {
app.takenOver = true;
for (const s of app.strips) {
powerOff(s);
}
banner('The rig is running in another tab. This page has powered its strips off; reload to take it back.', 'info');
setButtons();
}
return;
}
onDownlink(new Uint8Array(ev.data));
};
ws.onclose = () => {
app.wsOpen = false;
updateChips();
if (app.takenOver) {
return;
}
banner('Lost the simulator server. Reconnecting…');
setTimeout(connectBridge, 2000);
};
}
// ----- UI: chips, drawer ---------------------------------------------------
function updateChips() {
if (!app.cfg) {
return;
}
const b = app.cfg.bridge;
$('bridge-chip').textContent = `${b.name} · ${b.mac}`;
const cc = $('controller-chip');
cc.textContent = app.wsOpen
? `controller: ${app.controllers ? `${app.controllers} connected` : 'not connected'}`
: 'controller: –';
cc.className = `chip ${app.controllers ? 'ok' : 'warn'}`;
const running = app.strips.filter((s) => s.state === 'running').length;
const booting = app.strips.filter((s) => s.state === 'queued' || s.state === 'loading').length;
const crashed = app.strips.filter((s) => s.state === 'crashed').length;
let text = `strips: ${running}/${app.strips.length} running`;
if (booting) {
text += ` · ${booting} booting`;
}
if (crashed) {
text += ` · ${crashed} stopped`;
}
const sc = $('strips-chip');
sc.textContent = text;
sc.className = `chip ${crashed ? 'warn' : running ? 'ok' : ''}`;
}
function renderFacts() {
const s = app.selected;
if (!s) {
return;
}
const st = $('d-state');
st.textContent = s.state + (s.error && s.state === 'crashed' ? ` – ${s.error.split('\n').slice(-2).join(' ')}` : '');
st.className = `state-${s.state}`;
const lay = app.cfg.layout;
const side = lay.columns === 2 ? (s.info.col === 0 ? 'left' : 'right') : `column ${s.info.col + 1}`;
$('d-pos').textContent = `row ${s.info.row + 1}, ${side} · ${s.info.leds} LEDs · pixel 0 ${s.info.reversed ? 'at right end' : 'at left end'}`;
$('d-packets').textContent = `${s.rx} received · ${s.tx} sent`;
}
function renderDrawer() {
const s = app.selected;
$('drawer').hidden = !s;
if (!s) {
return;
}
$('d-name').textContent = s.name;
$('d-meta').textContent = `strip ${s.info.n} · ${s.mac}`;
renderFacts();
const off = s.state === 'off' || s.state === 'crashed';
$('d-on').disabled = !off || !self.crossOriginIsolated || app.takenOver;
$('d-off').disabled = off;
$('d-reset').disabled = !self.crossOriginIsolated || app.takenOver;
const el = $('d-log');
el.textContent = s.logs.join('\n');
el.scrollTop = el.scrollHeight;
}
function select(s) {
app.selected = app.selected === s ? null : s;
app.fullRedraw = true;
renderDrawer();
requestAnimationFrame(resize);
}
function setButtons() {
const ok = self.crossOriginIsolated && !app.takenOver;
for (const id of ['power-on-all', 'power-cycle-all', 'power-off-all']) {
$(id).disabled = !ok;
}
renderDrawer();
}
// ----- canvas ----------------------------------------------------------------
function resize() {
const c = app.canvas;
const rect = c.getBoundingClientRect();
app.dpr = window.devicePixelRatio || 1;
c.width = Math.max(1, Math.round(rect.width * app.dpr));
c.height = Math.max(1, Math.round(rect.height * app.dpr));
// Drawn where the controller placed each bar once every bar has a place, else as the layout grid
app.geo = app.strips.length && app.strips.every((s) => s.place)
? RigLayout.computePlaced(
app.strips.map((s) => ({ place: s.place, leds: s.info.leds })),
rect.width,
rect.height,
)
: RigLayout.computeGeometry(
app.cfg.layout,
app.strips.map((s) => s.info),
rect.width,
rect.height,
);
app.fullRedraw = true;
}
function colourAt(frame, i) {
const j = i * 3;
const r = frame[j] | 0;
const g = frame[j + 1] | 0;
const b = frame[j + 2] | 0;
if (r === 0 && g === 0 && b === 0) {
return null;
}
return `rgb(${r},${g},${b})`;
}
function drawLabel(s, sg) {
const ctx = app.ctx;
const pad = 4;
// clear the label band for this strip
ctx.fillStyle = '#0e0f12';
ctx.fillRect(sg.x0 - 1, sg.top, sg.w + 2, sg.y - sg.top - 1);
ctx.font = '11px system-ui, -apple-system, Segoe UI, Roboto, sans-serif';
ctx.textBaseline = 'middle';
ctx.textAlign = sg.labelAlign;
const arrow = sg.reversed ? '◂' : '▸';
const text = sg.reversed ? `${s.name} ${s.info.n} ${arrow}` : `${arrow} ${s.info.n} ${s.name}`;
ctx.fillStyle = s.lit ? LABEL_LIT : LABEL;
const dot = 7;
let tx = sg.labelX;
if (sg.reversed) {
tx -= dot + pad;
} else {
tx += dot + pad;
}
ctx.fillText(text, tx, sg.labelY);
// power state dot at the strip's start end
ctx.fillStyle = STATE_COLOUR[s.state] || STATE_COLOUR.off;
ctx.beginPath();
const dx = sg.reversed ? sg.labelX - dot / 2 : sg.labelX + dot / 2;
ctx.arc(dx, sg.labelY, dot / 2, 0, Math.PI * 2);
ctx.fill();
}
function drawPlaced(s) {
const ctx = app.ctx;
const geo = app.geo;
const sg = geo.strips[s.index];
const leds = s.info.leds;
const gap = sg.pitch >= 3 ? 1 : 0;
let lit = false;
ctx.save();
ctx.translate(sg.ax, sg.ay);
ctx.rotate(sg.ang);
for (let i = 0; i < leds; i += 1) {
const col = colourAt(s.frame, i);
if (col) {
lit = true;
}
ctx.fillStyle = col || OFF_COLOUR;
ctx.fillRect(i * sg.pitch, -geo.ledH / 2, Math.max(1, sg.pitch - gap), geo.ledH);
}
if (app.selected === s) {
ctx.strokeStyle = SELECT;
ctx.lineWidth = 1.5;
ctx.strokeRect(-1.5, -geo.ledH / 2 - 1.5, sg.len + 3, geo.ledH + 3);
}
// power state dot just before pixel 0 (the data-in head)
ctx.fillStyle = STATE_COLOUR[s.state] || STATE_COLOUR.off;
ctx.beginPath();
ctx.arc(-7, 0, 3.5, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
ctx.font = '11px system-ui, -apple-system, Segoe UI, Roboto, sans-serif';
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
ctx.fillStyle = lit ? LABEL_LIT : LABEL;
ctx.fillText(`${s.info.n} ${s.name}`, sg.labelX, sg.labelY);
s.lit = lit;
}
function drawStrip(s) {
const ctx = app.ctx;
const geo = app.geo;
const sg = geo.strips[s.index];
const leds = s.info.leds;
ctx.fillStyle = '#0e0f12';
ctx.fillRect(sg.x0 - 2, sg.y - 2, sg.w + 4, sg.h + 4);
let lit = false;
for (let i = 0; i < leds; i += 1) {
const col = colourAt(s.frame, i);
if (col) {
lit = true;
}
ctx.fillStyle = col || OFF_COLOUR;
ctx.fillRect(RigLayout.pixelX(geo, sg, i, leds), sg.y, geo.ledW, sg.h);
}
if (app.selected === s) {
ctx.strokeStyle = SELECT;
ctx.lineWidth = 1.5;
ctx.strokeRect(sg.x0 - 1.5, sg.y - 1.5, sg.w + 3, sg.h + 3);
}
s.lit = lit;
drawLabel(s, sg);
}
function frame() {
if (app.geo) {
const ctx = app.ctx;
ctx.setTransform(app.dpr, 0, 0, app.dpr, 0, 0);
if (app.geo.placed) {
// rotated bars overlap their neighbours' clear boxes: redraw everything when anything changed
if (app.fullRedraw || app.strips.some((s) => s.dirty)) {
const c = app.canvas;
ctx.fillStyle = '#0e0f12';
ctx.fillRect(0, 0, c.width / app.dpr, c.height / app.dpr);
ctx.fillStyle = CENTRE;
ctx.beginPath();
ctx.arc(app.geo.centre.x, app.geo.centre.y, 3, 0, Math.PI * 2);
ctx.fill();
for (const s of app.strips) {
s.dirty = false;
drawPlaced(s);
}
app.fullRedraw = false;
}
requestAnimationFrame(frame);
return;
}
if (app.fullRedraw) {
const c = app.canvas;
ctx.fillStyle = '#0e0f12';
ctx.fillRect(0, 0, c.width / app.dpr, c.height / app.dpr);
ctx.strokeStyle = CENTRE;
ctx.setLineDash([4, 4]);
ctx.lineWidth = 1;
for (const x of app.geo.centreLines) {
ctx.beginPath();
ctx.moveTo(x + 0.5, 6);
ctx.lineTo(x + 0.5, c.height / app.dpr - 6);
ctx.stroke();
}
ctx.setLineDash([]);
for (const s of app.strips) {
s.dirty = true;
}
app.fullRedraw = false;
}
for (const s of app.strips) {
if (s.dirty) {
s.dirty = false;
drawStrip(s);
}
}
}
requestAnimationFrame(frame);
}
function stripAt(x, y) {
const geo = app.geo;
if (!geo) {
return null;
}
if (geo.placed) {
let best = null;
let bestD = 12;
for (const s of app.strips) {
const sg = geo.strips[s.index];
const dx = sg.bx - sg.ax;
const dy = sg.by - sg.ay;
const t = Math.max(0, Math.min(1, ((x - sg.ax) * dx + (y - sg.ay) * dy) / (dx * dx + dy * dy || 1)));
const d = Math.hypot(x - (sg.ax + t * dx), y - (sg.ay + t * dy));
if (d < bestD) {
bestD = d;
best = s;
}
}
return best;
}
for (const s of app.strips) {
const sg = geo.strips[s.index];
if (x >= sg.x0 - 4 && x <= sg.x0 + sg.w + 4 && y >= sg.top && y <= sg.top + sg.rowH) {
return s;
}
}
return null;
}
// ----- boot --------------------------------------------------------------------
function wireUi() {
$('power-on-all').onclick = () => app.strips.forEach(powerOn);
$('power-off-all').onclick = () => app.strips.forEach(powerOff);
$('power-cycle-all').onclick = () => {
app.strips.forEach(powerOff);
app.strips.forEach(powerOn);
};
const auto = $('auto-power');
auto.checked = readAuto();
auto.onchange = () => writeAuto(auto.checked);
$('d-close').onclick = () => select(app.selected);
$('d-on').onclick = () => app.selected && powerOn(app.selected);
$('d-off').onclick = () => app.selected && powerOff(app.selected);
$('d-reset').onclick = () => app.selected && reset(app.selected);
$('d-clear').onclick = () => {
if (app.selected) {
app.selected.logs = [];
$('d-log').textContent = '';
}
};
app.canvas.addEventListener('click', (ev) => {
const r = app.canvas.getBoundingClientRect();
const s = stripAt(ev.clientX - r.left, ev.clientY - r.top);
if (s) {
select(s);
}
});
new ResizeObserver(() => resize()).observe($('rig'));
window.addEventListener('keydown', (ev) => {
if (ev.key === 'Escape' && app.selected) {
select(app.selected);
}
});
}
async function main() {
app.canvas = $('rig-canvas');
app.ctx = app.canvas.getContext('2d');
try {
app.cfg = await fetch('/api/config').then((r) => r.json());
} catch (err) {
banner(`Could not load /api/config: ${err}`);
return;
}
app.bridgeMac = macBytes(app.cfg.bridge.mac);
app.strips = app.cfg.strips.map(makeStrip);
for (const s of app.strips) {
app.byMac.set(s.mac, s);
}
const b = app.cfg.bridge;
const lay = app.cfg.layout;
document.title = `${b.name} · LED Rig Simulator`;
$('hint').innerHTML =
`${app.strips.length} strips × ${lay.leds_per_strip} LEDs, ${lay.columns} × ${lay.rows}. ` +
(b.udp_port
? `In led-controller set <code>"bridge": "${b.lan_ip}:${b.udp_port}"</code> (or <code>127.0.0.1:${b.udp_port}</code>) ` +
'in settings and restart it, or run its host build (<code>make sim</code>). '
: `In led-controller add a bridge: transport <code>ip</code>, address <code>${b.lan_ip}</code> ` +
`(or <code>127.0.0.1</code>), port <code>${b.port}</code>. `) +
'Strips register with their hello when they power on; power-cycle a strip to register it again.';
wireUi();
resize();
requestAnimationFrame(frame);
updateChips();
if (!self.crossOriginIsolated) {
banner(
`This page is not cross-origin isolated, so drivers cannot run (they need SharedArrayBuffer). ` +
`Open it as http://localhost:${b.port}/ on the computer running server.py, or over HTTPS.`,
);
}
setButtons();
connectBridge();
if (self.crossOriginIsolated && readAuto()) {
app.strips.forEach(powerOn);
}
}
main();
})();