Files
led-controller/led-simulator/web/app.js
T
jimmyandClaude Opus 5.5 581b751904 feat: browser simulator served by the controller, desktop build, browser bridge
- led-simulator: the rig runs the C++ led-driver as WebAssembly (sim-driver/),
  one single-threaded worker per bar, no cross-origin isolation needed. Rooms
  (one JSON per room) with an on-page editor, and a pattern gallery. The
  Python server, Pyodide boot and ring buffer are removed.
- sim-controller sim_rig.c: serves /sim/ from an embedded pack, the page's
  WebSocket and the rooms/flash API. The desktop build embeds it too.
- bridge.c: a "browser" bridge kind that carries ESP-NOW frames to the page;
  devices announced through it are marked sim.
- UI: Simulator in the Menu, split view with resize and pop-out, swipe
  between controller and rig on phones; SIM/REAL badges in Devices.
- Fades: preset pushes and Wi-Fi driver bodies always carry fade and
  beat_time, so "off" no longer inherits an earlier fade.
- Also the sequences-v2 work in progress: desktop port, bridge firmware,
  serial bridge, Wi-Fi drivers, sequence timeline, audio and API changes.
- led-driver: ESP-NOW link, beat sync, control messages, sim hooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 19:32:46 +13:00

1264 lines
38 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.
/* The simulated rig, served by led-controller's host build at /sim/ (sim-controller/components/sim/sim_rig.c).
*
* Each bar is a module worker running the C++ led-driver built to WebAssembly (driver-worker.js). The page is
* the radio between them and the controller's "browser" bridge (WebSocket /sim/ws):
* controller -> page binary dest_mac(6) + ESP-NOW packet (the controller transmits)
* page -> controller binary src_mac(6) + ESP-NOW packet (a driver transmits)
* controller -> page text {"t":"takeover"} (another page opened the rig)
* page -> controller text {"t":"flash","mac":..,"data":..} (a driver committed its NVS store)
*
* Where the bars are is the active room. In Edit mode the room can be changed: add bars by clicking the floor,
* drag to move, drag the end handle to turn, Delete to remove. Every change is saved (PUT /sim/api/rooms/<name>)
* and the bars' places go to the controller's rig layout (POST /devices/layout).
*/
/* global RigLayout */
(function () {
'use strict';
const BG = '#0e0f12';
const FLOOR = '#121419';
const GRID = '#1b1e25';
const WALL = '#2f3440';
const OFF_COLOUR = '#1d1f24';
const LABEL = '#8a909c';
const LABEL_LIT = '#d6dae2';
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 LED_H = 9;
const HANDLE_R = 6;
const SNAP_M = 0.05;
const SNAP_DEG = 15;
const $ = (id) => document.getElementById(id);
const params = new URLSearchParams(location.search);
// Test hook: a stand-in worker script under /sim/.
const workerUrl = /^\/sim\/[\w.-]+\.js$/.test(params.get('worker') || '')
? params.get('worker')
: '/sim/driver-worker.js';
const app = {
cfg: null,
room: null,
roomName: '',
bridgeMac: null,
strips: [],
byMac: new Map(),
ws: null,
wsOpen: false,
takenOver: false,
seedTimer: 0,
queue: [],
booting: 0,
view: null,
geo: [],
dirty: true,
selected: null,
canvas: null,
ctx: null,
dpr: 1,
edit: false,
drag: null,
saveTimer: 0,
lastDef: '',
};
// ----- 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
}
}
async function api(method, path, body) {
const r = await fetch(path, {
method,
headers: body === undefined ? {} : { 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
let data = null;
try {
data = await r.json();
} catch (_e) {
data = null;
}
if (!r.ok) {
throw new Error((data && data.error) || `${method} ${path}: HTTP ${r.status}`);
}
return data;
}
/** The driver's hostname from its NVS store, if it has one. */
function hostnameOf(nvsText) {
try {
const v = JSON.parse(nvsText).led.hostname;
return Array.isArray(v) && v[0] === 'str' && v[1] ? String(v[1]) : '';
} catch (_e) {
return '';
}
}
// ----- strips: power and workers ------------------------------------------
function makeStrip(info) {
return {
info,
id: info.id,
mac: info.mac,
macBytes: macBytes(info.mac),
name: info.label,
bootedLeds: 0,
state: 'off',
worker: null,
frame: new Uint8Array(info.leds * 3),
lit: false,
logs: [],
rx: 0,
tx: 0,
error: '',
};
}
function setState(s, state, error = '') {
s.state = state;
s.error = error;
app.dirty = true;
updateChips();
if (app.selected === s) {
renderDrawer();
}
}
function addLog(s, text) {
for (const line of String(text).split('\n')) {
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 (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.frame = new Uint8Array(s.info.leds * 3);
setState(s, 'off');
pumpQueue();
}
function reset(s) {
powerOff(s);
addLog(s, '--- reset ---');
powerOn(s);
}
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 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 nvs = await api('GET', `/sim/api/flash/${s.mac}`);
const nvsText = JSON.stringify(nvs);
s.name = hostnameOf(nvsText) || s.info.label;
if (s.state !== 'queued') {
app.booting -= 1;
return;
}
const worker = new Worker(workerUrl, { type: 'module' });
s.worker = worker;
s.bootedLeds = s.info.leds;
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',
mac: s.mac.replace(/:/g, ''),
nvs: nvsText,
fps: app.cfg.drivers.fps ?? 30,
});
}
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;
if (isReset) {
s.frame = new Uint8Array(s.info.leds * 3);
setState(s, 'off');
addLog(s, '--- esp_restart() ---');
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();
clearTimeout(app.seedTimer);
app.seedTimer = setTimeout(() => seedPlacements(false), 4000); // once its announce has registered it
}
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;
app.dirty = true;
break;
case 'flash': {
if (app.wsOpen) {
app.ws.send(JSON.stringify({ t: 'flash', mac: s.mac, data: m.data }));
}
const name = hostnameOf(m.data);
if (name && name !== s.name) {
s.name = name;
app.dirty = true;
if (app.selected === s) {
renderDrawer();
}
}
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.worker) {
return; // powered off or still booting: the packet is lost, as on air
}
s.worker.postMessage({ t: 'rx', data: 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`);
ws.binaryType = 'arraybuffer';
app.ws = ws;
ws.onopen = () => {
app.wsOpen = true;
if (!app.takenOver) {
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 === '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);
};
}
// ----- room: strips from fixtures, saving, switching -------------------------
/** Bring the strip list in line with the room: new fixtures appear off, removed ones power off. */
function syncStrips() {
const infos = RigLayout.roomStrips(app.room);
const old = new Map(app.strips.map((s) => [s.id, s]));
const next = [];
for (const info of infos) {
let s = old.get(info.id);
if (s && s.mac !== info.mac) {
powerOff(s);
s = null;
}
if (s) {
old.delete(info.id);
s.info = info;
if (s.state === 'off') {
s.name = info.label;
s.frame = new Uint8Array(info.leds * 3);
}
} else {
s = makeStrip(info);
}
next.push(s);
}
for (const s of old.values()) {
powerOff(s);
if (app.selected === s) {
app.selected = null;
}
}
app.strips = next;
app.byMac = new Map(next.map((s) => [s.mac, s]));
layoutView();
updateChips();
renderDrawer();
if (app.cfg) {
renderHint();
}
}
function scheduleSave() {
clearTimeout(app.saveTimer);
$('save-state').textContent = 'saving…';
app.saveTimer = setTimeout(saveRoom, 400);
}
async function saveRoom() {
const name = app.roomName;
try {
const out = await api('PUT', `/sim/api/rooms/${encodeURIComponent(name)}`, app.room);
if (name === app.roomName) {
$('save-state').textContent = 'saved';
seedPlacements(true);
app.room.width = out.room.width;
app.room.depth = out.room.depth;
}
} catch (err) {
$('save-state').textContent = 'not saved';
banner(`Saving the room failed: ${err.message}. Reloaded it from the server.`);
app.room = await api('GET', `/sim/api/rooms/${encodeURIComponent(name)}`);
syncStrips();
}
}
function changed() {
syncStrips();
scheduleSave();
}
async function switchRoom(name) {
if (name === app.roomName) {
return;
}
let cfg;
try {
cfg = await api('POST', '/sim/api/room', { name });
} catch (err) {
banner(`Could not switch room: ${err.message}`);
$('room-select').value = app.roomName;
return;
}
for (const s of app.strips) {
powerOff(s);
}
app.strips = [];
app.selected = null;
applyConfig(cfg);
if (readAuto()) {
app.strips.forEach(powerOn);
}
}
function applyConfig(cfg) {
app.cfg = cfg;
app.room = cfg.room;
app.roomName = cfg.room_name;
const sel = $('room-select');
sel.replaceChildren(...cfg.rooms.map((n) => new Option(n, n, false, n === cfg.room_name)));
app.lastDef = Object.keys(app.room.definitions)[0];
syncStrips();
renderHint();
}
/** A label for a new strip: drivers.name with n from its MAC, which no other room uses, so the name is unique too. */
function nextLabel(mac) {
const fmt = String(app.cfg.drivers.name || 'sim-{n:02d}');
const n0 = parseInt(mac.split(':').slice(-2).join(''), 16);
for (let n = n0; n < n0 + 1000; n += 1) {
const label = fmt
.replace(/\{n(?::0?(\d+)d)?\}/, (_m, w) => String(n).padStart(Number(w) || 0, '0'))
.replace(/\{[^}]*\}/g, '');
if (!(label in app.room.fixtures) && !Object.values(app.room.fixtures).some((f) => f.label === label)) {
return label;
}
}
return mac.replace(/:/g, '');
}
async function addFixture(x, y) {
let mac;
try {
const taken = Object.values(app.room.fixtures).map((f) => f.mac).join(',');
mac = (await api('GET', `/sim/api/next-mac?taken=${encodeURIComponent(taken)}`)).mac;
} catch (err) {
banner(`Could not add a strip: ${err.message}`);
return;
}
const label = nextLabel(mac);
app.room.fixtures[label] = {
label,
def: app.lastDef in app.room.definitions ? app.lastDef : Object.keys(app.room.definitions)[0],
mac,
x: round3(Math.round(x / SNAP_M) * SNAP_M),
y: round3(Math.round(y / SNAP_M) * SNAP_M),
direction: 90,
};
changed();
app.selected = app.strips.find((s) => s.id === label) || null;
renderDrawer();
}
function deleteFixture(s) {
if (!s || !(s.id in app.room.fixtures)) {
return;
}
delete app.room.fixtures[s.id];
if (app.selected === s) {
app.selected = null;
}
changed();
}
// ----- the controller: rig layout and the browser bridge -------------------------------
/** Where each bar is for the controller's rig layout: the room fitted to its 1000 x 700 canvas (y up),
* x0,y0 at pixel 0, keyed by MAC without colons. */
function rigPlacements() {
const W = 1000;
const H = 700;
const M = 20;
const s = Math.min((W - 2 * M) / app.room.width, (H - 2 * M) / app.room.depth);
const tx = (x) => Math.round((W / 2 + x * s) * 10) / 10;
const ty = (y) => Math.round((H / 2 + (y - app.room.depth / 2) * s) * 10) / 10;
const out = {};
for (const st of RigLayout.roomStrips(app.room)) {
out[st.mac.replace(/:/g, '')] = { x0: tx(st.x), y0: ty(st.y), x1: tx(st.x1), y1: ty(st.y1) };
}
return out;
}
/** Give the controller the room's places: every bar it knows (all = true, after an edit), else only the bars it
* has not placed yet. Bars that have not registered yet are tried again a little later. */
async function seedPlacements(all = false) {
clearTimeout(app.seedTimer);
let devices;
try {
devices = await api('GET', '/devices');
} catch (_e) {
return;
}
const places = rigPlacements();
const todo = {};
let missing = 0;
for (const [mac, pl] of Object.entries(places)) {
const dev = devices[mac];
if (!dev) {
missing += 1;
} else if (all || !(dev.placement && typeof dev.placement === 'object')) {
todo[mac] = pl;
}
}
if (Object.keys(todo).length) {
const body = { placements: todo };
if (!Object.values(devices).some((d) => d && d.placement)) {
body.center = { x: 500, y: 350 }; // a fresh rig: the room's centre
}
try {
await api('POST', '/devices/layout', body);
} catch (_e) {
// the controller logs it; the next seed tries again
}
}
if (missing && app.strips.some((s) => s.state !== 'off')) {
app.seedTimer = setTimeout(() => seedPlacements(false), 5000);
}
}
/** Put "browser" in the controller's bridges, so its ESP-NOW frames reach this page. */
async function addBridge() {
try {
const st = await api('GET', '/settings/bridge');
const addrs = (st.bridges || []).map((b) => b.addr).filter((a) => a && a !== 'browser');
await api('PUT', '/settings/bridge', { bridges: [...addrs, 'browser'] });
app.cfg.bridge.running = true;
banner('');
} catch (err) {
banner(`Could not add the browser bridge: ${err.message}`);
}
updateChips();
}
// ----- UI: chips, drawer, dialogs ------------------------------------------------
function updateChips() {
if (!app.cfg) {
return;
}
const b = app.cfg.bridge;
$('bridge-chip').textContent = `${b.name} · ${b.mac}`;
const cc = $('controller-chip');
const on = app.wsOpen && b.running;
cc.textContent = !app.wsOpen ? 'controller: –' : b.running ? 'browser bridge: on' : 'browser bridge: off';
cc.className = `chip ${on ? 'ok' : 'warn'}`;
$('add-bridge').hidden = !app.wsOpen || b.running;
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 renderHint() {
$('hint').innerHTML =
`Room <b>${app.roomName}</b>: ${app.room.width} × ${app.room.depth} m, ${app.strips.length} bars. ` +
'Each bar is the C++ led-driver; it registers with this controller when it powers on, ' +
'and its place in the room goes to the controller\'s rig layout. ' +
'<a href="/" target="_top">Open the controller</a> to drive them.';
}
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 i = s.info;
$('d-pos').textContent = `${i.x.toFixed(2)}, ${i.y.toFixed(2)} m · heading ${i.direction}° · ${i.leds} LEDs`;
$('d-packets').textContent = `${s.rx} received · ${s.tx} sent`;
const stale = s.state !== 'off' && s.bootedLeds && s.bootedLeds !== i.leds;
$('d-note').hidden = !stale;
$('d-note').textContent = stale ? `Running with ${s.bootedLeds} LEDs: power-cycle it to use ${i.leds}.` : '';
}
function renderEditForm() {
const s = app.selected;
const f = s && app.room.fixtures[s.id];
$('d-edit').hidden = !app.edit || !f;
if (!app.edit || !f) {
return;
}
const sel = $('e-def');
sel.replaceChildren(
...Object.entries(app.room.definitions).map(
([k, d]) => new Option(`${k} (${d.leds} LEDs, ${Math.round(1 / d.pitch_m)}/m)`, k, false, k === f.def),
),
);
const set = (id, v) => {
if (document.activeElement !== $(id)) {
$(id).value = v;
}
};
set('e-label', f.label);
set('e-leds', f.leds ?? '');
$('e-leds').placeholder = String(app.room.definitions[f.def].leds);
set('e-x', round3(f.x));
set('e-y', round3(f.y));
set('e-dir', f.direction);
}
function renderDrawer() {
const s = app.selected;
// In Edit mode the drawer stays open, so selecting a strip never resizes the room under the pointer
const wasHidden = $('drawer').hidden;
$('drawer').hidden = !s && !app.edit;
$('d-empty').hidden = Boolean(s);
$('d-body').hidden = !s;
if (wasHidden !== $('drawer').hidden) {
requestAnimationFrame(layoutView);
}
if (!s) {
return;
}
$('d-name').textContent = s.name;
$('d-meta').textContent = `${s.id} · ${s.mac}`;
renderFacts();
renderEditForm();
const off = s.state === 'off' || s.state === 'crashed';
$('d-on').disabled = !off || app.takenOver;
$('d-off').disabled = off;
$('d-reset').disabled = app.takenOver;
const el = $('d-log');
el.textContent = s.logs.join('\n');
el.scrollTop = el.scrollHeight;
}
function select(s) {
app.selected = s;
app.dirty = true;
renderDrawer();
}
function setButtons() {
const ok = !app.takenOver;
for (const id of ['power-on-all', 'power-cycle-all', 'power-off-all']) {
$(id).disabled = !ok;
}
renderDrawer();
}
function setEdit(on) {
app.edit = on;
document.body.classList.toggle('editing', on);
$('edit-toggle').textContent = on ? 'Done' : 'Edit room';
$('edit-tools').hidden = !on;
$('save-state').textContent = '';
app.dirty = true;
renderDrawer();
}
function fixtureField(key, raw) {
const s = app.selected;
const f = s && app.room.fixtures[s.id];
if (!f) {
return;
}
if (key === 'label') {
f.label = String(raw).trim().slice(0, 47) || s.id;
} else if (key === 'def') {
f.def = raw;
app.lastDef = raw;
} else if (key === 'leds') {
const n = Math.round(Number(raw));
if (raw === '' || !n) {
delete f.leds;
} else {
f.leds = Math.max(1, Math.min(512, n));
}
} else {
const v = Number(raw);
if (!Number.isFinite(v)) {
return;
}
f[key] = key === 'direction' ? wrapDeg(v) : Math.round(v * 1000) / 1000;
}
changed();
}
function round3(v) {
return Math.round(v * 1000) / 1000;
}
function wrapDeg(d) {
let a = ((d % 360) + 360) % 360;
if (a > 180) {
a -= 360;
}
return Math.round(a * 10) / 10;
}
function openRoomDialog() {
$('r-width').value = app.room.width;
$('r-depth').value = app.room.depth;
renderDefs();
$('room-dialog').showModal();
}
function renderDefs() {
const rows = Object.entries(app.room.definitions).map(([k, d]) => {
const used = Object.values(app.room.fixtures).filter((f) => f.def === k).length;
const tr = document.createElement('tr');
tr.innerHTML =
`<td><code></code></td><td><input type="number" min="1" max="512" step="1" data-k="leds"></td>` +
`<td><input type="number" min="1" max="1000" step="1" data-k="per_m"></td><td class="muted"></td><td></td>`;
tr.querySelector('code').textContent = k;
tr.querySelector('[data-k=leds]').value = d.leds;
tr.querySelector('[data-k=per_m]').value = Math.round(1 / d.pitch_m);
tr.children[3].textContent = used ? `${used} strip${used === 1 ? '' : 's'}` : 'unused';
for (const inp of tr.querySelectorAll('input')) {
inp.onchange = () => {
const v = Number(inp.value);
if (!(v > 0)) {
return;
}
if (inp.dataset.k === 'leds') {
d.leds = Math.min(512, Math.round(v));
} else {
d.pitch_m = Math.round((1 / v) * 100000) / 100000;
}
changed();
};
}
if (!used && Object.keys(app.room.definitions).length > 1) {
const del = document.createElement('button');
del.type = 'button';
del.className = 'link';
del.textContent = 'remove';
del.onclick = () => {
delete app.room.definitions[k];
changed();
renderDefs();
};
tr.children[4].append(del);
}
return tr;
});
$('r-defs').replaceChildren(...rows);
}
function wireDialogs() {
$('room-settings').onclick = openRoomDialog;
$('r-close').onclick = () => $('room-dialog').close();
for (const id of ['r-width', 'r-depth']) {
$(id).onchange = () => {
const v = Number($(id).value);
if (v >= 0.5 && v <= 200) {
app.room[id === 'r-width' ? 'width' : 'depth'] = v;
changed();
}
};
}
$('r-add-def').onclick = () => {
const name = $('r-def-name').value.trim();
const leds = Math.round(Number($('r-def-leds').value));
const perM = Number($('r-def-perm').value) || 60;
if (!/^[A-Za-z0-9_.#-]{1,40}$/.test(name) || name in app.room.definitions || !(leds >= 1 && leds <= 512)) {
$('r-def-name').focus();
return;
}
app.room.definitions[name] = { leds, pitch_m: Math.round((1 / perM) * 100000) / 100000 };
app.lastDef = name;
$('r-def-name').value = '';
changed();
renderDefs();
};
$('room-new').onclick = () => {
$('n-name').value = '';
$('n-width').value = app.room.width;
$('n-depth').value = app.room.depth;
$('n-copy').checked = false;
$('n-error').textContent = '';
$('new-dialog').showModal();
$('n-name').focus();
};
$('n-cancel').onclick = () => $('new-dialog').close();
$('new-form').onsubmit = async (ev) => {
ev.preventDefault();
const name = $('n-name').value.trim();
try {
await api('POST', '/sim/api/rooms', {
name,
width: Number($('n-width').value),
depth: Number($('n-depth').value),
copy_from: $('n-copy').checked ? app.roomName : undefined,
});
} catch (err) {
$('n-error').textContent = err.message;
return;
}
$('new-dialog').close();
await switchRoom(name);
setEdit(true);
};
$('room-delete').onclick = async () => {
const others = app.cfg.rooms.filter((n) => n !== app.roomName);
if (!others.length) {
banner('This is the only room: make another one before deleting it.', 'info');
return;
}
if (!confirm(`Delete room "${app.roomName}"? Its file rooms/${app.roomName}.json is removed; the strips' flash is kept.`)) {
return;
}
const doomed = app.roomName;
await switchRoom(others[0]);
try {
const info = await api('DELETE', `/sim/api/rooms/${encodeURIComponent(doomed)}`);
app.cfg.rooms = info.rooms;
$('room-select').replaceChildren(...info.rooms.map((n) => new Option(n, n, false, n === app.roomName)));
} catch (err) {
banner(`Could not delete the room: ${err.message}`);
}
};
}
// ----- canvas ----------------------------------------------------------------
function layoutView() {
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));
app.view = RigLayout.fit(app.room, rect.width, rect.height);
app.geo = RigLayout.stripGeometry(app.view, app.strips.map((s) => s.info));
app.dirty = 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 drawRoom() {
const ctx = app.ctx;
const v = app.view;
const w = app.room.width;
const d = app.room.depth;
const x0 = v.sx(-w / 2);
const x1 = v.sx(w / 2);
const y0 = v.sy(d);
const y1 = v.sy(0);
ctx.fillStyle = FLOOR;
ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
ctx.strokeStyle = GRID;
ctx.lineWidth = 1;
ctx.beginPath();
for (let x = Math.ceil(-w / 2); x <= w / 2; x += 1) {
ctx.moveTo(Math.round(v.sx(x)) + 0.5, y0);
ctx.lineTo(Math.round(v.sx(x)) + 0.5, y1);
}
for (let y = 1; y < d; y += 1) {
ctx.moveTo(x0, Math.round(v.sy(y)) + 0.5);
ctx.lineTo(x1, Math.round(v.sy(y)) + 0.5);
}
ctx.stroke();
ctx.strokeStyle = WALL;
ctx.lineWidth = 2;
ctx.strokeRect(x0, y0, x1 - x0, y1 - y0);
ctx.font = '11px system-ui, -apple-system, Segoe UI, Roboto, sans-serif';
ctx.fillStyle = LABEL;
ctx.textAlign = 'left';
ctx.textBaseline = 'bottom';
ctx.fillText(`${app.roomName} · ${w} × ${d} m · 1 m grid`, x0, y0 - 6);
}
function drawStrip(s, sg) {
const ctx = app.ctx;
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);
const shown = Math.min(leds, s.frame.length / 3);
for (let i = 0; i < leds; i += 1) {
const col = i < shown ? colourAt(s.frame, i) : null;
if (col) {
lit = true;
}
ctx.fillStyle = col || OFF_COLOUR;
ctx.fillRect(i * sg.pitch, -LED_H / 2, Math.max(1, sg.pitch - gap), LED_H);
}
if (app.selected === s) {
ctx.strokeStyle = SELECT;
ctx.lineWidth = 1.5;
ctx.strokeRect(-1.5, -LED_H / 2 - 1.5, sg.len + 3, LED_H + 3);
}
// power state dot just before pixel 0 (the data-in end)
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();
if (app.edit) {
// turn handle at the strip's far end
ctx.strokeStyle = app.selected === s ? SELECT : LABEL;
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.arc(sg.bx, sg.by, HANDLE_R, 0, Math.PI * 2);
ctx.stroke();
}
ctx.font = '11px system-ui, -apple-system, Segoe UI, Roboto, sans-serif';
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
ctx.fillStyle = lit ? LABEL_LIT : LABEL;
// label on the side of the strip that faces up the screen
const nx = Math.sin(sg.ang);
const ny = -Math.cos(sg.ang);
const side = ny <= 0 ? 1 : -1;
ctx.fillText(s.name, (sg.ax + sg.bx) / 2 + nx * 13 * side, (sg.ay + sg.by) / 2 + ny * 13 * side);
s.lit = lit;
}
function frame() {
if (app.view && app.dirty) {
app.dirty = false;
const ctx = app.ctx;
const c = app.canvas;
ctx.setTransform(app.dpr, 0, 0, app.dpr, 0, 0);
ctx.fillStyle = BG;
ctx.fillRect(0, 0, c.width / app.dpr, c.height / app.dpr);
drawRoom();
app.strips.forEach((s, i) => drawStrip(s, app.geo[i]));
}
requestAnimationFrame(frame);
}
/** What is under the pointer: {s, part: 'handle' | 'body'} or null. */
function hitTest(x, y) {
if (app.edit) {
for (let i = app.strips.length - 1; i >= 0; i -= 1) {
const sg = app.geo[i];
if (Math.hypot(x - sg.bx, y - sg.by) <= HANDLE_R + 3) {
return { s: app.strips[i], part: 'handle' };
}
}
}
let best = null;
let bestD = 10;
app.strips.forEach((s, i) => {
const d = RigLayout.distToStrip(app.geo[i], x, y);
if (d < bestD) {
bestD = d;
best = s;
}
});
return best ? { s: best, part: 'body' } : null;
}
function pointerPos(ev) {
const r = app.canvas.getBoundingClientRect();
return [ev.clientX - r.left, ev.clientY - r.top];
}
function wireCanvas() {
const c = app.canvas;
c.addEventListener('pointerdown', (ev) => {
const [x, y] = pointerPos(ev);
const hit = hitTest(x, y);
if (!app.edit) {
if (hit) {
select(app.selected === hit.s ? null : hit.s);
}
return;
}
if (!hit) {
app.drag = { kind: 'floor', x, y };
return;
}
const f = app.room.fixtures[hit.s.id];
select(hit.s);
app.drag = {
kind: hit.part === 'handle' ? 'turn' : 'move',
s: hit.s,
startX: f.x,
startY: f.y,
mx: app.view.mx(x),
my: app.view.my(y),
moved: false,
};
c.setPointerCapture(ev.pointerId);
});
c.addEventListener('pointermove', (ev) => {
const [x, y] = pointerPos(ev);
const d = app.drag;
if (!d) {
if (app.edit) {
const hit = hitTest(x, y);
c.style.cursor = hit ? (hit.part === 'handle' ? 'crosshair' : 'move') : 'copy';
} else {
c.style.cursor = hitTest(x, y) ? 'pointer' : 'default';
}
return;
}
if (d.kind === 'floor') {
return;
}
const f = app.room.fixtures[d.s.id];
if (!f) {
app.drag = null;
return;
}
const wx = app.view.mx(x);
const wy = app.view.my(y);
if (d.kind === 'move') {
const snap = ev.altKey ? 0.001 : SNAP_M;
f.x = round3(Math.round((d.startX + wx - d.mx) / snap) * snap);
f.y = round3(Math.round((d.startY + wy - d.my) / snap) * snap);
} else {
const deg = (Math.atan2(wx - f.x, wy - f.y) * 180) / Math.PI;
f.direction = wrapDeg(ev.shiftKey ? deg : Math.round(deg / SNAP_DEG) * SNAP_DEG);
}
d.moved = true;
d.s.info = Object.assign(d.s.info, RigLayout.roomStrips(app.room).find((i) => i.id === d.s.id));
app.geo = RigLayout.stripGeometry(app.view, app.strips.map((s) => s.info));
app.dirty = true;
renderFacts();
renderEditForm();
});
const end = (ev) => {
const d = app.drag;
app.drag = null;
if (!d) {
return;
}
if (d.kind === 'floor') {
const [x, y] = pointerPos(ev);
if (Math.hypot(x - d.x, y - d.y) < 4 && ev.type === 'pointerup') {
const wx = app.view.mx(x);
const wy = app.view.my(y);
if (Math.abs(wx) <= app.room.width / 2 && wy >= 0 && wy <= app.room.depth) {
addFixture(wx, wy);
} else {
select(null);
}
}
return;
}
if (d.moved) {
changed();
}
};
c.addEventListener('pointerup', end);
c.addEventListener('pointercancel', end);
}
// ----- 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);
$('room-select').onchange = () => switchRoom($('room-select').value);
$('add-bridge').onclick = addBridge;
$('edit-toggle').onclick = () => setEdit(!app.edit);
$('d-close').onclick = () => select(null);
$('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-delete').onclick = () => deleteFixture(app.selected);
$('d-clear').onclick = () => {
if (app.selected) {
app.selected.logs = [];
$('d-log').textContent = '';
}
};
$('e-label').onchange = () => fixtureField('label', $('e-label').value);
$('e-def').onchange = () => fixtureField('def', $('e-def').value);
$('e-leds').onchange = () => fixtureField('leds', $('e-leds').value);
$('e-x').onchange = () => fixtureField('x', $('e-x').value);
$('e-y').onchange = () => fixtureField('y', $('e-y').value);
$('e-dir').onchange = () => fixtureField('direction', $('e-dir').value);
wireDialogs();
wireCanvas();
new ResizeObserver(() => layoutView()).observe($('rig'));
window.addEventListener('keydown', (ev) => {
const typing = /^(INPUT|SELECT|TEXTAREA)$/.test(document.activeElement && document.activeElement.tagName);
if (ev.key === 'Escape' && app.selected && !typing) {
select(null);
} else if (app.edit && app.selected && !typing && (ev.key === 'Delete' || ev.key === 'Backspace')) {
ev.preventDefault();
deleteFixture(app.selected);
}
});
}
async function main() {
// Beside the controller (its Simulator split view, in an iframe): no link back to the controller
let embedded = false;
try {
embedded = window.top !== window;
} catch (_e) {
embedded = true;
}
document.body.classList.toggle('embedded', embedded);
app.canvas = $('rig-canvas');
app.ctx = app.canvas.getContext('2d');
let cfg;
try {
cfg = await api('GET', '/sim/api/config');
} catch (err) {
banner(`Could not load /sim/api/config: ${err}`);
return;
}
app.bridgeMac = macBytes(cfg.bridge.mac);
document.title = `${cfg.bridge.name} · LED Rig Simulator`;
wireUi();
applyConfig(cfg);
requestAnimationFrame(frame);
setButtons();
connectBridge();
if (readAuto()) {
app.strips.forEach(powerOn);
}
}
main();
})();