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>
This commit is contained in:
commit
698c1463c0
41 files changed
+4369
-4
No files matched your search
@@ -0,0 +1,816 @@
|
||||
/* 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();
|
||||
})();
|
||||
@@ -0,0 +1,84 @@
|
||||
/* One simulated led-driver: Pyodide running led-driver/src/main.py.
|
||||
*
|
||||
* The page posts {t: 'boot', ...} once. The worker loads Pyodide, writes the
|
||||
* strip's flash (driver source, patterns, settings.json, presets.json) and the
|
||||
* stubs into the Pyodide filesystem, then runs web/driver_boot.py, which never
|
||||
* returns while the driver is powered. Power-off is Worker.terminate().
|
||||
*
|
||||
* Messages to the page:
|
||||
* {t:'state', state} loading | running
|
||||
* {t:'log', text} driver serial output (one line)
|
||||
* {t:'tx', data} Uint8Array dest_mac(6) + ESP-NOW packet
|
||||
* {t:'px', data} Uint8Array RGB frame
|
||||
* {t:'flash', path, data} settings.json / presets.json changed
|
||||
* {t:'exit', error, reset} main.py stopped (reset: machine.reset())
|
||||
*/
|
||||
/* global importScripts, loadPyodide, SimRing */
|
||||
importScripts('/web/ring.js');
|
||||
|
||||
let ring = null;
|
||||
let sleepView = null;
|
||||
|
||||
self.simRecv = () => (ring ? ring.pop() : undefined);
|
||||
self.simPending = () => (ring ? ring.count() : 0);
|
||||
self.simTx = (u8) => self.postMessage({ t: 'tx', data: u8 }, [u8.buffer]);
|
||||
self.simPixels = (u8) => self.postMessage({ t: 'px', data: u8 }, [u8.buffer]);
|
||||
self.simFlash = (path, text) =>
|
||||
self.postMessage({ t: 'flash', path: String(path), data: String(text) });
|
||||
self.simSleep = (ms) => {
|
||||
if (ms > 0 && sleepView) {
|
||||
// Nobody notifies this slot: it is a plain blocking sleep.
|
||||
Atomics.wait(sleepView, 0, 0, ms);
|
||||
}
|
||||
};
|
||||
|
||||
function log(text) {
|
||||
self.postMessage({ t: 'log', text: String(text) });
|
||||
}
|
||||
|
||||
function writeTree(FS, root, files) {
|
||||
for (const [rel, body] of Object.entries(files)) {
|
||||
const path = `${root}/${String(rel).replace(/^\/+/, '')}`;
|
||||
const dir = path.slice(0, path.lastIndexOf('/'));
|
||||
if (dir) {
|
||||
FS.mkdirTree(dir);
|
||||
}
|
||||
FS.writeFile(path, String(body));
|
||||
}
|
||||
}
|
||||
|
||||
self.onmessage = async (event) => {
|
||||
const m = event.data || {};
|
||||
if (m.t !== 'boot') {
|
||||
return;
|
||||
}
|
||||
ring = new SimRing(m.ringSab);
|
||||
sleepView = new Int32Array(m.sleepSab);
|
||||
self.postMessage({ t: 'state', state: 'loading' });
|
||||
try {
|
||||
importScripts(`${m.pyodideUrl}pyodide.js`);
|
||||
const py = await loadPyodide({
|
||||
indexURL: m.pyodideUrl,
|
||||
stdout: log,
|
||||
stderr: log,
|
||||
});
|
||||
const FS = py.FS;
|
||||
writeTree(FS, '/flash', m.files.driver);
|
||||
writeTree(FS, '/flash', m.flash);
|
||||
writeTree(FS, '/stubs', m.files.stubs);
|
||||
FS.writeFile('/boot.py', m.bootPy);
|
||||
py.globals.set('__sim_env', py.toPy(m.env));
|
||||
py.runPython('import os\nos.environ.update({str(k): str(v) for k, v in __sim_env.items()})\ndel __sim_env');
|
||||
self.postMessage({ t: 'state', state: 'running' });
|
||||
// Blocks until main.py exits (it normally never does).
|
||||
py.runPython('import runpy\nrunpy.run_path("/boot.py", run_name="__boot__")');
|
||||
self.postMessage({ t: 'exit', error: 'main.py returned', reset: false });
|
||||
} catch (err) {
|
||||
const msg = String((err && err.message) || err);
|
||||
const reset = /SystemExit:\s*75\b/.test(msg);
|
||||
if (!reset) {
|
||||
log(msg);
|
||||
}
|
||||
self.postMessage({ t: 'exit', error: reset ? 'machine.reset()' : msg, reset });
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Boot one simulated led-driver inside Pyodide (run by web/driver-worker.js).
|
||||
|
||||
The worker has already written the strip's flash into ``LED_SIM_FLASH``
|
||||
(``led-driver/src`` including ``patterns/``, plus this strip's
|
||||
``settings.json`` and ``presets.json``) and the stubs into ``LED_SIM_STUBS``.
|
||||
This then runs the real ``main.py`` as ``__main__``, as the board does at
|
||||
power-on: settings, presets, startup preset, ESP-NOW hello, main loop.
|
||||
"""
|
||||
|
||||
import gc
|
||||
import os
|
||||
import runpy
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
def boot():
|
||||
flash = os.environ.get("LED_SIM_FLASH", "/flash")
|
||||
stubs = os.environ.get("LED_SIM_STUBS", "/stubs")
|
||||
|
||||
# Stubs replace the hardware modules; the flash root plays the device's
|
||||
# "/" (cwd), where main.py, settings.json, presets.json and patterns/ live.
|
||||
for p in (flash, stubs):
|
||||
while p in sys.path:
|
||||
sys.path.remove(p)
|
||||
sys.path[:0] = [stubs, flash]
|
||||
os.chdir(flash)
|
||||
|
||||
import _simlink
|
||||
|
||||
# No threads and no event loop turns while main.py runs: sleeps block on
|
||||
# Atomics.wait, and the ping-reply "thread" runs from the main loop.
|
||||
time.sleep = _simlink.real_sleep
|
||||
import _thread
|
||||
|
||||
_thread.start_new_thread = _simlink.start_new_thread
|
||||
|
||||
if not hasattr(gc, "mem_free"):
|
||||
gc.mem_free = lambda: 256 * 1024
|
||||
gc.mem_alloc = lambda: 64 * 1024
|
||||
|
||||
import settings as led_settings
|
||||
|
||||
led_settings.Settings.SETTINGS_FILE = flash.rstrip("/") + "/settings.json"
|
||||
|
||||
runpy.run_path(flash.rstrip("/") + "/main.py", run_name="__main__")
|
||||
|
||||
|
||||
boot()
|
||||
@@ -0,0 +1,71 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="theme-color" content="#0e0f12">
|
||||
<title>LED Rig Simulator</title>
|
||||
<link rel="icon" href="data:,">
|
||||
<link rel="stylesheet" href="/web/styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<span class="brand-mark" aria-hidden="true"></span>
|
||||
<span class="brand-name">led-simulator</span>
|
||||
</div>
|
||||
<div class="chips">
|
||||
<span class="chip" id="bridge-chip" title="Simulated Wi-Fi bridge">bridge</span>
|
||||
<span class="chip" id="controller-chip">controller: –</span>
|
||||
<span class="chip" id="strips-chip">strips: –</span>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button type="button" id="power-on-all">Power on all</button>
|
||||
<button type="button" id="power-cycle-all">Power cycle all</button>
|
||||
<button type="button" id="power-off-all" class="secondary">Power off all</button>
|
||||
<label class="toggle" title="Boot every strip when this page opens">
|
||||
<input type="checkbox" id="auto-power"> Power on when opened
|
||||
</label>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="banner" class="banner" hidden></div>
|
||||
|
||||
<main class="stage">
|
||||
<div class="rig" id="rig">
|
||||
<canvas id="rig-canvas" aria-label="LED rig"></canvas>
|
||||
</div>
|
||||
|
||||
<aside class="drawer" id="drawer" hidden aria-label="Strip details">
|
||||
<div class="drawer-head">
|
||||
<div>
|
||||
<div class="drawer-title" id="d-name">sim-01</div>
|
||||
<div class="drawer-sub" id="d-meta">02:51:4d:00:00:01</div>
|
||||
</div>
|
||||
<button type="button" class="icon" id="d-close" aria-label="Close">×</button>
|
||||
</div>
|
||||
<dl class="facts">
|
||||
<dt>State</dt><dd id="d-state">off</dd>
|
||||
<dt>Position</dt><dd id="d-pos">–</dd>
|
||||
<dt>Packets</dt><dd id="d-packets">–</dd>
|
||||
</dl>
|
||||
<div class="drawer-actions">
|
||||
<button type="button" id="d-on">Power on</button>
|
||||
<button type="button" id="d-reset">Reset</button>
|
||||
<button type="button" id="d-off" class="secondary">Power off</button>
|
||||
</div>
|
||||
<div class="log-head">
|
||||
<span>Serial</span>
|
||||
<button type="button" class="link" id="d-clear">clear</button>
|
||||
</div>
|
||||
<pre class="log" id="d-log"></pre>
|
||||
</aside>
|
||||
</main>
|
||||
|
||||
<footer class="hint" id="hint">Loading…</footer>
|
||||
|
||||
<script src="/web/ring.js"></script>
|
||||
<script src="/web/layout.js"></script>
|
||||
<script src="/web/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,103 @@
|
||||
/* Rig geometry for the canvas: strips along their rows, pixel 0 at the
|
||||
* strip's start end (next to the centre line for start: "center").
|
||||
* Strip placement (row, col, reversed) comes from the server (layout.py).
|
||||
*/
|
||||
(function (g) {
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @param {object} layout {rows, columns, leds_per_strip}
|
||||
* @param {Array} strips [{row, col, leds, reversed}]
|
||||
* @returns {object} {ledPitch, ledW, ledH, strips:[{x0, y, w, labelX, labelY, labelAlign}], centreLines}
|
||||
*/
|
||||
function computeGeometry(layout, strips, width, height, opts = {}) {
|
||||
const margin = opts.margin ?? 16;
|
||||
const colGap = opts.colGap ?? 32;
|
||||
const labelH = opts.labelH ?? 16;
|
||||
const rows = layout.rows;
|
||||
const cols = layout.columns;
|
||||
const n = layout.leds_per_strip;
|
||||
const usableW = Math.max(cols * n, width - 2 * margin - (cols - 1) * colGap);
|
||||
const colW = usableW / cols;
|
||||
const pitch = colW / n;
|
||||
const rowH = Math.max(labelH + 6, (height - 2 * margin) / rows);
|
||||
const ledH = Math.max(6, Math.min(rowH - labelH - 10, 18));
|
||||
const gap = pitch >= 3 ? 1 : 0;
|
||||
const ledW = Math.max(1, pitch - gap);
|
||||
|
||||
const out = strips.map((s) => {
|
||||
const x0 = margin + s.col * (colW + colGap);
|
||||
const yTop = margin + s.row * rowH;
|
||||
// strip sits just under its label; leftover row space goes below it
|
||||
const y = yTop + labelH + 4;
|
||||
return {
|
||||
x0,
|
||||
y,
|
||||
w: colW,
|
||||
h: ledH,
|
||||
top: yTop,
|
||||
rowH,
|
||||
reversed: Boolean(s.reversed),
|
||||
labelX: s.reversed ? x0 + colW : x0,
|
||||
labelY: yTop + labelH / 2 + 2,
|
||||
labelAlign: s.reversed ? 'right' : 'left',
|
||||
};
|
||||
});
|
||||
const centreLines = [];
|
||||
for (let c = 1; c < cols; c += 1) {
|
||||
centreLines.push(margin + c * (colW + colGap) - colGap / 2);
|
||||
}
|
||||
return { ledPitch: pitch, ledW, ledH, strips: out, centreLines };
|
||||
}
|
||||
|
||||
/**
|
||||
* Geometry from each strip's rig place [x0, y0, x1, y1] (y up, centre 0, as the controller sends it),
|
||||
* fitted to the canvas with one scale. Used once every strip has a place.
|
||||
* @returns {object} {placed: true, ledH, strips: [{ax, ay, bx, by, ang, len, pitch, labelX, labelY}], centre}
|
||||
*/
|
||||
function computePlaced(strips, width, height, opts = {}) {
|
||||
const margin = opts.margin ?? 28;
|
||||
const ledH = opts.ledH ?? 12;
|
||||
let lo = [Infinity, Infinity];
|
||||
let hi = [-Infinity, -Infinity];
|
||||
for (const s of strips) {
|
||||
const p = s.place;
|
||||
for (let k = 0; k < 4; k += 2) {
|
||||
lo = [Math.min(lo[0], p[k]), Math.min(lo[1], p[k + 1])];
|
||||
hi = [Math.max(hi[0], p[k]), Math.max(hi[1], p[k + 1])];
|
||||
}
|
||||
}
|
||||
const spanX = Math.max(hi[0] - lo[0], 1e-3);
|
||||
const spanY = Math.max(hi[1] - lo[1], 1e-3);
|
||||
const scale = Math.min((width - 2 * margin) / spanX, (height - 2 * margin) / spanY);
|
||||
const ox = width / 2 - ((lo[0] + hi[0]) / 2) * scale;
|
||||
const oy = height / 2 + ((lo[1] + hi[1]) / 2) * scale;
|
||||
const tx = (x) => ox + x * scale;
|
||||
const ty = (y) => oy - y * scale;
|
||||
const out = strips.map((s) => {
|
||||
const [x0, y0, x1, y1] = s.place;
|
||||
const ax = tx(x0);
|
||||
const ay = ty(y0);
|
||||
const bx = tx(x1);
|
||||
const by = ty(y1);
|
||||
const len = Math.hypot(bx - ax, by - ay);
|
||||
const n = s.leds;
|
||||
return {
|
||||
ax, ay, bx, by, len,
|
||||
ang: Math.atan2(by - ay, bx - ax),
|
||||
pitch: len / n,
|
||||
labelX: (ax + bx) / 2,
|
||||
labelY: (ay + by) / 2 - ledH / 2 - 9,
|
||||
};
|
||||
});
|
||||
return { placed: true, ledH, strips: out, centre: { x: tx(0), y: ty(0) } };
|
||||
}
|
||||
|
||||
/** x of pixel i of a strip (pixel 0 at the start end). */
|
||||
function pixelX(geo, sg, i, leds) {
|
||||
const pos = sg.reversed ? leds - 1 - i : i;
|
||||
return sg.x0 + pos * geo.ledPitch;
|
||||
}
|
||||
|
||||
g.RigLayout = { computeGeometry, computePlaced, pixelX };
|
||||
})(typeof self !== 'undefined' ? self : globalThis);
|
||||
@@ -0,0 +1,93 @@
|
||||
/* SharedArrayBuffer message ring: the page pushes received ESP-NOW frames,
|
||||
* the driver worker pops them while main.py runs (it never yields to the JS
|
||||
* event loop, so postMessage cannot reach it).
|
||||
*
|
||||
* Layout: Int32[4] header {head, tail, dropped, count} then `capacity` bytes.
|
||||
* Each message is a little-endian u16 length followed by the bytes.
|
||||
* One producer (page) and one consumer (worker).
|
||||
*
|
||||
* Loaded as a classic script by both the page and the worker.
|
||||
*/
|
||||
(function (g) {
|
||||
'use strict';
|
||||
const HEADER = 16;
|
||||
const HEAD = 0;
|
||||
const TAIL = 1;
|
||||
const DROPPED = 2;
|
||||
const COUNT = 3;
|
||||
|
||||
class SimRing {
|
||||
constructor(sab) {
|
||||
this.sab = sab;
|
||||
this.idx = new Int32Array(sab, 0, 4);
|
||||
this.cap = sab.byteLength - HEADER;
|
||||
this.data = new Uint8Array(sab, HEADER, this.cap);
|
||||
}
|
||||
|
||||
static create(capacity = 65536) {
|
||||
return new SimRing(new SharedArrayBuffer(HEADER + capacity));
|
||||
}
|
||||
|
||||
used() {
|
||||
const h = Atomics.load(this.idx, HEAD);
|
||||
const t = Atomics.load(this.idx, TAIL);
|
||||
return (h - t + this.cap) % this.cap;
|
||||
}
|
||||
|
||||
count() {
|
||||
return Atomics.load(this.idx, COUNT);
|
||||
}
|
||||
|
||||
dropped() {
|
||||
return Atomics.load(this.idx, DROPPED);
|
||||
}
|
||||
|
||||
/** Producer: false (and counted as dropped) when the ring is full. */
|
||||
push(bytes) {
|
||||
const n = bytes.length;
|
||||
if (n > 0xffff || n + 2 >= this.cap - this.used()) {
|
||||
Atomics.add(this.idx, DROPPED, 1);
|
||||
return false;
|
||||
}
|
||||
const cap = this.cap;
|
||||
const data = this.data;
|
||||
let h = Atomics.load(this.idx, HEAD);
|
||||
data[h] = n & 0xff;
|
||||
h = (h + 1) % cap;
|
||||
data[h] = n >> 8;
|
||||
h = (h + 1) % cap;
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
data[h] = bytes[i];
|
||||
h = (h + 1) % cap;
|
||||
}
|
||||
Atomics.store(this.idx, HEAD, h);
|
||||
Atomics.add(this.idx, COUNT, 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Consumer: next message as a Uint8Array, or undefined when empty. */
|
||||
pop() {
|
||||
let t = Atomics.load(this.idx, TAIL);
|
||||
if (t === Atomics.load(this.idx, HEAD)) {
|
||||
return undefined;
|
||||
}
|
||||
const cap = this.cap;
|
||||
const data = this.data;
|
||||
const lo = data[t];
|
||||
t = (t + 1) % cap;
|
||||
const hi = data[t];
|
||||
t = (t + 1) % cap;
|
||||
const n = lo | (hi << 8);
|
||||
const out = new Uint8Array(n);
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
out[i] = data[t];
|
||||
t = (t + 1) % cap;
|
||||
}
|
||||
Atomics.store(this.idx, TAIL, t);
|
||||
Atomics.sub(this.idx, COUNT, 1);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
g.SimRing = SimRing;
|
||||
})(typeof self !== 'undefined' ? self : globalThis);
|
||||
@@ -0,0 +1,169 @@
|
||||
:root {
|
||||
--bg: #0e0f12;
|
||||
--panel: #15171c;
|
||||
--panel-2: #1b1e24;
|
||||
--line: #2a2e36;
|
||||
--text: #d6dae2;
|
||||
--muted: #8a909c;
|
||||
--accent: #5aa9ff;
|
||||
--ok: #3ecf8e;
|
||||
--warn: #f2b84b;
|
||||
--bad: #ff6b6b;
|
||||
--off: #4b505b;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html, body {
|
||||
margin: 0;
|
||||
height: 100%;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 13px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
button {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: #253041;
|
||||
border: 1px solid #34465f;
|
||||
border-radius: 6px;
|
||||
padding: 5px 11px;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:hover:not(:disabled) { background: #2d3b50; }
|
||||
button:disabled { opacity: .45; cursor: default; }
|
||||
button.secondary { background: var(--panel-2); border-color: var(--line); }
|
||||
button.secondary:hover:not(:disabled) { background: #232730; }
|
||||
button.icon {
|
||||
background: none; border: none; font-size: 20px; line-height: 1;
|
||||
padding: 0 4px; color: var(--muted);
|
||||
}
|
||||
button.link {
|
||||
background: none; border: none; padding: 0; color: var(--muted);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px 18px;
|
||||
padding: 10px 16px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: var(--panel);
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: 8px; font-weight: 600; }
|
||||
.brand-mark {
|
||||
width: 14px; height: 14px; border-radius: 3px;
|
||||
background: linear-gradient(90deg, #ff3b3b, #ffd23b, #3bff8a, #3bb2ff, #b03bff);
|
||||
}
|
||||
.chips { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.chip {
|
||||
border: 1px solid var(--line);
|
||||
background: var(--panel-2);
|
||||
border-radius: 999px;
|
||||
padding: 2px 10px;
|
||||
color: var(--muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.chip.ok { color: var(--ok); border-color: #22533f; }
|
||||
.chip.warn { color: var(--warn); border-color: #5a4720; }
|
||||
.actions { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-left: auto; }
|
||||
.toggle { display: flex; align-items: center; gap: 5px; color: var(--muted); margin-left: 6px; }
|
||||
|
||||
.banner {
|
||||
padding: 8px 16px;
|
||||
background: #3a1d22;
|
||||
color: #ffd6d6;
|
||||
border-bottom: 1px solid #5c2a31;
|
||||
}
|
||||
.banner.info { background: #1d2a3a; color: #d6e8ff; border-color: #2a405c; }
|
||||
|
||||
.stage {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
min-height: 0;
|
||||
}
|
||||
.rig {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
min-height: 360px;
|
||||
}
|
||||
.rig canvas {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.drawer {
|
||||
width: 360px;
|
||||
max-width: 100%;
|
||||
border-left: 1px solid var(--line);
|
||||
background: var(--panel);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 12px 14px;
|
||||
gap: 10px;
|
||||
min-height: 0;
|
||||
}
|
||||
.drawer[hidden] { display: none; }
|
||||
.drawer-head { display: flex; justify-content: space-between; align-items: flex-start; }
|
||||
.drawer-title { font-size: 16px; font-weight: 600; }
|
||||
.drawer-sub { color: var(--muted); font-family: ui-monospace, Menlo, Consolas, monospace; }
|
||||
.facts {
|
||||
display: grid;
|
||||
grid-template-columns: 80px 1fr;
|
||||
gap: 4px 10px;
|
||||
margin: 0;
|
||||
}
|
||||
.facts dt { color: var(--muted); }
|
||||
.facts dd { margin: 0; }
|
||||
.drawer-actions { display: flex; gap: 6px; flex-wrap: wrap; }
|
||||
.log-head { display: flex; justify-content: space-between; color: var(--muted); }
|
||||
.log {
|
||||
flex: 1;
|
||||
min-height: 120px;
|
||||
margin: 0;
|
||||
overflow: auto;
|
||||
background: #0b0c0f;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
font: 11px/1.45 ui-monospace, Menlo, Consolas, monospace;
|
||||
color: #b9c0cc;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.state-off { color: var(--off); }
|
||||
.state-queued, .state-loading { color: var(--warn); }
|
||||
.state-running { color: var(--ok); }
|
||||
.state-crashed { color: var(--bad); }
|
||||
|
||||
.hint {
|
||||
padding: 8px 16px;
|
||||
border-top: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
background: var(--panel);
|
||||
}
|
||||
.hint code {
|
||||
color: var(--text);
|
||||
font-family: ui-monospace, Menlo, Consolas, monospace;
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.stage { flex-direction: column; }
|
||||
.drawer { width: auto; border-left: none; border-top: 1px solid var(--line); max-height: 50vh; }
|
||||
.actions { margin-left: 0; }
|
||||
}
|
||||
Reference in new issue
Block a user