feat: control several drivers from one web UI

- Device dropdown: All devices, this device by name, then drivers found by
  mDNS (tagged app=led-strip) and any added by hand.
- POST /api/relay: a driver calls another driver's API for the page, so the
  browser only talks to its own board. Limited to /api/*, /ota and /reboot.
- All devices sends brightness and preset plays to every device.
- Settings: sync this device's presets, order and startup to the others.
- CORS for LAN and localhost origins, and an OPTIONS handler for /ota.
- Header labels are removed; the controls keep aria-labels.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Haiku 5.5 committed 2026-11-11 02:48:48 +13:00
1 parent 4b623bb156
commit d32f3d69cf
8 files changed
+525 -11

No files matched your search

+215 -6
View File
@@ -3,13 +3,61 @@
const $ = (id) => document.getElementById(id);
const MAX_COLOURS = 8;
// The device being controlled: '' is this device, otherwise another driver's address (e.g. 10.1.1.50).
const DEVICES_KEY = 'led-driver-devices';
const HOST_RE = /^[A-Za-z0-9.-]+(:\d{1,5})?$/;
let base = '';
// Selecting ALL sends the changes below to every device at once; reads show this device.
const ALL = '*';
const ALL_WRITES = ['/api/brightness', '/api/presets/select'];
async function api(path, opts) {
if (base === ALL) return fanOut(path, opts);
if (base) return relayTo(base, path, opts);
return direct(path, opts);
}
// This device's own API
async function direct(path, opts) {
const r = await fetch(path, opts);
const j = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(j.error || r.statusText);
return j;
}
// Another device: this driver makes the call (POST /api/relay), so the browser only talks to this one.
async function relayTo(host, path, opts) {
const method = (opts && opts.method) || 'GET';
const body = opts && typeof opts.body === 'string' ? opts.body : '';
const r = await fetch('/api/relay', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ host, method, path, body }),
});
const env = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(env.error || r.statusText);
let j = {};
try { j = JSON.parse(env.body || '{}'); } catch (_) { j = {}; }
if (env.status < 200 || env.status >= 300) throw new Error(j.error || 'HTTP ' + env.status);
return j;
}
// All devices: the same change goes to every device at once. Reads come from this device.
async function fanOut(path, opts) {
const method = (opts && opts.method) || 'GET';
if (method === 'GET') return direct(path, opts);
if (!ALL_WRITES.includes(path)) {
throw new Error('Choose one device to change this. "All devices" only sets brightness and plays presets.');
}
const hosts = ['', ...deviceChoices().map(([h]) => h)];
const results = await Promise.allSettled(hosts.map((h) => (h ? relayTo(h, path, opts) : direct(path, opts))));
const failed = results.filter((r) => r.status === 'rejected');
if (failed.length) {
throw new Error(`${failed.length} of ${hosts.length} devices failed: ${failed[0].reason.message}`);
}
return results[0].value;
}
const post = (path, body) => api(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -675,6 +723,10 @@
$('fwMsg').textContent = 'Choose a .bin file first';
return;
}
if (base) {
$('fwMsg').textContent = 'Firmware files are too large to relay. Open the device’s own address to update it.';
return;
}
if (!confirm(`Update to ${file.name} (${file.size} bytes)? The driver reboots afterwards.`)) return;
$('fwUpload').disabled = true;
$('fwMsg').textContent = 'Uploading…';
@@ -835,6 +887,165 @@
// ---- tabs and start-up ------------------------------------------------------------------------
// On phones the header menu is collapsed behind the ☰ button
// ---- other devices: one page, many drivers ----------------------------------------------------
function loadDevices() {
try {
const list = JSON.parse(localStorage.getItem(DEVICES_KEY) || '[]');
return Array.isArray(list) ? list.filter((h) => typeof h === 'string' && HOST_RE.test(h)) : [];
} catch (_) { return []; }
}
function saveDevices(list) {
try { localStorage.setItem(DEVICES_KEY, JSON.stringify(list)); } catch (_) { /* ignore */ }
}
function refreshAll() {
loadStatus().catch((e) => { $('status').textContent = e.message; });
loadPresets().catch((e) => { $('status').textContent = e.message; });
loadWifi().catch(() => {});
loadNetwork().catch(() => {});
loadHardware().catch(() => {});
loadFirmware().catch((e) => { $('fwInfo').textContent = e.message; });
}
// LED drivers found on the network by mDNS, from this device's /api/devices
let found = [];
let localName = ''; // this device's name (its hostname), shown in the dropdown
// The dropdown: This device, every driver found on the network, and any added by hand.
function deviceChoices() {
const here = location.hostname;
const seen = new Set();
const out = [];
const add = (host, label) => {
if (!host || host === here || seen.has(host)) return;
seen.add(host);
out.push([host, label]);
};
found.filter((d) => d.ip !== here).forEach((d) => add(d.host, d.name));
loadDevices().forEach((h) => add(h, h));
// A device that drops off the network stays selected rather than vanishing from the list
if (base && base !== ALL && !seen.has(base)) out.push([base, base]);
return out;
}
async function discoverDevices() {
try {
// Both asked of this device, which is the one the page came from
const [dr, sr] = await Promise.all([fetch('/api/devices'), fetch('/api/status')]);
const j = await dr.json();
const st = await sr.json();
const next = Array.isArray(j.devices) ? j.devices.filter((d) => d && d.host) : [];
const name = typeof st.hostname === 'string' ? st.hostname : '';
if (JSON.stringify(next) !== JSON.stringify(found) || name !== localName) {
found = next;
localName = name;
renderDevices();
}
} catch (_) { /* keep the list we have */ }
}
function renderDevices() {
const list = loadDevices();
const sel = $('deviceSelect');
sel.textContent = '';
const choices = deviceChoices();
// All devices first, then this device by its name, then the others
const top = choices.length ? [[ALL, 'All devices']] : [];
[...top, ['', localName || 'This device'], ...choices].forEach(([value, label]) => {
const opt = document.createElement('option');
opt.value = value;
opt.textContent = label;
sel.appendChild(opt);
});
sel.value = base;
const box = $('devList');
box.textContent = '';
list.forEach((h) => {
const li = document.createElement('li');
const name = document.createElement('span');
name.textContent = h;
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'btn-secondary';
remove.textContent = 'Remove';
remove.addEventListener('click', () => removeDevice(h));
li.append(name, remove);
box.appendChild(li);
});
}
function selectDevice(host) {
if (host === base) return;
base = host;
closeEditor();
$('status').textContent = host === ALL ? `Controlling all ${deviceChoices().length + 1} devices` : '';
renderDevices();
refreshAll();
}
function removeDevice(host) {
saveDevices(loadDevices().filter((h) => h !== host));
if (base === host) base = '';
renderDevices();
refreshAll();
}
// ---- sync presets: this device is the master -------------------------------------------------
async function syncPresets() {
const msg = $('syncMsg');
const slaves = deviceChoices().map(([h]) => h);
if (!slaves.length) {
msg.textContent = 'No other devices found. Add one, or wait for discovery.';
return;
}
if (!confirm(`Copy this device's presets to ${slaves.length} other device(s)? Same-name presets are replaced.`)) return;
msg.textContent = 'Syncing…';
const master = await direct('/api/presets'); // always this device, even when another device is selected
const presets = master.presets || [];
const names = presets.map((p) => p.name);
const failed = [];
for (const host of slaves) {
try {
for (const p of presets) {
await relayTo(host, '/api/presets', { method: 'POST', body: JSON.stringify(p) });
}
await relayTo(host, '/api/presets/order', { method: 'POST', body: JSON.stringify({ names }) });
await relayTo(host, '/api/presets/startup', { method: 'POST', body: JSON.stringify({ name: master.startup || '' }) });
} catch (e) {
failed.push(`${host}: ${e.message}`);
}
}
msg.textContent = failed.length
? `Failed on ${failed.length} of ${slaves.length}. ${failed.join('; ')}`
: `Synced ${presets.length} preset(s) to ${slaves.length} device(s).`;
if (base) refreshAll(); // the presets list may have changed on the device being viewed
}
$('syncPresets').addEventListener('click', () => {
syncPresets().catch((e) => { $('syncMsg').textContent = e.message; });
});
$('deviceSelect').addEventListener('change', () => selectDevice($('deviceSelect').value));
$('devAdd').addEventListener('submit', (ev) => {
ev.preventDefault();
const host = $('devHost').value.trim().replace(/^https?:\/\//, '').replace(/\/+$/, '');
if (!HOST_RE.test(host)) {
$('devMsg').textContent = 'Enter an address such as 10.1.1.50 or led-desk.local.';
return;
}
const list = loadDevices();
if (!list.includes(host)) list.push(host);
saveDevices(list);
$('devHost').value = '';
$('devMsg').textContent = '';
base = host;
renderDevices();
refreshAll();
});
const header = document.querySelector('header');
const menuToggle = $('menuToggle');
const setMenu = (open) => {
@@ -891,12 +1102,10 @@
renderColours();
updateOutputs();
loadStatus().catch((e) => { $('status').textContent = e.message; });
loadPresets().catch((e) => { $('status').textContent = e.message; });
loadWifi().catch(() => {});
loadNetwork().catch(() => {});
loadHardware().catch(() => {});
loadFirmware().catch((e) => { $('fwInfo').textContent = e.message; });
renderDevices();
refreshAll();
discoverDevices();
setInterval(discoverDevices, 60000);
setInterval(() => {
loadStatus().catch(() => {});
loadPresets().catch(() => {});
+22 -3
View File
@@ -17,10 +17,13 @@
<button class="tab" data-tab="settings">Settings</button>
<button id="modeToggle" type="button" class="mode-toggle" aria-pressed="false">Edit mode</button>
<button id="newPreset" type="button" class="tab-action" hidden>+ New preset</button>
<label class="header-bright">Brightness
<input type="range" id="globalBright" min="0" max="255" step="1">
<div class="header-device">
<select id="deviceSelect" aria-label="Device"></select>
</div>
<div class="header-bright">
<input type="range" id="globalBright" min="0" max="255" step="1" aria-label="Brightness">
<output id="globalOut"></output>
</label>
</div>
</nav>
</header>
@@ -32,11 +35,27 @@
</section>
<section id="settings" hidden>
<h2>Devices</h2>
<p class="muted">Control other LED drivers from this page. Add each one by its address, such as 10.1.1.50 or led-desk.local. The list is kept in this browser.</p>
<ul id="devList" class="list"></ul>
<form id="devAdd">
<label>Address
<input id="devHost" maxlength="80" autocomplete="off" placeholder="10.1.1.50">
</label>
<button type="submit">Add device</button>
</form>
<p id="devMsg" class="muted" role="status"></p>
<h2>Presets</h2>
<p class="muted">Adds the default presets (Rainbow, Chase, Aurora, Candle, Twinkle, Flame, Sweep, Off) that are not in the list yet. Your own presets are kept.</p>
<button id="addDefaults" type="button">Add default presets</button>
<p id="defaultsMsg" class="muted" role="status"></p>
<h2>Sync presets</h2>
<p class="muted">Copy this device's presets, their order and its startup preset to every other device. A preset with the same name is replaced. Presets that only the other devices have are kept.</p>
<button id="syncPresets" type="button">Sync presets to other devices</button>
<p id="syncMsg" class="muted" role="status"></p>
<h2>LED strip</h2>
<form id="hwForm">
<label>Number of LEDs
+1
View File
@@ -278,6 +278,7 @@ button.preset-tile.active {
outline-offset: 2px;
}
.header-device,
.header-bright {
flex-direction: row;
align-items: center;