// LED strip web UI. Talks to the JSON API in main/web.cpp. (() => { 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); } // The page talks to this device over one WebSocket (/ws). Replies come back in the order the // requests were sent, so each reply belongs to the oldest request still waiting. const WS_TIMEOUT_MS = 15000; let sock = null; const waiting = []; // {text, resolve, reject}, oldest first let watchdog = null; function kick() { clearTimeout(watchdog); watchdog = waiting.length ? setTimeout(() => closeSock(new Error('The device did not answer.')), WS_TIMEOUT_MS) : null; } function closeSock(err) { const s = sock; sock = null; clearTimeout(watchdog); watchdog = null; if (s) { s.onopen = s.onmessage = s.onclose = s.onerror = null; try { s.close(); } catch (_) { /* already closed */ } } while (waiting.length) waiting.shift().reject(err); } function openSock() { const s = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws'); sock = s; s.onopen = () => { if (sock === s) for (const w of waiting) s.send(w.text); }; s.onmessage = (ev) => { const w = waiting.shift(); kick(); if (!w) return; try { w.resolve(JSON.parse(ev.data)); } catch (e) { w.reject(e); } }; s.onclose = () => { if (sock === s) closeSock(new Error('Lost the connection to the device.')); }; s.onerror = () => {}; // onclose follows } // One request over the WebSocket; resolves to the reply envelope {status, body}. function wsCall(msg) { return new Promise((resolve, reject) => { const text = JSON.stringify(msg); waiting.push({ text, resolve, reject }); if (!sock) openSock(); else if (sock.readyState === WebSocket.OPEN) sock.send(text); kick(); }); } // An API call. host is another driver's address; it is left out for this device. async function wsApi(method, path, body, host) { const msg = { method, path, body }; if (host) msg.host = host; const env = await wsCall(msg); 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; } // This device's own API, over the WebSocket. Firmware upload and info stay on plain HTTP (/ota). async function direct(path, opts) { if (path.startsWith('/ota')) { 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 method = (opts && opts.method) || 'GET'; const body = opts && typeof opts.body === 'string' ? opts.body : ''; return wsApi(method, path, body); } // Another device: this driver makes the call, 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 : ''; return wsApi(method, path, body, host); } // 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' }, 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))); } // One brightness slider. With one device selected it sets that device's own level. // With All devices selected it is a master scale: each device's level is multiplied by it, so // the devices keep their own levels relative to each other. const brightKey = () => (base === ALL ? 'master' : 'brightness'); let globalTimer; $('globalBright').addEventListener('input', () => { $('globalOut').textContent = $('globalBright').value; clearTimeout(globalTimer); globalTimer = setTimeout(() => { post('/api/brightness', { [brightKey()]: Number($('globalBright').value) }).catch((e) => { $('status').textContent = e.message; }); }, 150); }); async function loadStatus() { const host = base; const s = await api('/api/status'); // Another device may have been selected while this answer was on its way: drop it if (host !== base) return; if (document.activeElement !== $('globalBright')) { const level = base === ALL ? s.master_brightness : s.global_brightness; $('globalBright').value = level; $('globalOut').textContent = level; } $('apName').textContent = s.ap_ssid; $('apInfo').hidden = !s.ap_on; $('apOffInfo').hidden = !!s.ap_on; $('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() ? 'No presets yet. Use + New preset.' : 'No presets yet. Switch to Edit mode to add some.'; } 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 (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…'; 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; $('apOn').checked = n.ap_enabled !== false; $('apSsid').value = n.ap_ssid_custom ? n.ap_ssid : ''; $('apSsid').placeholder = n.ap_ssid; $('apPass').value = ''; $('apOpen').checked = false; $('apPassHint').textContent = n.ap_password_set ? '(set; blank keeps it)' : '(open network now)'; $('ddpOn').checked = n.ddp_enabled !== false; 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(), ap_enabled: $('apOn').checked, ddp_enabled: $('ddpOn').checked, ap_ssid: $('apSsid').value.trim(), }; if ($('apOpen').checked) { body.ap_password = ''; } else if ($('apPass').value) { body.ap_password = $('apPass').value; } $('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; $('apPass').value = ''; $('apOpen').checked = false; if (body.ap_password !== undefined) { $('apPassHint').textContent = body.ap_password ? '(set; blank keeps it)' : '(open network now)'; } } catch (e) { $('netMsg').textContent = e.message; } }); // ---- 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 [j, st] = await Promise.all([direct('/api/devices'), direct('/api/status')]); 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) => { 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); }); }); // Settings is split into sections: one visible at a time function showSub(id) { document.querySelectorAll('.subtab').forEach((b) => { const on = b.dataset.sub === id; b.classList.toggle('active', on); b.setAttribute('aria-selected', String(on)); }); document.querySelectorAll('.subpage').forEach((p) => { p.hidden = p.dataset.sub !== id; }); } document.querySelectorAll('.subtab').forEach((btn) => { btn.addEventListener('click', () => showSub(btn.dataset.sub)); }); $('modeToggle').addEventListener('click', () => setMode(isEditMode() ? 'run' : 'edit')); $('newPreset').addEventListener('click', () => setMenu(false)); applyMode(); renderColours(); updateOutputs(); renderDevices(); refreshAll(); discoverDevices(); setInterval(discoverDevices, 60000); setInterval(() => { loadStatus().catch(() => {}); loadPresets().catch(() => {}); }, 5000); })();