Files
led-driver/web/app.js
T
jimmyandClaude Haiku 5.5 9a04d28ecf feat: web UI with AP, Wi-Fi client, mDNS, presets, OTA and DDP
- Wi-Fi access point led-XXXXXX plus a client network, configurable
  mDNS name and static client address
- Preset tiles with an editor, drag to reorder, default presets,
  global brightness, Run and Edit modes, collapsible menu on phones
- 35 patterns ported from led-driver, up to 512 LEDs, colour order,
  max brightness and data pin settings
- Over-the-air updates (POST /ota) with rollback, and a CLI in tools/ota.py
- DDP receiver on UDP 4048 with tools/ddp_test.py
- LED refresh every 10 ms; lwIP sockets raised to 16 so mDNS, HTTP
  and DDP can run together

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 01:54:32 +13:00

905 lines
33 KiB
JavaScript

// LED strip web UI. Talks to the JSON API in main/web.cpp.
(() => {
const $ = (id) => document.getElementById(id);
const MAX_COLOURS = 8;
async function api(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;
}
const post = (path, body) => api(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const toHex = (rgb) => '#' + rgb.map((v) => v.toString(16).padStart(2, '0')).join('');
const fromHex = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));
let colours = ['#ff0000'];
let presetState = { presets: [], selected: '', startup: '' };
let loadedName = ''; // the preset open in the editor ('' for a new one)
// ---- the editor (a child window) ------------------------------------------------------------
function renderColours() {
const box = $('colours');
box.textContent = '';
colours.forEach((hex, i) => {
const input = document.createElement('input');
input.type = 'color';
input.value = hex;
input.title = 'Colour ' + (i + 1);
input.addEventListener('input', () => { colours[i] = input.value; });
box.appendChild(input);
});
$('addColour').disabled = colours.length >= MAX_COLOURS;
$('removeColour').disabled = colours.length <= 1;
}
function updateOutputs() {
$('delayOut').textContent = $('delay').value + ' ms';
$('brightOut').textContent = $('bright').value;
$('fadeOut').textContent = $('fade').value + ' ms';
}
// ---- the pattern-specific numbers -------------------------------------------------------------
// Which of n1-n4 each pattern reads, and what they mean (defaults are used when a number is 0).
// Patterns with styles read n6 (the style) to choose which set applies.
const F = (n, label, extra) => Object.assign({ n, label }, extra || {});
const DIR = [[0, 'Left to right'], [1, 'Right to left']];
const SPEC = {
bar_graph: [F('n1', 'Level (%)', { min: 0, max: 100, hint: 'lit share of the strip' })],
blizzard: [
F('n1', 'Density', { hint: 'flakes spawned per frame, 0-255 (default 90)' }),
F('n2', 'Speed', { hint: 'LEDs per frame (default 2)' }),
F('n3', 'Wind', { hint: '128 is no wind; below drifts one way, above the other' }),
],
candle_glow: [
F('n1', 'Candles', { hint: 'number of flames (default 4)' }),
F('n2', 'Width', { hint: 'LEDs each flame covers (default 3)' }),
F('n3', 'Flicker', { hint: 'how much each flame varies, 1-255 (default 90)' }),
],
circle: [
F('n1', 'Head speed', { hint: 'LEDs per second' }),
F('n2', 'Max length', { hint: 'LEDs before the tail starts to move' }),
F('n3', 'Tail speed', { hint: 'LEDs per second' }),
F('n4', 'Min length', { hint: '0 turns the ring off between loops' }),
],
clock_sweep: [
F('n1', 'Width', { hint: 'LEDs in the hand (default 1)' }),
F('n2', 'Marker every', { hint: 'LEDs between marks; 0 for none' }),
],
colour_cycle: [F('n1', 'Step', { hint: 'how far it moves each step (default 1)' })],
field_wave: [
F('n1', 'Direction', { hint: 'degrees (0 is left to right)' }),
F('n2', 'Wavelength', { hint: 'per mille of the strip (default 1000)' }),
F('n3', 'Shape', { options: [[0, 'Linear'], [1, 'Rings'], [2, 'Swirl'], [3, 'Plasma']] }),
],
flame: [
F('n1', 'Lowest level', { hint: 'dimmest the flame gets, 0-255' }),
F('n2', 'Breath period', { hint: 'ms per breath (default 2500)' }),
F('n3', 'Spark gap (min)', { hint: 'ms; 0 with the max for the default' }),
F('n4', 'Spark gap (max)', { hint: 'ms' }),
],
flicker: [F('n1', 'Lowest brightness', { hint: '0-255; the top is the brightness' })],
gradient_wipe: [
F('n1', 'First LED', { hint: 'where the wipe starts' }),
F('n2', 'Last LED', { hint: 'where it ends' }),
],
grow: [
F('n1', 'Grows from', { options: [[0, 'Centre out'], [1, 'Edges in'], [2, 'Round the centre'], [3, 'Across']] }),
F('n2', 'Then', { options: [[0, 'Stays lit'], [1, 'Empties back'], [2, 'Empties from the start'], [3, 'Goes off']] }),
F('n3', 'Angle', { hint: 'degrees, used when growing across' }),
],
hit: [
F('n1', 'Rise', { hint: 'time to full, ms (or quarter beats)' }),
F('n2', 'Hold', { hint: 'time at full' }),
F('n3', 'Decay', { hint: 'time to fade out' }),
F('n4', 'After', { options: [[0, 'Background'], [1, 'Stays on the colour']] }),
],
icicles: [
F('n1', 'Spacing', { hint: 'LEDs between icicles (default 12)' }),
F('n2', 'Max length', { hint: 'LEDs (default 14)' }),
F('n3', 'Phase step', { hint: 'how fast they grow and shrink (default 1)' }),
],
keyframes: [
F('n1', 'Easing', { options: [[0, 'Linear'], [1, 'Ease in and out'], [2, 'Step'], [3, 'Ease in'], [4, 'Ease out']] }),
F('n2', 'When done', { options: [[0, 'Last colour'], [1, 'Background'], [2, 'Off']] }),
],
orbit: [
F('n1', 'Dots', { hint: 'number of orbiting lights (default 3)' }),
F('n2', 'Speed', { hint: 'default 1' }),
],
palette_morph: [
F('n1', 'Morph time', { hint: 'ms from one colour to the next (default 1200)' }),
F('n2', 'Warp rate', { hint: 'default 3' }),
F('n3', 'Turbulence', { hint: 'how much the colours ripple (default 24)' }),
],
plasma: [
F('n1', 'Scale', { hint: 'default 6' }),
F('n2', 'Speed', { hint: 'default 2' }),
F('n3', 'Contrast', { hint: 'default 2' }),
],
pulse: [
F('n1', 'Attack', { hint: 'ms' }),
F('n2', 'Hold', { hint: 'ms' }),
F('n3', 'Decay', { hint: 'ms' }),
],
radiate: [
F('n1', 'Node spacing', { hint: 'LEDs between nodes (default 1)' }),
F('n2', 'Outward', { hint: 'ms for the ring to travel out' }),
F('n3', 'Return', { hint: 'ms for it to come back' }),
],
rain_drops: [
F('n1', 'Rate', { hint: 'drops per frame, 0-255 (default 32)' }),
F('n2', 'Width', { hint: 'LEDs each drop covers (default 3)' }),
],
rime: [
F('n1', 'Chill', { hint: 'how often frost forms, 1-255 (default 36)' }),
F('n2', 'Melt', { hint: 'how fast it fades (default 12)' }),
F('n3', 'Sparkles', { hint: 'new spots per frame (default 3)' }),
],
ripple: [
F('n1', 'Ring width', { hint: 'per mille (default 150)' }),
F('n2', 'Rings', { hint: 'rings at once (default 1)' }),
F('n3', 'Direction', { options: [[0, 'Outward'], [1, 'Inward from the edge']] }),
F('n4', 'Fade', { hint: 'per mille of distance; 0 for none' }),
],
spin: [
F('n1', 'Arms', { hint: 'default 1' }),
F('n2', 'Arm width', { hint: 'degrees (default 20)' }),
F('n3', 'Tail', { hint: 'degrees (default 90)' }),
F('n4', 'Turn', { options: [[0, 'Anticlockwise'], [1, 'Clockwise']] }),
],
strobe_burst: [
F('n1', 'Flashes', { hint: 'per burst (default 3)' }),
F('n2', 'Gap', { hint: 'ms between flashes (default 60)' }),
F('n3', 'Cooldown', { hint: 'ms between bursts (default 400)' }),
],
sweep: [
F('n1', 'Direction', { hint: 'degrees (0 is left to right)' }),
F('n2', 'Band width', { hint: 'per mille of the strip (default 200)' }),
F('n3', 'Trail', { hint: 'per mille behind the band' }),
F('n4', 'After', { options: [[0, 'Band moves on'], [1, 'Leave lit (wipe)']] }),
],
twinkle: [
F('n1', 'Activity', { hint: '1-255 (default 48)' }),
F('n2', 'Density', { hint: '0-255 (default 128)' }),
F('n3', 'Smallest cluster', { hint: 'LEDs (default 1)' }),
F('n4', 'Largest cluster', { hint: 'LEDs (default 4)' }),
],
// Patterns with styles: n6 picks the set of fields
aurora: {
styles: ['Bands', 'Northern wave'],
fields: [
[F('n1', 'Bands', { hint: 'default 3' }), F('n2', 'Shimmer', { hint: '0-255 (default 40)' })],
[F('n1', 'Wave length', { hint: 'LEDs (default 20)' }), F('n2', 'Contrast', { hint: '1-255 (default 200)' }),
F('n3', 'Drift', { hint: 'default 2' })],
],
},
chase: {
styles: ['Chase', 'Marquee'],
fields: [
[F('n1', 'Lit LEDs', { hint: 'default 1' }), F('n2', 'Gap LEDs', { hint: 'default 1' }),
F('n3', 'Step (even beats)'), F('n4', 'Step (odd beats)')],
[F('n1', 'Lit LEDs', { hint: 'default 3' }), F('n2', 'Gap LEDs', { hint: 'default 2' }),
F('n3', 'Step', { hint: 'default 1' })],
],
},
meteor: {
styles: ['Meteor', 'Comet', 'Scanner'],
fields: [
[F('n1', 'Tail', { hint: 'LEDs (default 8)' }), F('n2', 'Speed', { hint: 'default 1' }),
F('n3', 'Fade', { hint: '1-255 (default 192)' })],
[F('n1', 'Tail', { hint: 'LEDs (default 6)' }), F('n2', 'Speed', { hint: 'default 1' }),
F('n3', 'Gap', { hint: 'LEDs between the two (default 0)' })],
[F('n1', 'Width', { hint: 'LEDs (default 4)' }), F('n2', 'End pause', { hint: 'frames at each end' })],
],
},
particles: {
styles: ['Snow', 'Starfall'],
fields: [
[F('n1', 'Density', { hint: '0-255 (default 20)' }), F('n2', 'Speed', { hint: 'default 1' })],
[F('n1', 'Spawn rate', { hint: '1-255 (default 14)' }), F('n2', 'Speed', { hint: 'default 2' }),
F('n3', 'Tail', { hint: 'LEDs (default 10)' })],
],
},
sparkle: {
styles: ['Trail', 'Ice', 'Fireflies'],
fields: [
[F('n1', 'Density', { hint: '0-255 (default 24)' }), F('n2', 'Decay', { hint: '1-255 (default 210)' })],
[F('n1', 'Rate', { hint: '1-255 (default 55)' }), F('n2', 'Decay', { hint: '1-255 (default 140)' }),
F('n3', 'Halo', { hint: '0-3 LEDs' })],
[F('n1', 'Fireflies', { hint: 'default 6' }), F('n2', 'Speed', { hint: 'default 8' })],
],
},
};
// colour_cycle has a style too: gradient (0) or rainbow (1), both using the step
SPEC.colour_cycle = {
styles: ['Gradient', 'Rainbow'],
fields: [[F('n1', 'Step', { hint: 'default 1' })], [F('n1', 'Step', { hint: 'default 1' })]],
};
// The fields a pattern uses for a style: [] when it has none
function fieldsFor(name, style) {
const spec = SPEC[name];
if (!spec) return [];
if (Array.isArray(spec)) return spec;
return spec.fields[style] || spec.fields[0] || [];
}
function stylesFor(name) {
const spec = SPEC[name];
return spec && !Array.isArray(spec) ? spec.styles : null;
}
// The current numbers, by key (n1..n4) and the style (n6)
let nums = { n1: 0, n2: 0, n3: 0, n4: 0 };
function renderPatternFields() {
const name = $('pattern').value;
const styles = stylesFor(name);
const styleSel = $('style');
if (styles) {
if (styleSel.options.length !== styles.length) {
styleSel.textContent = '';
styles.forEach((label, i) => styleSel.add(new Option(label, i)));
}
$('styleRow').hidden = false;
} else {
styleSel.textContent = '';
styleSel.add(new Option('—', 0));
$('styleRow').hidden = true;
}
const style = styles ? Number(styleSel.value) || 0 : 0;
const box = $('numbers');
box.textContent = '';
fieldsFor(name, style).forEach((f) => {
const label = document.createElement('label');
label.textContent = f.label;
let input;
if (f.options) {
input = document.createElement('select');
f.options.forEach(([v, text]) => input.add(new Option(text, v)));
input.value = nums[f.n] ?? 0;
if (!f.options.some(([v]) => v === Number(input.value))) input.value = f.options[0][0];
} else {
input = document.createElement('input');
input.type = 'number';
input.min = f.min ?? 0;
if (f.max !== undefined) input.max = f.max;
input.step = 1;
input.value = nums[f.n] ?? 0;
}
input.addEventListener('input', () => { nums[f.n] = Number(input.value) || 0; });
input.addEventListener('change', () => { nums[f.n] = Number(input.value) || 0; });
label.appendChild(input);
if (f.hint) {
const hint = document.createElement('span');
hint.className = 'muted';
hint.textContent = f.hint;
label.appendChild(hint);
}
box.appendChild(label);
});
if (!fieldsFor(name, style).length) {
const none = document.createElement('p');
none.className = 'muted';
none.textContent = 'This pattern has no extra settings.';
box.appendChild(none);
}
}
// Load the numbers and style of a preset into the editor
function setNumbers(p) {
nums = { n1: p.n1 || 0, n2: p.n2 || 0, n3: p.n3 || 0, n4: p.n4 || 0 };
const styles = stylesFor(p.pattern);
$('style').textContent = '';
if (styles) {
styles.forEach((label, i) => $('style').add(new Option(label, i)));
$('style').value = p.mode || 0;
}
renderPatternFields();
}
// The editor's fields as a preset
function gather() {
return {
pattern: $('pattern').value,
colors: colours.map(fromHex),
background: fromHex($('bg').value),
delay: Number($('delay').value),
brightness: Number($('bright').value),
fade: Number($('fade').value),
auto: $('auto').checked,
reverse: $('reverse').checked,
beat_time: $('beatTime').checked,
n1: nums.n1,
n2: nums.n2,
n3: nums.n3,
n4: nums.n4,
mode: stylesFor($('pattern').value) ? Number($('style').value) || 0 : 0,
};
}
// Fill the editor from a preset
function fillEditor(p) {
if (p.pattern !== undefined) $('pattern').value = p.pattern;
colours = (p.colors && p.colors.length ? p.colors : [[255, 255, 255]]).map(toHex);
renderColours();
$('bg').value = toHex(p.background || [0, 0, 0]);
$('delay').value = p.delay;
$('bright').value = p.brightness;
$('fade').value = p.fade || 0;
$('auto').checked = !!p.auto;
$('reverse').checked = !!p.reverse;
$('beatTime').checked = !!p.beat_time;
setNumbers(p);
updateOutputs();
}
function editorMsg(text) {
$('presetMsg').textContent = text;
}
// Open the child window: an existing preset, or a new one (null)
function openEditor(p) {
if (p) {
fillEditor(p);
$('presetName').value = p.name;
loadedName = p.name;
$('editor-title').textContent = 'Edit ' + p.name;
} else {
fillEditor({
pattern: 'chase', colors: [[255, 0, 0]], background: [0, 0, 0],
delay: 1000, brightness: 16, auto: true,
});
$('presetName').value = '';
loadedName = '';
$('editor-title').textContent = 'New preset';
}
refreshEditorButtons();
editorMsg('');
$('editor-modal').hidden = false;
$('presetName').focus();
}
function closeEditor() {
$('editor-modal').hidden = true;
}
function refreshEditorButtons() {
const exists = presetState.presets.some((p) => p.name === loadedName);
$('presetStartup').disabled = !exists;
$('presetDelete').disabled = !exists;
$('presetStartup').textContent = exists && presetState.startup === loadedName
? 'Clear startup' : 'Use at startup';
}
$('editorClose').addEventListener('click', closeEditor);
$('editor-modal').addEventListener('click', (ev) => {
if (ev.target === $('editor-modal')) closeEditor();
});
document.addEventListener('keydown', (ev) => {
if (ev.key === 'Escape' && !$('editor-modal').hidden) closeEditor();
});
$('apply').addEventListener('click', async () => {
try {
await post('/api/pattern', gather());
editorMsg('Applied to the strip (not saved)');
await loadStatus();
} catch (e) {
editorMsg(e.message);
}
});
$('presetSave').addEventListener('click', async () => {
const name = $('presetName').value.trim();
if (!name) {
editorMsg('Give the preset a name');
return;
}
try {
await post('/api/presets', Object.assign(gather(), { name }));
await post('/api/presets/select', { name });
loadedName = name;
await loadPresets();
await loadStatus();
closeEditor();
} catch (e) {
editorMsg(e.message);
}
});
$('presetStartup').addEventListener('click', async () => {
const name = presetState.startup === loadedName ? '' : loadedName;
try {
await post('/api/presets/startup', { name });
await loadPresets();
refreshEditorButtons();
editorMsg(name ? name + ' will load at startup' : 'Startup preset cleared');
} catch (e) {
editorMsg(e.message);
}
});
$('presetDelete').addEventListener('click', async () => {
const name = loadedName;
if (!name || !confirm(`Delete preset "${name}"?`)) return;
try {
await post('/api/presets/delete', { name });
await loadPresets();
closeEditor();
} catch (e) {
editorMsg(e.message);
}
});
$('addColour').addEventListener('click', () => {
if (colours.length < MAX_COLOURS) {
colours.push(colours[colours.length - 1]);
renderColours();
}
});
$('removeColour').addEventListener('click', () => {
if (colours.length > 1) {
colours.pop();
renderColours();
}
});
['delay', 'bright', 'fade'].forEach((id) => $(id).addEventListener('input', updateOutputs));
$('pattern').addEventListener('change', () => { renderPatternFields(); });
$('style').addEventListener('change', () => { renderPatternFields(); });
// ---- the running settings ---------------------------------------------------------------------
async function loadPatterns(status) {
if ($('pattern').options.length) return;
status.patterns.forEach((name) => $('pattern').add(new Option(name, name)));
}
let globalTimer;
$('globalBright').addEventListener('input', () => {
$('globalOut').textContent = $('globalBright').value;
clearTimeout(globalTimer);
globalTimer = setTimeout(() => {
post('/api/brightness', { brightness: Number($('globalBright').value) }).catch((e) => {
$('status').textContent = e.message;
});
}, 150);
});
async function loadStatus() {
const s = await api('/api/status');
if (document.activeElement !== $('globalBright')) {
$('globalBright').value = s.global_brightness;
$('globalOut').textContent = s.global_brightness;
}
$('apName').textContent = s.ap_ssid;
$('staState').textContent = s.sta_connected ? 'connected (' + s.sta_ip + ')' : 'not connected';
await loadPatterns(s);
}
// ---- preset buttons on the front --------------------------------------------------------------
// Drag to reorder. Mouse: move 8 px to start. Touch: hold a moment, so scrolling still works.
let dragging = false; // a drag is in progress
let dragRow = null;
let dragId = null;
let dragX = 0;
let dragY = 0;
let holdTimer = null;
let justDragged = false;
function startDrag(row) {
dragging = true;
dragRow = row;
row.classList.add('dragging');
}
function attachDrag(row) {
row.addEventListener('pointerdown', (ev) => {
if (!isEditMode()) return;
if (ev.pointerType === 'mouse' && ev.button !== 0) return;
dragId = ev.pointerId;
dragX = ev.clientX;
dragY = ev.clientY;
if (ev.pointerType !== 'mouse') {
clearTimeout(holdTimer);
holdTimer = setTimeout(() => startDrag(row), 300);
}
row.dataset.pending = '1';
});
row.addEventListener('pointerup', () => { row.dataset.pending = ''; });
}
document.addEventListener('pointermove', (ev) => {
if (ev.pointerId !== dragId) return;
if (!dragRow) {
const moved = Math.hypot(ev.clientX - dragX, ev.clientY - dragY);
const pending = [...$('presetList').querySelectorAll('.preset-tile-row')].find((r) => r.dataset.pending === '1');
if (pending && moved > 8 && ev.pointerType === 'mouse') {
startDrag(pending);
} else if (pending && moved > 8) {
clearTimeout(holdTimer); // moved before the hold: a scroll
}
if (!dragRow) return;
}
ev.preventDefault();
const list = $('presetList');
const over = document.elementFromPoint(ev.clientX, ev.clientY);
const target = over && over.closest('.preset-tile-row');
if (target && target !== dragRow && target.parentNode === list) {
const r = target.getBoundingClientRect();
const before = ev.clientY < r.top + r.height / 2 || (Math.abs(ev.clientY - (r.top + r.height / 2)) < r.height / 4 && ev.clientX < r.left + r.width / 2);
list.insertBefore(dragRow, before ? target : target.nextSibling);
}
}, { passive: false });
async function endDrag(ev) {
if (ev.pointerId !== dragId) return;
clearTimeout(holdTimer);
dragId = null;
if (!dragRow) return;
const row = dragRow;
dragRow = null;
row.classList.remove('dragging');
row.dataset.pending = '';
justDragged = true; // swallow the click that follows
setTimeout(() => { justDragged = false; }, 0);
const names = [...$('presetList').querySelectorAll('.preset-tile-row')].map((r) => r.dataset.name);
dragging = false;
try {
await post('/api/presets/order', { names });
await loadPresets();
} catch (e) {
presetMsg(e.message);
await loadPresets();
}
}
document.addEventListener('pointerup', endDrag);
document.addEventListener('pointercancel', (ev) => {
clearTimeout(holdTimer);
if (ev.pointerId === dragId && dragRow) endDrag(ev);
else dragId = null;
});
$('presetList').addEventListener('click', (ev) => {
if (justDragged) {
ev.preventDefault();
ev.stopPropagation();
}
}, true);
function renderPresets() {
const list = $('presetList');
list.textContent = '';
if (!presetState.presets.length) {
list.innerHTML = isEditMode()
? '<span class="muted">No presets yet. Use + New preset.</span>'
: '<span class="muted">No presets yet. Switch to Edit mode to add some.</span>';
}
presetState.presets.forEach((p) => {
const row = document.createElement('div');
row.className = 'preset-tile-row';
row.dataset.name = p.name;
attachDrag(row);
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'preset-tile' + (p.name === presetState.selected ? ' active' : '');
const cols = (p.colors && p.colors.length ? p.colors : [[255, 255, 255]]).map(toHex);
const stops = cols.length === 1 ? [cols[0], cols[0]] : cols;
btn.style.background = `linear-gradient(90deg, ${stops.join(', ')})`;
const name = document.createElement('span');
name.className = 'preset-tile-name';
name.textContent = (p.name === presetState.startup ? '★ ' : '') + p.name;
const pat = document.createElement('span');
pat.className = 'preset-tile-pattern';
pat.textContent = p.pattern;
btn.appendChild(name);
btn.appendChild(pat);
btn.title = p.name + ' · ' + p.pattern;
btn.addEventListener('click', () => playPreset(p.name));
const edit = document.createElement('button');
edit.type = 'button';
edit.className = 'preset-edit';
edit.textContent = 'Edit';
edit.addEventListener('click', () => openEditor(p));
row.appendChild(btn);
if (isEditMode()) row.appendChild(edit); // Edit and drag are for Edit mode only
list.appendChild(row);
});
}
async function loadPresets() {
presetState = await api('/api/presets');
if (!dragging) renderPresets();
if (!$('editor-modal').hidden) refreshEditorButtons();
}
// Tapping a preset plays it on the strip
async function playPreset(name) {
try {
await post('/api/presets/select', { name });
await loadPresets();
await loadStatus();
$('status').textContent = 'Playing ' + name;
} catch (e) {
$('status').textContent = e.message;
}
}
$('newPreset').addEventListener('click', () => openEditor(null));
// ---- firmware (over the air) ------------------------------------------------------------------
let fwPartition = null;
async function loadFirmware() {
const f = await api('/ota');
fwPartition = f.partition;
$('fwInfo').textContent = `${f.version} (built ${f.built}, slot ${f.partition})`;
return f;
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// After an update the board reboots onto the other slot: wait until it answers again
async function waitForReboot(before) {
await sleep(3000);
for (let i = 0; i < 40; i++) {
try {
const f = await api('/ota');
return f.partition !== before ? f : null;
} catch (e) {
await sleep(1000);
}
}
return null;
}
$('fwForm').addEventListener('submit', async (ev) => {
ev.preventDefault();
const file = $('fwFile').files[0];
if (!file) {
$('fwMsg').textContent = 'Choose a .bin file first';
return;
}
if (!confirm(`Update to ${file.name} (${file.size} bytes)? The driver reboots afterwards.`)) return;
$('fwUpload').disabled = true;
$('fwMsg').textContent = 'Uploading…';
const before = fwPartition;
try {
const r = await fetch('/ota', {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: file,
});
const j = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(j.error || r.statusText);
$('fwMsg').textContent = 'Written. Rebooting…';
const now = await waitForReboot(before);
$('fwMsg').textContent = now
? `Updated: now running ${now.version} on ${now.partition}.`
: 'The driver is taking a while to come back. Reload the page in a minute.';
if (now) await loadFirmware();
} catch (e) {
$('fwMsg').textContent = e.message;
} finally {
$('fwUpload').disabled = false;
}
});
$('fwReboot').addEventListener('click', async () => {
if (!confirm('Reboot the driver now? The page is unavailable for a few seconds.')) return;
try {
await post('/reboot', {});
$('fwMsg').textContent = 'Rebooting…';
setTimeout(() => location.reload(), 8000);
} catch (e) {
$('fwMsg').textContent = e.message;
}
});
$('addDefaults').addEventListener('click', async () => {
try {
const j = await post('/api/presets/defaults', {});
$('defaultsMsg').textContent = j.added ? `Added ${j.added} preset${j.added === 1 ? '' : 's'}.` : 'All default presets are already there.';
await loadPresets();
} catch (e) {
$('defaultsMsg').textContent = e.message;
}
});
// ---- LED strip settings -----------------------------------------------------------------------
async function loadHardware() {
const h = await api('/api/hardware');
$('hwLeds').value = h.num_leds;
$('hwPin').value = h.pin;
$('hwOrder').value = h.rgb_order;
$('hwMax').value = h.max_brightness;
$('hwMaxOut').textContent = h.max_brightness;
}
$('hwMax').addEventListener('input', () => { $('hwMaxOut').textContent = $('hwMax').value; });
$('hwForm').addEventListener('submit', async (ev) => {
ev.preventDefault();
$('hwMsg').textContent = 'Saving…';
try {
await post('/api/hardware', {
num_leds: Number($('hwLeds').value),
pin: Number($('hwPin').value),
rgb_order: $('hwOrder').value,
max_brightness: Number($('hwMax').value),
});
$('hwMsg').textContent = 'Saved. The strip has been reset with the new settings.';
} catch (e) {
$('hwMsg').textContent = e.message;
}
});
// ---- Wi-Fi and network ------------------------------------------------------------------------
async function loadWifi() {
const w = await api('/api/wifi');
if (w.ssid && !$('ssid').value) $('ssid').value = w.ssid;
}
function updateStaticFields() {
$('staticFields').hidden = $('ipMode').value !== 'static';
}
async function loadNetwork() {
const n = await api('/api/network');
$('hostname').value = n.hostname;
$('mdnsName').textContent = n.hostname;
$('ipMode').value = n.mode;
$('sIp').value = n.ip;
$('sMask').value = n.netmask;
$('sGw').value = n.gateway;
$('sDns').value = n.dns;
updateStaticFields();
}
async function scan() {
const list = $('networks');
list.textContent = 'Scanning…';
try {
const { networks } = await api('/api/wifi/scan');
list.textContent = '';
networks.sort((a, b) => b.rssi - a.rssi).forEach((n) => {
const li = document.createElement('li');
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'net';
btn.textContent = `${n.ssid || '(hidden)'} ${n.rssi} dBm${n.open ? '' : ' 🔒'}`;
btn.addEventListener('click', () => { $('ssid').value = n.ssid; $('pass').focus(); });
li.appendChild(btn);
list.appendChild(li);
});
if (!networks.length) list.textContent = 'No networks found.';
} catch (e) {
list.textContent = e.message;
}
}
$('scan').addEventListener('click', scan);
$('wifiForm').addEventListener('submit', async (ev) => {
ev.preventDefault();
$('wifiMsg').textContent = 'Saving…';
try {
const j = await post('/api/wifi', { ssid: $('ssid').value, password: $('pass').value });
$('wifiMsg').textContent = j.message || 'Saved';
$('pass').value = '';
setTimeout(() => loadStatus().catch(() => {}), 4000);
} catch (e) {
$('wifiMsg').textContent = e.message;
}
});
$('ipMode').addEventListener('change', updateStaticFields);
$('netForm').addEventListener('submit', async (ev) => {
ev.preventDefault();
const body = {
hostname: $('hostname').value.trim().toLowerCase(),
mode: $('ipMode').value,
ip: $('sIp').value.trim(),
netmask: $('sMask').value.trim(),
gateway: $('sGw').value.trim(),
dns: $('sDns').value.trim(),
};
$('netMsg').textContent = 'Saving…';
try {
const j = await post('/api/network', body);
$('netMsg').textContent = `Saved. The client reconnects; open http://${j.address}/ in a few seconds.`;
$('mdnsName').textContent = body.hostname;
} catch (e) {
$('netMsg').textContent = e.message;
}
});
// ---- tabs and start-up ------------------------------------------------------------------------
// On phones the header menu is collapsed behind the ☰ button
const header = document.querySelector('header');
const menuToggle = $('menuToggle');
const setMenu = (open) => {
header.classList.toggle('menu-open', open);
menuToggle.setAttribute('aria-expanded', String(open));
};
menuToggle.addEventListener('click', () => setMenu(!header.classList.contains('menu-open')));
// Run mode: tap presets to play them. Edit mode: also Edit, drag to reorder, New preset and Settings.
const MODE_KEY = 'led-driver-ui-mode';
let uiMode = 'run';
try {
uiMode = localStorage.getItem(MODE_KEY) === 'edit' ? 'edit' : 'run';
} catch (_) { /* private mode: keep Run */ }
function isEditMode() { return uiMode === 'edit'; }
function applyMode() {
const edit = isEditMode();
document.body.classList.toggle('mode-edit', edit);
document.body.classList.toggle('mode-run', !edit);
$('modeToggle').textContent = edit ? 'Run mode' : 'Edit mode'; // label is the mode you switch to
$('modeToggle').setAttribute('aria-pressed', String(edit));
$('newPreset').hidden = !edit;
document.querySelector('.tab[data-tab="settings"]').hidden = !edit;
if (!edit) {
document.querySelector('.tab[data-tab="settings"]').classList.remove('active');
showTab('presets');
if (!$('editor-modal').hidden) closeEditor();
}
renderPresets();
}
function setMode(mode) {
uiMode = mode === 'edit' ? 'edit' : 'run';
try { localStorage.setItem(MODE_KEY, uiMode); } catch (_) { /* ignore */ }
applyMode();
setMenu(false);
}
function showTab(id) {
document.querySelectorAll('.tab').forEach((b) => b.classList.toggle('active', b.dataset.tab === id));
['presets', 'settings'].forEach((s) => { $(s).hidden = s !== id; });
}
document.querySelectorAll('.tab').forEach((btn) => {
btn.addEventListener('click', () => {
showTab(btn.dataset.tab);
setMenu(false);
});
});
$('modeToggle').addEventListener('click', () => setMode(isEditMode() ? 'run' : 'edit'));
$('newPreset').addEventListener('click', () => setMenu(false));
applyMode();
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; });
setInterval(() => {
loadStatus().catch(() => {});
loadPresets().catch(() => {});
}, 5000);
})();