// Device registry: name, id (storage key), type (led), transport (wifi|espnow), address /** Last TCP snapshot from WebSocket (so we can apply after async list render). */ let lastTcpSnapshotIps = null; /** Match server-side ``normalize_tcp_peer_ip`` for WS events vs registry rows. */ function normalizeWifiAddressForMatch(addr) { let s = String(addr || '').trim(); if (s.toLowerCase().startsWith('::ffff:')) { s = s.slice(7); } return s; } const DEVICES_MODAL_POLL_MS = 1000; let devicesModalLiveTimer = null; /** Last ESP-NOW ping result per MAC (hex, no separators). Cleared only when a new ping marks offline. */ const espnowPingStatusByMac = new Map(); /** Aggregate ping dot state (Devices / Settings ping buttons). */ let lastEspnowPingAggregate = { state: 'unknown', title: 'Not pinged yet', }; function stopDevicesModalLiveRefresh() { if (devicesModalLiveTimer != null) { clearInterval(devicesModalLiveTimer); devicesModalLiveTimer = null; } } /** * Refetch registry and re-render the list (no loading spinner). Keeps scroll position. * Used while the devices modal stays open so new TCP devices, renames, and removals appear live. */ async function refreshDevicesListQuiet() { const modal = document.getElementById('devices-modal'); if (!modal || !modal.classList.contains('active')) return; const container = document.getElementById('devices-list-modal'); if (!container) return; const prevTop = container.scrollTop; try { const res = await fetch('/devices', { headers: { Accept: 'application/json' } }); if (!res.ok) return; const data = await res.json(); renderDevicesList(data || {}); container.scrollTop = prevTop; } catch (_) { /* ignore */ } } function startDevicesModalLiveRefresh() { stopDevicesModalLiveRefresh(); devicesModalLiveTimer = setInterval(() => { refreshDevicesListQuiet(); }, DEVICES_MODAL_POLL_MS); } const DEVICE_DOT_CLASSES = [ 'device-status-dot--online', 'device-status-dot--offline', 'device-status-dot--unknown', 'device-status-dot--pinging', ]; function normalizeDeviceMacKey(mac) { return String(mac || '') .trim() .toLowerCase() .replace(/[:-]/g, ''); } function normalizeMacInput(raw) { return String(raw || '') .trim() .toLowerCase() .replace(/[:-]/g, ''); } function findPingResponse(responses, deviceId) { if (!responses || typeof responses !== 'object') return null; const want = normalizeDeviceMacKey(deviceId); for (const [mac, info] of Object.entries(responses)) { if (normalizeDeviceMacKey(mac) === want) return info; } return null; } function setDeviceStatusDot(dot, state, title) { if (!dot) return; dot.classList.remove(...DEVICE_DOT_CLASSES); if (state === 'online') dot.classList.add('device-status-dot--online'); else if (state === 'offline') dot.classList.add('device-status-dot--offline'); else if (state === 'pinging') dot.classList.add('device-status-dot--pinging'); else dot.classList.add('device-status-dot--unknown'); dot.title = title; dot.setAttribute('aria-label', title); } function updatePingStatusDot(dotEl, state, title) { if (!dotEl) return; dotEl.classList.remove(...DEVICE_DOT_CLASSES); if (state === 'online') dotEl.classList.add('device-status-dot--online'); else if (state === 'offline') dotEl.classList.add('device-status-dot--offline'); else if (state === 'pinging') dotEl.classList.add('device-status-dot--pinging'); else dotEl.classList.add('device-status-dot--unknown'); dotEl.title = title; dotEl.setAttribute('aria-label', title); } function rememberEspnowPingAggregate(state, title) { lastEspnowPingAggregate = { state, title }; } function applyEspnowPingAggregateToDots() { for (const id of ['devices-ping-dot']) { updatePingStatusDot(document.getElementById(id), lastEspnowPingAggregate.state, lastEspnowPingAggregate.title); } } async function runUpdateGroups(btn) { const statusEl = document.getElementById('devices-groups-status'); const prevLabel = btn ? btn.textContent : ''; if (btn) { btn.disabled = true; btn.textContent = 'Updating…'; } if (statusEl) statusEl.textContent = 'Sending group membership…'; try { const res = await fetch('/devices/groups', { method: 'POST', headers: { Accept: 'application/json' }, }); const data = await res.json().catch(() => ({})); if (!res.ok || !data.ok) { const err = data.error || 'Update groups failed'; if (statusEl) statusEl.textContent = err; return; } const sent = Number(data.sent) || 0; const failed = Number(data.failed) || 0; if (statusEl) { statusEl.textContent = failed > 0 ? `Sent to ${sent} driver${sent === 1 ? '' : 's'}, ${failed} failed` : `Sent to ${sent} driver${sent === 1 ? '' : 's'}`; } } catch (error) { if (statusEl) statusEl.textContent = error.message; } finally { if (btn) { btn.disabled = false; btn.textContent = prevLabel; } } } async function runEspnowPing({ btn, dot, statusEl } = {}) { const prevLabel = btn ? btn.textContent : ''; if (btn) { btn.disabled = true; btn.textContent = 'Pinging…'; } updatePingStatusDot(dot, 'pinging', 'Ping in progress…'); if (statusEl) statusEl.textContent = 'Waiting for replies (3 s)…'; applyEspnowPingToDeviceRows(null, 'pinging'); try { const res = await fetch('/devices/ping', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify({ timeout_s: 3 }), }); const data = await res.json().catch(() => ({})); if (!res.ok || !data.ok) { const err = data.error || 'Ping failed'; rememberEspnowPingAggregate('offline', err); updatePingStatusDot(dot, 'offline', err); applyEspnowPingAggregateToDots(); if (statusEl) statusEl.textContent = err; return; } const count = Object.keys(data.responses || {}).length; const registered = Number(data.registered) || 0; const aggState = count > 0 ? 'online' : 'offline'; const aggTitle = count > 0 ? `${count} driver${count === 1 ? '' : 's'} replied` : 'No drivers replied'; rememberEspnowPingAggregate(aggState, aggTitle); updatePingStatusDot(dot, aggState, aggTitle); applyEspnowPingAggregateToDots(); if (statusEl) { let msg = `${count} response${count === 1 ? '' : 's'}`; if (registered > 0) { msg += ` · ${registered} new in list`; } statusEl.textContent = msg; } await refreshDevicesListQuiet(); applyEspnowPingToDeviceRows(data.responses, 'done'); } catch (error) { const msg = `Error: ${error.message}`; rememberEspnowPingAggregate('offline', msg); updatePingStatusDot(dot, 'offline', msg); applyEspnowPingAggregateToDots(); if (statusEl) statusEl.textContent = error.message; } finally { if (btn) { btn.disabled = false; btn.textContent = prevLabel; } } } function applyEspnowPingToDeviceRows(responses, phase) { const container = document.getElementById('devices-list-modal'); if (!container) return; container.querySelectorAll('.profiles-row[data-device-transport="espnow"]').forEach((row) => { const dot = row.querySelector('.device-status-dot'); if (!dot) return; if (phase === 'pinging') { setDeviceStatusDot(dot, 'pinging', 'Ping in progress…'); return; } const macKey = normalizeDeviceMacKey(row.dataset.deviceId); const info = findPingResponse(responses, row.dataset.deviceId); if (info) { const rtt = info.rtt_ms != null ? `${info.rtt_ms} ms` : 'ok'; const title = `Ping reply (${rtt})`; setDeviceStatusDot(dot, 'online', title); espnowPingStatusByMac.set(macKey, { state: 'online', title }); } else { const title = 'No ping reply'; setDeviceStatusDot(dot, 'offline', title); espnowPingStatusByMac.set(macKey, { state: 'offline', title }); } }); } function espnowPingStatusForMac(devId) { return espnowPingStatusByMac.get(normalizeDeviceMacKey(devId)) || null; } function updateWifiRowDot(row, connected) { const dot = row.querySelector('.device-status-dot'); if (!dot) return; if ((row.dataset.deviceTransport || '') !== 'wifi') return; dot.classList.remove(...DEVICE_DOT_CLASSES); if (connected) { dot.classList.add('device-status-dot--online'); dot.title = 'Connected (Wi-Fi TCP session)'; } else { dot.classList.add('device-status-dot--offline'); dot.title = 'Not connected (no Wi-Fi TCP session)'; } dot.setAttribute('aria-label', dot.title); } function applyTcpSnapshot(ips) { const set = new Set( (ips || []).map((x) => normalizeWifiAddressForMatch(x)).filter(Boolean), ); const container = document.getElementById('devices-list-modal'); if (!container) return; container.querySelectorAll('.profiles-row[data-device-transport="wifi"]').forEach((row) => { const addr = normalizeWifiAddressForMatch(row.dataset.deviceAddress); updateWifiRowDot(row, set.has(addr)); }); } /** Keep cached snapshot aligned with incremental WS events (connect/disconnect). */ function mergeTcpSnapshotPresence(ip, connected) { const n = normalizeWifiAddressForMatch(ip); if (!n) return; const prev = lastTcpSnapshotIps; const set = new Set( (Array.isArray(prev) ? prev : []).map((x) => normalizeWifiAddressForMatch(x)).filter(Boolean), ); if (connected) { set.add(n); } else { set.delete(n); } lastTcpSnapshotIps = Array.from(set); } function applyTransportVisibility(transport) { const isWifi = transport === 'wifi'; const esp = document.getElementById('edit-device-address-espnow'); const espDrv = document.getElementById('edit-device-espnow-driver-wrap'); const wifiWrap = document.getElementById('edit-device-address-wifi-wrap'); const drvWrap = document.getElementById('edit-device-wifi-driver-wrap'); if (esp) esp.hidden = isWifi; if (espDrv) espDrv.hidden = isWifi; if (wifiWrap) wifiWrap.hidden = !isWifi; if (drvWrap) drvWrap.hidden = !isWifi; } function readMaxBrightness(id) { const el = document.getElementById(id); if (!el || el.value === '') return null; const n = parseInt(el.value, 10); return Number.isNaN(n) ? null : Math.max(0, Math.min(255, n)); } function getDriverConfigPushFields(transport, registryName) { const push = {}; if (registryName) push.name = registryName; const mb = readMaxBrightness('edit-device-max-brightness'); if (mb != null) push.max_brightness = mb; if (transport === 'wifi') { const nl = document.getElementById('edit-device-wifi-num-leds'); const co = document.getElementById('edit-device-wifi-color-order'); const ws = document.getElementById('edit-device-wifi-startup-mode'); if (nl && nl.value !== '') { const n = parseInt(nl.value, 10); if (!Number.isNaN(n) && n >= 1) push.num_leds = n; } if (co && co.value) push.color_order = co.value; if (ws && ws.value) push.startup_mode = ws.value; } else { const nl = document.getElementById('edit-device-espnow-num-leds'); const co = document.getElementById('edit-device-espnow-color-order'); if (nl && nl.value !== '') { const n = parseInt(nl.value, 10); if (!Number.isNaN(n) && n >= 1) push.num_leds = n; } if (co && co.value) push.color_order = co.value; } return push; } function getAddressForPayload(transport) { if (transport === 'wifi') { const el = document.getElementById('edit-device-address-wifi'); const v = (el && el.value.trim()) || ''; return v || null; } const macEl = document.getElementById('edit-device-address-mac'); const hex = normalizeMacInput(macEl && macEl.value); return hex || null; } function collectDeviceEditPayload() { const idInput = document.getElementById('edit-device-id'); const nameInput = document.getElementById('edit-device-name'); const typeSel = document.getElementById('edit-device-type'); const transportSel = document.getElementById('edit-device-transport'); const devId = idInput && idInput.value; const transport = (transportSel && transportSel.value) || 'espnow'; const address = getAddressForPayload(transport); const obr = document.getElementById('edit-device-output-brightness'); let output_brightness = 255; if (obr && obr.value !== '') { const n = parseInt(obr.value, 10); output_brightness = !Number.isNaN(n) ? Math.max(0, Math.min(255, n)) : 255; } const payload = { name: nameInput ? nameInput.value.trim() : '', type: (typeSel && typeSel.value) || 'led', transport, address, output_brightness, }; const maxB = readMaxBrightness('edit-device-max-brightness'); if (maxB != null) payload.max_brightness = maxB; if (transport === 'wifi') { const dn = document.getElementById('edit-device-wifi-driver-name'); const nl = document.getElementById('edit-device-wifi-num-leds'); const co = document.getElementById('edit-device-wifi-color-order'); const ws = document.getElementById('edit-device-wifi-startup-mode'); if (dn && dn.value.trim()) payload.wifi_driver_display_name = dn.value.trim(); if (nl && nl.value !== '') { const n = parseInt(nl.value, 10); if (!Number.isNaN(n) && n >= 1) payload.wifi_driver_num_leds = n; } if (co && co.value) payload.wifi_color_order = co.value; if (ws && ws.value) payload.wifi_startup_mode = ws.value; } else { const nl = document.getElementById('edit-device-espnow-num-leds'); const co = document.getElementById('edit-device-espnow-color-order'); if (nl && nl.value !== '') { const n = parseInt(nl.value, 10); if (!Number.isNaN(n) && n >= 1) payload.num_leds = n; } if (co && co.value) payload.color_order = co.value; } return { devId, payload }; } async function loadDevicesModal() { const container = document.getElementById('devices-list-modal'); if (!container) return; if (typeof window.getEspnowSocket === 'function') { window.getEspnowSocket(); } container.innerHTML = 'Loading...'; try { const response = await fetch('/devices', { headers: { Accept: 'application/json' } }); if (!response.ok) throw new Error('Failed to load devices'); const devices = await response.json(); renderDevicesList(devices || {}); } catch (e) { console.error('loadDevicesModal:', e); container.innerHTML = 'Failed to load devices.'; } } async function createDeviceFromModal() { const nameEl = document.getElementById('devices-add-name'); const trEl = document.getElementById('devices-add-transport'); const macEl = document.getElementById('devices-add-mac'); const addrEl = document.getElementById('devices-add-address'); const statusEl = document.getElementById('devices-add-status'); const btn = document.getElementById('devices-add-btn'); const name = (nameEl && nameEl.value.trim()) || ''; const transport = (trEl && trEl.value) || 'espnow'; const mac = normalizeMacInput(macEl && macEl.value); const address = (addrEl && addrEl.value.trim()) || ''; if (!name) { if (statusEl) statusEl.textContent = 'Name is required'; return; } if (mac.length !== 12) { if (statusEl) statusEl.textContent = 'MAC must be 12 hex characters'; return; } if (transport === 'wifi' && !address) { if (statusEl) statusEl.textContent = 'Address is required for Wi-Fi devices'; return; } if (btn) { btn.disabled = true; btn.textContent = 'Adding…'; } if (statusEl) statusEl.textContent = 'Creating device…'; try { const payload = { name, transport, type: 'led', mac, address: transport === 'wifi' ? address : mac, }; const res = await fetch('/devices', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify(payload), }); const data = await res.json().catch(() => ({})); if (!res.ok) { if (statusEl) statusEl.textContent = data.error || 'Create failed'; return; } if (statusEl) statusEl.textContent = 'Device added'; if (nameEl) nameEl.value = ''; if (macEl) macEl.value = ''; if (addrEl) addrEl.value = ''; await loadDevicesModal(); } catch (e) { if (statusEl) statusEl.textContent = e.message || 'Create failed'; } finally { if (btn) { btn.disabled = false; btn.textContent = 'Add device'; } } } function createDeviceIdentifyButton(devId) { const identifyBtn = document.createElement('button'); identifyBtn.className = 'btn btn-primary btn-small'; identifyBtn.type = 'button'; identifyBtn.textContent = 'Identify'; identifyBtn.title = 'Red blink at 10 Hz (~50% brightness) for 2 s, then off (not saved as a preset)'; identifyBtn.addEventListener('click', async () => { try { const res = await fetch(`/devices/${encodeURIComponent(devId)}/identify`, { method: 'POST', credentials: 'same-origin', headers: { Accept: 'application/json' }, }); const data = await res.json().catch(() => ({})); if (!res.ok) { alert(data.error || 'Identify failed'); return; } } catch (err) { console.error(err); alert('Identify failed'); } }); return identifyBtn; } function renderDevicesList(devices) { const container = document.getElementById('devices-list-modal'); if (!container) return; container.innerHTML = ''; const ids = Object.keys(devices).filter((k) => devices[k] && typeof devices[k] === 'object'); if (ids.length === 0) { const p = document.createElement('p'); p.className = 'muted-text'; p.textContent = 'No devices yet.'; container.appendChild(p); return; } ids.forEach((devId) => { const dev = devices[devId]; const tr = (dev && dev.transport) || 'espnow'; const addrRaw = (dev && dev.address) != null ? String(dev.address).trim() : ''; const row = document.createElement('div'); row.className = 'profiles-row'; row.style.display = 'flex'; row.style.alignItems = 'center'; row.style.gap = '0.5rem'; row.style.flexWrap = 'wrap'; row.dataset.deviceId = devId; row.dataset.deviceTransport = tr; row.dataset.deviceAddress = addrRaw; const dot = document.createElement('span'); dot.className = 'device-status-dot'; dot.setAttribute('role', 'img'); const live = dev && Object.prototype.hasOwnProperty.call(dev, 'connected') ? dev.connected : null; if (live === true) { setDeviceStatusDot(dot, 'online', 'Connected (Wi-Fi TCP session)'); } else if (live === false) { setDeviceStatusDot(dot, 'offline', 'Not connected (no Wi-Fi TCP session)'); } else { const pingCached = espnowPingStatusForMac(devId); if (pingCached) { setDeviceStatusDot(dot, pingCached.state, pingCached.title); } else { setDeviceStatusDot(dot, 'unknown', 'ESP-NOW — ping or identify to test reachability'); } } const label = document.createElement('span'); label.textContent = (dev && dev.name) || devId; label.style.flex = '1'; label.style.minWidth = '100px'; const editBtn = document.createElement('button'); editBtn.className = 'btn btn-secondary btn-small'; editBtn.textContent = 'Edit'; editBtn.addEventListener('click', () => openEditDeviceModal(devId, dev)); const identifyBtn = createDeviceIdentifyButton(devId); const deleteBtn = document.createElement('button'); deleteBtn.className = 'btn btn-secondary btn-small'; deleteBtn.textContent = 'Delete'; deleteBtn.addEventListener('click', async () => { if (!confirm(`Delete device "${(dev && dev.name) || devId}"?`)) return; try { const res = await fetch(`/devices/${encodeURIComponent(devId)}`, { method: 'DELETE' }); if (res.ok) await loadDevicesModal(); else { const data = await res.json().catch(() => ({})); alert(data.error || 'Delete failed'); } } catch (err) { console.error(err); alert('Delete failed'); } }); row.appendChild(dot); row.appendChild(label); row.appendChild(editBtn); row.appendChild(identifyBtn); row.appendChild(deleteBtn); container.appendChild(row); }); // Do not re-apply lastTcpSnapshotIps here: it is only updated on WS open and // device_tcp events; re-applying after each /devices poll overwrites correct // API "connected" with a stale list and leaves Wi-Fi rows stuck online. } function openEditDeviceModal(devId, dev) { const modal = document.getElementById('edit-device-modal'); const idInput = document.getElementById('edit-device-id'); const storageLabel = document.getElementById('edit-device-storage-id'); const nameInput = document.getElementById('edit-device-name'); const typeSel = document.getElementById('edit-device-type'); const transportSel = document.getElementById('edit-device-transport'); const macInput = document.getElementById('edit-device-address-mac'); const wifiInput = document.getElementById('edit-device-address-wifi'); if (!modal || !idInput) return; idInput.value = devId; if (storageLabel) storageLabel.textContent = devId; if (nameInput) nameInput.value = (dev && dev.name) || ''; if (typeSel) typeSel.value = (dev && dev.type) || 'led'; const tr = (dev && dev.transport) || 'espnow'; if (transportSel) transportSel.value = tr; applyTransportVisibility(tr); if (macInput) macInput.value = tr === 'espnow' ? ((dev && dev.address) || '') : ''; if (wifiInput) wifiInput.value = tr === 'wifi' ? ((dev && dev.address) || '') : ''; const eLeds = document.getElementById('edit-device-espnow-num-leds'); const eCo = document.getElementById('edit-device-espnow-color-order'); if (eLeds) { eLeds.value = tr === 'espnow' && dev && dev.num_leds != null && dev.num_leds !== '' ? String(dev.num_leds) : ''; } if (eCo) { const co = (dev && dev.color_order) || 'rgb'; eCo.value = ['rgb', 'rbg', 'grb', 'gbr', 'brg', 'bgr'].includes(String(co).toLowerCase()) ? String(co).toLowerCase() : 'rgb'; } const wName = document.getElementById('edit-device-wifi-driver-name'); const wLeds = document.getElementById('edit-device-wifi-num-leds'); const wCo = document.getElementById('edit-device-wifi-color-order'); const wStart = document.getElementById('edit-device-wifi-startup-mode'); if (wName) { const savedDisp = dev && Object.prototype.hasOwnProperty.call(dev, 'wifi_driver_display_name') ? dev.wifi_driver_display_name : undefined; if (savedDisp != null && String(savedDisp).trim() !== '') { wName.value = String(savedDisp).trim(); } else { wName.value = dev && dev.name ? String(dev.name) : ''; } } if (wLeds) { wLeds.value = dev && dev.wifi_driver_num_leds != null && dev.wifi_driver_num_leds !== '' ? String(dev.wifi_driver_num_leds) : ''; } if (wCo) { const co = (dev && dev.wifi_color_order) || 'rgb'; wCo.value = ['rgb', 'rbg', 'grb', 'gbr', 'brg', 'bgr'].includes(String(co).toLowerCase()) ? String(co).toLowerCase() : 'rgb'; } if (wStart) { const sm = (dev && dev.wifi_startup_mode) || 'default'; wStart.value = ['default', 'last', 'off'].includes(String(sm).toLowerCase()) ? String(sm).toLowerCase() : 'default'; } const obr = document.getElementById('edit-device-output-brightness'); const obv = document.getElementById('edit-device-output-brightness-value'); if (obr) { let bv = 255; if (dev && dev.output_brightness != null && dev.output_brightness !== '') { const n = parseInt(String(dev.output_brightness), 10); if (!Number.isNaN(n)) bv = Math.max(0, Math.min(255, n)); } obr.value = String(bv); if (obv) obv.textContent = String(bv); } const mbr = document.getElementById('edit-device-max-brightness'); const mbv = document.getElementById('edit-device-max-brightness-value'); if (mbr) { let mv = 255; if (dev && dev.max_brightness != null && dev.max_brightness !== '') { const n = parseInt(String(dev.max_brightness), 10); if (!Number.isNaN(n)) mv = Math.max(0, Math.min(255, n)); } mbr.value = String(mv); if (mbv) mbv.textContent = String(mv); } void renderEditDeviceGroups(devId); modal.classList.add('active'); } /** One checkbox per group in the edit modal, ticked when the group lists this device. */ async function renderEditDeviceGroups(devId) { const listEl = document.getElementById('edit-device-groups'); if (!listEl) return; listEl.innerHTML = ''; const groups = await fetchGroupsMap(); const idInput = document.getElementById('edit-device-id'); if (!idInput || idInput.value !== devId) return; listEl.innerHTML = ''; const entries = Object.entries(groups).sort(([a, ga], [b, gb]) => String((ga && ga.name) || a).localeCompare(String((gb && gb.name) || b)), ); if (!entries.length) { const empty = document.createElement('span'); empty.className = 'muted-text'; empty.textContent = 'No groups yet. Add one under Groups.'; listEl.appendChild(empty); return; } entries.forEach(([gid, g]) => { const lbl = document.createElement('label'); lbl.style.cssText = 'display:flex;align-items:center;justify-content:flex-start;gap:0.5rem;margin:0.25rem 0;font-weight:normal;'; const cb = document.createElement('input'); cb.type = 'checkbox'; cb.style.cssText = 'width:auto;flex:none;margin:0;'; cb.value = gid; cb.checked = Array.isArray(g && g.devices) && g.devices.includes(devId); const name = document.createElement('span'); name.textContent = (g && g.name) || gid; lbl.appendChild(cb); lbl.appendChild(name); listEl.appendChild(lbl); }); } /** Add the device to the ticked groups and take it out of the rest; only changed groups are sent. */ async function saveEditDeviceGroups(devId) { const boxes = document.querySelectorAll('#edit-device-groups input[type="checkbox"]'); if (!boxes.length) return true; // Fresh copies, so a member added elsewhere since the modal opened is kept. const groups = await fetchGroupsMap(); try { for (const cb of boxes) { const g = groups[cb.value]; if (!g) throw new Error(`Group ${cb.value} not found`); const devices = Array.isArray(g.devices) ? g.devices : []; if (devices.includes(devId) === cb.checked) continue; const res = await fetch(`/groups/${encodeURIComponent(cb.value)}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ devices: cb.checked ? [...devices, devId] : devices.filter((mac) => mac !== devId), }), }); if (!res.ok) { const data = await res.json().catch(() => ({})); throw new Error(data.error || `Group ${cb.value} not saved`); } } return true; } catch (e) { console.error('saveEditDeviceGroups:', e); alert(e.message || 'Failed to update groups'); return false; } } async function updateDevice(devId, payload) { try { const res = await fetch(`/devices/${encodeURIComponent(devId)}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }); const data = await res.json().catch(() => ({})); if (res.ok) { await loadDevicesModal(); return true; } alert(data.error || 'Failed to update device'); return false; } catch (e) { console.error('updateDevice:', e); alert('Failed to update device'); return false; } } async function pushWifiDriverConfig(devId, fields) { const push = {}; if (fields.name != null && String(fields.name).trim()) push.name = String(fields.name).trim(); if (fields.num_leds != null && fields.num_leds !== '') { const n = parseInt(String(fields.num_leds), 10); if (!Number.isNaN(n) && n >= 1) push.num_leds = n; } if (fields.color_order != null && String(fields.color_order).trim()) { push.color_order = String(fields.color_order).trim().toLowerCase(); } if (fields.startup_mode != null && String(fields.startup_mode).trim()) { const sm = String(fields.startup_mode).trim().toLowerCase(); if (sm === 'default' || sm === 'last' || sm === 'off') push.startup_mode = sm; } if (Object.keys(push).length === 0) return { ok: true, skipped: true }; try { const res = await fetch(`/devices/${encodeURIComponent(devId)}/driver-config`, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify(push), }); const data = await res.json().catch(() => ({})); if (!res.ok) { alert(data.error || 'Could not send settings to the driver (is it connected?)'); return { ok: false }; } return { ok: true }; } catch (e) { console.error('pushWifiDriverConfig:', e); alert('Could not send settings to the driver'); return { ok: false }; } } document.addEventListener('DOMContentLoaded', () => { window.addEventListener('deviceTcpStatus', (ev) => { const { ip, connected } = ev.detail || {}; if (ip == null || typeof connected !== 'boolean') return; mergeTcpSnapshotPresence(ip, connected); const norm = normalizeWifiAddressForMatch(ip); const container = document.getElementById('devices-list-modal'); if (!container) return; container.querySelectorAll('.profiles-row[data-device-transport="wifi"]').forEach((row) => { if (normalizeWifiAddressForMatch(row.dataset.deviceAddress) === norm) { updateWifiRowDot(row, connected); } }); }); window.addEventListener('deviceTcpSnapshot', (ev) => { const ips = ev.detail && ev.detail.connectedIps; lastTcpSnapshotIps = ips; applyTcpSnapshot(ips); }); window.addEventListener('deviceTcpWsOpen', () => { refreshDevicesListQuiet(); }); const devOutBr = document.getElementById('edit-device-output-brightness'); const devOutBrVal = document.getElementById('edit-device-output-brightness-value'); if (devOutBr && devOutBrVal) { devOutBr.addEventListener('input', () => { devOutBrVal.textContent = devOutBr.value; }); } const devMaxBr = document.getElementById('edit-device-max-brightness'); const devMaxBrVal = document.getElementById('edit-device-max-brightness-value'); if (devMaxBr && devMaxBrVal) { devMaxBr.addEventListener('input', () => { devMaxBrVal.textContent = devMaxBr.value; }); } const transportEdit = document.getElementById('edit-device-transport'); if (transportEdit) { transportEdit.addEventListener('change', () => { applyTransportVisibility(transportEdit.value); }); } const devicesBtn = document.getElementById('devices-btn'); const devicesModal = document.getElementById('devices-modal'); const devicesCloseBtn = document.getElementById('devices-close-btn'); const editForm = document.getElementById('edit-device-form'); const editCloseBtn = document.getElementById('edit-device-close-btn'); const editDeviceModal = document.getElementById('edit-device-modal'); const addTransport = document.getElementById('devices-add-transport'); const addAddress = document.getElementById('devices-add-address'); const addBtn = document.getElementById('devices-add-btn'); if (devicesBtn && devicesModal) { devicesBtn.addEventListener('click', () => { devicesModal.classList.add('active'); if (typeof window.getEspnowSocket === 'function') { window.getEspnowSocket(); } applyEspnowPingAggregateToDots(); loadDevicesModal(); startDevicesModalLiveRefresh(); }); } if (devicesCloseBtn) { devicesCloseBtn.addEventListener('click', () => { if (devicesModal) devicesModal.classList.remove('active'); }); } if (addTransport && addAddress) { const syncAddAddress = () => { addAddress.hidden = addTransport.value !== 'wifi'; }; addTransport.addEventListener('change', syncAddAddress); syncAddAddress(); } if (addBtn) { addBtn.addEventListener('click', () => createDeviceFromModal()); } const devicesPingBtn = document.getElementById('devices-ping-btn'); if (devicesPingBtn) { devicesPingBtn.addEventListener('click', () => { runEspnowPing({ btn: devicesPingBtn, dot: document.getElementById('devices-ping-dot'), statusEl: document.getElementById('devices-ping-status'), }); }); } const devicesUpdateGroupsBtn = document.getElementById('devices-update-groups-btn'); if (devicesUpdateGroupsBtn) { devicesUpdateGroupsBtn.addEventListener('click', () => runUpdateGroups(devicesUpdateGroupsBtn)); } const devicesModalEl = document.getElementById('devices-modal'); if (devicesModalEl) { new MutationObserver(() => { if (!devicesModalEl.classList.contains('active')) { stopDevicesModalLiveRefresh(); } }).observe(devicesModalEl, { attributes: true, attributeFilter: ['class'] }); } if (editForm) { editForm.addEventListener('submit', async (e) => { e.preventDefault(); const { devId, payload } = collectDeviceEditPayload(); if (!devId) return; const ok = await updateDevice(devId, payload); if (!ok) return; // Before the brightness push: a driver's brightness includes its groups' factors. if (!(await saveEditDeviceGroups(devId))) return; try { const brRes = await fetch(`/devices/${encodeURIComponent(devId)}/brightness`, { method: 'POST', credentials: 'same-origin', headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({}), }); if (!brRes.ok && brRes.status !== 503) { const brData = await brRes.json().catch(() => ({})); console.warn('brightness push:', brData.error || brRes.status); } } catch (e) { console.warn('brightness push failed', e); } const pushRes = await pushWifiDriverConfig( devId, getDriverConfigPushFields(payload.transport || 'espnow', payload.name), ); if (!pushRes.ok) return; await loadDevicesModal(); }); } if (editCloseBtn) { editCloseBtn.addEventListener('click', () => editDeviceModal && editDeviceModal.classList.remove('active')); } }); if (typeof window !== 'undefined') { window.applyEspnowPingToDeviceRows = applyEspnowPingToDeviceRows; window.runEspnowPing = runEspnowPing; window.applyEspnowPingAggregateToDots = applyEspnowPingAggregateToDots; }