feat(v2): move web UI into v2, remove legacy MicroPython app
Move the web assets and templates under v2/web, drop the old src/, lib/ and scripts, and update firmware, tools, docs and db files. Add the audio page, LED test scripts and VPN autoconnect script. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6c16998691
commit
71bd320661
193 files changed
+5605
-18860
No files matched your search
@@ -0,0 +1,188 @@
|
||||
// Audio modal: live beat indicators and level from the controller's microphone detector, plus a
|
||||
// simulated beat (a fixed BPM sent to the drivers, with the microphone ignored while it runs).
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const modal = document.getElementById('audio-modal');
|
||||
const openBtn = document.getElementById('audio-btn');
|
||||
if (!modal || !openBtn) return;
|
||||
|
||||
const el = (id) => document.getElementById(id);
|
||||
const beatBtn = el('audio-modal-beat-sync');
|
||||
const bpmValue = el('audio-bpm-value');
|
||||
const beatReadout = el('audio-modal-beat-readout');
|
||||
const barPhase = el('audio-bar-phase-value');
|
||||
const levelBar = el('audio-input-level-bar');
|
||||
const levelReadout = el('audio-level-readout');
|
||||
const simInput = el('audio-simulated-bpm');
|
||||
const simStatus = el('audio-sim-status');
|
||||
const simStart = el('audio-sim-start-btn');
|
||||
const simStop = el('audio-sim-stop-btn');
|
||||
|
||||
const SIM_MIN = 60;
|
||||
const SIM_MAX = 200;
|
||||
let events = null;
|
||||
let pollTimer = null;
|
||||
let simRunning = false;
|
||||
let simBpm = 120;
|
||||
let simTimer = null;
|
||||
let simTick = 0;
|
||||
|
||||
const clampSim = (n) => Math.max(SIM_MIN, Math.min(SIM_MAX, Math.round(Number(n) || 120)));
|
||||
|
||||
function flash(simulated) {
|
||||
const cls = simulated ? 'flash-simulated' : 'flash';
|
||||
beatBtn.classList.add(cls);
|
||||
setTimeout(() => beatBtn.classList.remove(cls), 90);
|
||||
}
|
||||
|
||||
function showBar(bar, meter, sure) {
|
||||
if (!bar) {
|
||||
barPhase.textContent = '';
|
||||
return;
|
||||
}
|
||||
barPhase.textContent = `${bar}/${meter}`;
|
||||
barPhase.classList.toggle('is-downbeat', bar === 1);
|
||||
beatBtn.classList.toggle('guess', !sure);
|
||||
}
|
||||
|
||||
function showBpm(bpm, simulated) {
|
||||
bpmValue.textContent = bpm ? bpm.toFixed(simulated ? 0 : 1) : '--';
|
||||
beatBtn.classList.toggle('audio-simulated', simulated);
|
||||
}
|
||||
|
||||
// --- detector events -------------------------------------------------------------------
|
||||
function openEvents() {
|
||||
if (events || !window.EventSource) return;
|
||||
events = new EventSource('/beats');
|
||||
events.addEventListener('beat', (e) => {
|
||||
if (simRunning) return;
|
||||
const s = JSON.parse(e.data);
|
||||
flash(false);
|
||||
showBpm(s.bpm, false);
|
||||
beatReadout.textContent = `#${s.n}`;
|
||||
showBar(s.bar, s.meter, s.sure);
|
||||
});
|
||||
events.addEventListener('tempo', (e) => {
|
||||
if (simRunning) return;
|
||||
const s = JSON.parse(e.data);
|
||||
showBpm(s.locked ? s.bpm : 0, false);
|
||||
});
|
||||
}
|
||||
|
||||
function closeEvents() {
|
||||
if (events) {
|
||||
events.close();
|
||||
events = null;
|
||||
}
|
||||
}
|
||||
|
||||
// --- level and simulation state --------------------------------------------------------
|
||||
async function poll() {
|
||||
try {
|
||||
const s = await (await fetch('/status', { cache: 'no-store' })).json();
|
||||
const pct = Math.max(0, Math.min(100, ((s.mic_rms_dbfs + 90) / 90) * 100));
|
||||
levelBar.style.width = `${pct}%`;
|
||||
levelBar.parentElement.setAttribute('aria-valuenow', String(Math.round(pct)));
|
||||
levelReadout.textContent = `${s.mic_rms_dbfs.toFixed(1)} dBFS · ${s.mic_spl_db.toFixed(0)} dB`;
|
||||
const t = await (await fetch('/test/beats', { cache: 'no-store' })).json();
|
||||
setSimRunning(!!t.running);
|
||||
} catch (e) {
|
||||
/* controller briefly unreachable */
|
||||
}
|
||||
if (modal.classList.contains('active')) pollTimer = setTimeout(poll, 500);
|
||||
}
|
||||
|
||||
function setSimRunning(on) {
|
||||
if (on === simRunning && (on === (simTimer !== null))) return;
|
||||
simRunning = on;
|
||||
simStart.disabled = on;
|
||||
simStop.disabled = !on;
|
||||
simStatus.textContent = on ? `Sending ${simBpm} BPM to the drivers; the microphone is ignored.` : '';
|
||||
clearInterval(simTimer);
|
||||
simTimer = null;
|
||||
if (on) {
|
||||
// The controller does not echo generated beats back, so the indicator runs on its own clock
|
||||
simTick = 0;
|
||||
showBpm(simBpm, true);
|
||||
simTimer = setInterval(() => {
|
||||
simTick++;
|
||||
flash(true);
|
||||
beatReadout.textContent = `#${simTick}`;
|
||||
showBar(((simTick - 1) % 4) + 1, 4, true);
|
||||
}, 60000 / simBpm);
|
||||
} else {
|
||||
showBpm(0, false);
|
||||
beatReadout.textContent = '';
|
||||
showBar(0);
|
||||
}
|
||||
}
|
||||
|
||||
async function startSim() {
|
||||
simBpm = clampSim(simInput.value);
|
||||
simInput.value = simBpm;
|
||||
simStatus.textContent = '';
|
||||
const res = await fetch('/test/beats', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ bpm: simBpm, count: 0 }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
simStatus.textContent = 'The controller refused that BPM.';
|
||||
return;
|
||||
}
|
||||
setSimRunning(false);
|
||||
setSimRunning(true);
|
||||
fetch('/settings/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ audio_simulated_bpm: simBpm }),
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
async function stopSim() {
|
||||
await fetch('/test/beats/stop', { method: 'POST' });
|
||||
setSimRunning(false);
|
||||
}
|
||||
|
||||
function tap() {
|
||||
fetch('/tap', { method: 'POST' }).catch(() => {});
|
||||
}
|
||||
|
||||
async function loadSimBpm() {
|
||||
try {
|
||||
const s = await (await fetch('/settings', { cache: 'no-store' })).json();
|
||||
if (s.audio_simulated_bpm != null) simInput.value = clampSim(s.audio_simulated_bpm);
|
||||
} catch (e) {
|
||||
/* keep the default */
|
||||
}
|
||||
}
|
||||
|
||||
// --- open and close --------------------------------------------------------------------
|
||||
function open() {
|
||||
modal.classList.add('active');
|
||||
simStop.disabled = true;
|
||||
loadSimBpm();
|
||||
openEvents();
|
||||
clearTimeout(pollTimer);
|
||||
poll();
|
||||
}
|
||||
|
||||
function close() {
|
||||
modal.classList.remove('active');
|
||||
closeEvents();
|
||||
clearTimeout(pollTimer);
|
||||
// The simulation keeps running on the controller; only the local indicator stops
|
||||
clearInterval(simTimer);
|
||||
simTimer = null;
|
||||
}
|
||||
|
||||
openBtn.addEventListener('click', open);
|
||||
el('audio-close-btn').addEventListener('click', close);
|
||||
simStart.addEventListener('click', startSim);
|
||||
simStop.addEventListener('click', stopSim);
|
||||
el('audio-tap-btn').addEventListener('click', tap);
|
||||
beatBtn.addEventListener('click', tap);
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (!modal.classList.contains('active') || e.repeat) return;
|
||||
if ((e.key === 't' || e.key === 'T') && !/INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) tap();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const paletteButton = document.getElementById('color-palette-btn');
|
||||
const paletteModal = document.getElementById('color-palette-modal');
|
||||
const closeButton = document.getElementById('color-palette-close-btn');
|
||||
const paletteContainer = document.getElementById('palette-container');
|
||||
const paletteNewColor = document.getElementById('palette-new-color');
|
||||
const profileNameDisplay = document.getElementById('palette-current-profile-name');
|
||||
|
||||
if (!paletteButton || !paletteModal || !paletteContainer) {
|
||||
return;
|
||||
}
|
||||
|
||||
let currentProfileId = null;
|
||||
let currentPaletteId = null;
|
||||
let currentPalette = [];
|
||||
let currentProfileName = null;
|
||||
|
||||
const renderPalette = () => {
|
||||
paletteContainer.innerHTML = '';
|
||||
if (!currentPalette.length) {
|
||||
const empty = document.createElement('p');
|
||||
empty.className = 'muted-text';
|
||||
empty.textContent = 'No colors in palette.';
|
||||
paletteContainer.appendChild(empty);
|
||||
return;
|
||||
}
|
||||
currentPalette.forEach((color, index) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'profiles-row';
|
||||
row.dataset.color = color;
|
||||
row.style.cssText = 'display: flex; align-items: center; gap: 1rem;';
|
||||
// Ensure no text content
|
||||
row.textContent = '';
|
||||
|
||||
const swatch = document.createElement('div');
|
||||
swatch.style.cssText = `
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
border-radius: 8px;
|
||||
background-color: ${color};
|
||||
border: 2px solid #4a4a4a;
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.3);
|
||||
`;
|
||||
swatch.title = color; // Show hex code on hover only
|
||||
swatch.setAttribute('aria-label', `Color ${color}`);
|
||||
|
||||
const removeButton = document.createElement('button');
|
||||
removeButton.className = 'btn btn-danger btn-small';
|
||||
removeButton.textContent = 'Remove';
|
||||
removeButton.style.fontSize = '0.8rem'; // Restore font size for button
|
||||
removeButton.addEventListener('click', async (e) => {
|
||||
e.stopPropagation();
|
||||
const updated = currentPalette.filter((_, i) => i !== index);
|
||||
await savePalette(updated);
|
||||
});
|
||||
|
||||
row.appendChild(swatch);
|
||||
row.appendChild(removeButton);
|
||||
paletteContainer.appendChild(row);
|
||||
});
|
||||
};
|
||||
|
||||
const loadPalette = async () => {
|
||||
try {
|
||||
const currentResponse = await fetch('/profiles/current', {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!currentResponse.ok) {
|
||||
throw new Error('Failed to load current profile');
|
||||
}
|
||||
const currentData = await currentResponse.json();
|
||||
currentProfileId = currentData.id || null;
|
||||
const profile = currentData.profile || null;
|
||||
currentProfileName = profile ? profile.name : null;
|
||||
if (profileNameDisplay) {
|
||||
profileNameDisplay.textContent = currentProfileName || currentProfileId || 'None';
|
||||
}
|
||||
|
||||
if (!currentProfileId || !profile) {
|
||||
currentPalette = [];
|
||||
renderPalette();
|
||||
return;
|
||||
}
|
||||
|
||||
// Prefer palette_id-based storage; fall back to legacy inline palette.
|
||||
currentPaletteId = profile.palette_id || profile.paletteId || null;
|
||||
if (currentPaletteId) {
|
||||
try {
|
||||
const palResponse = await fetch(`/palettes/${currentPaletteId}`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (palResponse.ok) {
|
||||
const palData = await palResponse.json();
|
||||
currentPalette = (palData.colors) || [];
|
||||
} else {
|
||||
currentPalette = [];
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load palette by id:', e);
|
||||
currentPalette = [];
|
||||
}
|
||||
} else {
|
||||
// Legacy: palette stored directly on profile
|
||||
currentPalette = profile.palette || profile.color_palette || [];
|
||||
}
|
||||
renderPalette();
|
||||
} catch (error) {
|
||||
console.error('Failed to load palette:', error);
|
||||
currentPalette = [];
|
||||
renderPalette();
|
||||
}
|
||||
};
|
||||
|
||||
const savePalette = async (newPalette) => {
|
||||
if (!currentProfileId) {
|
||||
alert('No profile selected.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// Ensure we have a palette ID for this profile.
|
||||
if (!currentPaletteId) {
|
||||
const createResponse = await fetch('/palettes', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ colors: newPalette }),
|
||||
});
|
||||
if (!createResponse.ok) {
|
||||
throw new Error('Failed to create palette');
|
||||
}
|
||||
const pal = await createResponse.json();
|
||||
currentPaletteId = pal.id || Object.keys(pal)[0];
|
||||
|
||||
// Link the new palette to the current profile.
|
||||
const linkResponse = await fetch('/profiles/current', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
palette_id: currentPaletteId,
|
||||
}),
|
||||
});
|
||||
if (!linkResponse.ok) {
|
||||
throw new Error('Failed to link palette to profile');
|
||||
}
|
||||
} else {
|
||||
// Update existing palette colors
|
||||
const updateResponse = await fetch(`/palettes/${currentPaletteId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ colors: newPalette }),
|
||||
});
|
||||
if (!updateResponse.ok) {
|
||||
throw new Error('Failed to save palette');
|
||||
}
|
||||
}
|
||||
|
||||
currentPalette = newPalette;
|
||||
renderPalette();
|
||||
} catch (error) {
|
||||
console.error('Failed to save palette:', error);
|
||||
alert('Failed to save palette.');
|
||||
}
|
||||
};
|
||||
|
||||
const openModal = () => {
|
||||
paletteModal.classList.add('active');
|
||||
loadPalette();
|
||||
};
|
||||
|
||||
const closeModal = () => {
|
||||
paletteModal.classList.remove('active');
|
||||
};
|
||||
|
||||
paletteButton.addEventListener('click', openModal);
|
||||
if (closeButton) {
|
||||
closeButton.addEventListener('click', closeModal);
|
||||
}
|
||||
if (paletteNewColor) {
|
||||
const addSelectedColor = async () => {
|
||||
const color = paletteNewColor.value;
|
||||
if (!color) {
|
||||
return;
|
||||
}
|
||||
if (currentPalette.includes(color)) {
|
||||
alert('Color already in palette.');
|
||||
return;
|
||||
}
|
||||
await savePalette([...currentPalette, color]);
|
||||
};
|
||||
// Add when the picker closes (user confirms selection).
|
||||
paletteNewColor.addEventListener('change', addSelectedColor);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,471 @@
|
||||
// Device registry: name, id (storage key), type (led), transport (wifi|espnow), address
|
||||
|
||||
const HEX_BOX_COUNT = 12;
|
||||
|
||||
/** 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;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
function updateWifiRowDot(row, connected) {
|
||||
const dot = row.querySelector('.device-status-dot');
|
||||
if (!dot) return;
|
||||
if ((row.dataset.deviceTransport || '') !== 'wifi') return;
|
||||
dot.classList.remove('device-status-dot--online', 'device-status-dot--offline', 'device-status-dot--unknown');
|
||||
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 makeHexAddressBoxes(container) {
|
||||
if (!container || container.querySelector('.hex-addr-box')) return;
|
||||
container.innerHTML = '';
|
||||
for (let i = 0; i < HEX_BOX_COUNT; i++) {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'text';
|
||||
input.className = 'hex-addr-box';
|
||||
input.maxLength = 1;
|
||||
input.autocomplete = 'off';
|
||||
input.setAttribute('data-index', i);
|
||||
input.setAttribute('inputmode', 'numeric');
|
||||
input.setAttribute('aria-label', `Hex digit ${i + 1}`);
|
||||
input.addEventListener('input', (e) => {
|
||||
const v = e.target.value.replace(/[^0-9a-fA-F]/g, '');
|
||||
e.target.value = v;
|
||||
if (v && e.target.nextElementSibling && e.target.nextElementSibling.classList.contains('hex-addr-box')) {
|
||||
e.target.nextElementSibling.focus();
|
||||
}
|
||||
});
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Backspace' && !e.target.value && e.target.previousElementSibling) {
|
||||
e.target.previousElementSibling.focus();
|
||||
}
|
||||
});
|
||||
input.addEventListener('paste', (e) => {
|
||||
e.preventDefault();
|
||||
const pasted = (e.clipboardData.getData('text') || '').replace(/[^0-9a-fA-F]/g, '').slice(0, HEX_BOX_COUNT);
|
||||
const boxes = container.querySelectorAll('.hex-addr-box');
|
||||
for (let j = 0; j < pasted.length && j < boxes.length; j++) {
|
||||
boxes[j].value = pasted[j];
|
||||
}
|
||||
if (pasted.length > 0) {
|
||||
const nextIdx = Math.min(pasted.length, boxes.length - 1);
|
||||
boxes[nextIdx].focus();
|
||||
}
|
||||
});
|
||||
container.appendChild(input);
|
||||
}
|
||||
}
|
||||
|
||||
function setAddressToBoxes(container, addrStr) {
|
||||
if (!container) return;
|
||||
const s = (addrStr || '').replace(/[^0-9a-fA-F]/g, '').slice(0, HEX_BOX_COUNT);
|
||||
const boxes = container.querySelectorAll('.hex-addr-box');
|
||||
boxes.forEach((b, i) => {
|
||||
b.value = s[i] || '';
|
||||
});
|
||||
}
|
||||
|
||||
function applyTransportVisibility(transport) {
|
||||
const isWifi = transport === 'wifi';
|
||||
const esp = document.getElementById('edit-device-address-espnow');
|
||||
const wifiWrap = document.getElementById('edit-device-address-wifi-wrap');
|
||||
if (esp) esp.hidden = isWifi;
|
||||
if (wifiWrap) wifiWrap.hidden = !isWifi;
|
||||
}
|
||||
|
||||
function getAddressForPayload(transport) {
|
||||
if (transport === 'wifi') {
|
||||
const el = document.getElementById('edit-device-address-wifi');
|
||||
const v = (el && el.value.trim()) || '';
|
||||
return v || null;
|
||||
}
|
||||
const boxEl = document.getElementById('edit-device-address-boxes');
|
||||
if (!boxEl) return null;
|
||||
const boxes = boxEl.querySelectorAll('.hex-addr-box');
|
||||
const hex = Array.from(boxes).map((b) => b.value).join('').toLowerCase();
|
||||
return hex || null;
|
||||
}
|
||||
|
||||
async function loadDevicesModal() {
|
||||
const container = document.getElementById('devices-list-modal');
|
||||
if (!container) return;
|
||||
if (typeof window.getEspnowSocket === 'function') {
|
||||
window.getEspnowSocket();
|
||||
}
|
||||
container.innerHTML = '<span class="muted-text">Loading...</span>';
|
||||
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 = '<span class="muted-text">Failed to load devices.</span>';
|
||||
}
|
||||
}
|
||||
|
||||
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. Wi-Fi drivers will appear here when they connect over TCP.';
|
||||
container.appendChild(p);
|
||||
return;
|
||||
}
|
||||
ids.forEach((devId) => {
|
||||
const dev = devices[devId];
|
||||
const t = (dev && dev.type) || 'led';
|
||||
const tr = (dev && dev.transport) || 'espnow';
|
||||
const addrRaw = (dev && dev.address) != null ? String(dev.address).trim() : '';
|
||||
const addrDisplay = addrRaw || '—';
|
||||
|
||||
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) {
|
||||
dot.classList.add('device-status-dot--online');
|
||||
dot.title = 'Connected (Wi-Fi TCP session)';
|
||||
dot.setAttribute('aria-label', dot.title);
|
||||
} else if (live === false) {
|
||||
dot.classList.add('device-status-dot--offline');
|
||||
dot.title = 'Not connected (no Wi-Fi TCP session)';
|
||||
dot.setAttribute('aria-label', dot.title);
|
||||
} else {
|
||||
dot.classList.add('device-status-dot--unknown');
|
||||
dot.title = 'ESP-NOW — TCP status does not apply';
|
||||
dot.setAttribute('aria-label', dot.title);
|
||||
}
|
||||
|
||||
const label = document.createElement('span');
|
||||
label.textContent = (dev && dev.name) || devId;
|
||||
label.style.flex = '1';
|
||||
label.style.minWidth = '100px';
|
||||
|
||||
const macEl = document.createElement('code');
|
||||
macEl.className = 'device-row-mac';
|
||||
macEl.textContent = devId;
|
||||
macEl.title = 'MAC (registry id)';
|
||||
|
||||
const meta = document.createElement('span');
|
||||
meta.className = 'muted-text';
|
||||
meta.style.fontSize = '0.85em';
|
||||
meta.textContent = `${t} · ${tr} · ${addrDisplay}`;
|
||||
|
||||
const editBtn = document.createElement('button');
|
||||
editBtn.className = 'btn btn-secondary btn-small';
|
||||
editBtn.textContent = 'Edit';
|
||||
editBtn.addEventListener('click', () => openEditDeviceModal(devId, dev));
|
||||
|
||||
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');
|
||||
}
|
||||
});
|
||||
|
||||
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(macEl);
|
||||
row.appendChild(meta);
|
||||
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 addressBoxes = document.getElementById('edit-device-address-boxes');
|
||||
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);
|
||||
setAddressToBoxes(addressBoxes, tr === 'espnow' ? ((dev && dev.address) || '') : '');
|
||||
if (wifiInput) wifiInput.value = tr === 'wifi' ? ((dev && dev.address) || '') : '';
|
||||
DEVICE_SETTING_FIELDS.forEach((f) => {
|
||||
const el = document.getElementById(f.id);
|
||||
if (el) el.value = dev && dev[f.key] != null ? String(dev[f.key]) : '';
|
||||
});
|
||||
modal.classList.add('active');
|
||||
}
|
||||
|
||||
// Driver settings edited in the device dialog: key on the device record, input id, parser (null = leave unchanged)
|
||||
const DEVICE_SETTING_FIELDS = [
|
||||
{ key: 'num_leds', id: 'edit-device-num-leds', parse: (v) => Math.max(1, Math.min(2048, Math.round(Number(v)) || 1)) },
|
||||
{ key: 'color_order', id: 'edit-device-color-order', parse: (v) => v },
|
||||
{ key: 'startup_mode', id: 'edit-device-startup-mode', parse: (v) => v },
|
||||
{ key: 'reversed', id: 'edit-device-reversed', parse: (v) => v === 'true' },
|
||||
{ key: 'max_brightness', id: 'edit-device-max-brightness', parse: (v) => Math.max(0, Math.min(255, Math.round(Number(v)) || 0)) },
|
||||
];
|
||||
|
||||
function readDeviceSettings() {
|
||||
const out = {};
|
||||
DEVICE_SETTING_FIELDS.forEach((f) => {
|
||||
const el = document.getElementById(f.id);
|
||||
const raw = el ? el.value.trim() : '';
|
||||
if (raw !== '') out[f.key] = f.parse(raw);
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
async function updateDevice(devId, name, type, transport, address, settings) {
|
||||
try {
|
||||
const res = await fetch(`/devices/${encodeURIComponent(devId)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name,
|
||||
type: type || 'led',
|
||||
transport: transport || 'espnow',
|
||||
address,
|
||||
...(settings || {}),
|
||||
}),
|
||||
});
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
makeHexAddressBoxes(document.getElementById('edit-device-address-boxes'));
|
||||
|
||||
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');
|
||||
|
||||
if (devicesBtn && devicesModal) {
|
||||
devicesBtn.addEventListener('click', () => {
|
||||
devicesModal.classList.add('active');
|
||||
if (typeof window.getEspnowSocket === 'function') {
|
||||
window.getEspnowSocket();
|
||||
}
|
||||
loadDevicesModal();
|
||||
startDevicesModalLiveRefresh();
|
||||
});
|
||||
}
|
||||
if (devicesCloseBtn) {
|
||||
devicesCloseBtn.addEventListener('click', () => {
|
||||
if (devicesModal) devicesModal.classList.remove('active');
|
||||
});
|
||||
}
|
||||
|
||||
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 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;
|
||||
if (!devId) return;
|
||||
const transport = (transportSel && transportSel.value) || 'espnow';
|
||||
const address = getAddressForPayload(transport);
|
||||
const ok = await updateDevice(
|
||||
devId,
|
||||
nameInput ? nameInput.value.trim() : '',
|
||||
(typeSel && typeSel.value) || 'led',
|
||||
transport,
|
||||
address,
|
||||
readDeviceSettings()
|
||||
);
|
||||
if (ok) editDeviceModal.classList.remove('active');
|
||||
});
|
||||
}
|
||||
if (editCloseBtn) {
|
||||
editCloseBtn.addEventListener('click', () => editDeviceModal && editDeviceModal.classList.remove('active'));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,295 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Help modal
|
||||
const helpBtn = document.getElementById('help-btn');
|
||||
const helpModal = document.getElementById('help-modal');
|
||||
const helpCloseBtn = document.getElementById('help-close-btn');
|
||||
const mainMenuBtn = document.getElementById('main-menu-btn');
|
||||
const mainMenuDropdown = document.getElementById('main-menu-dropdown');
|
||||
|
||||
if (helpBtn && helpModal) {
|
||||
helpBtn.addEventListener('click', () => {
|
||||
helpModal.classList.add('active');
|
||||
});
|
||||
}
|
||||
|
||||
if (helpCloseBtn && helpModal) {
|
||||
helpCloseBtn.addEventListener('click', () => {
|
||||
helpModal.classList.remove('active');
|
||||
});
|
||||
}
|
||||
|
||||
// Mobile main menu: forward clicks to existing header buttons
|
||||
if (mainMenuBtn && mainMenuDropdown) {
|
||||
mainMenuBtn.addEventListener('click', () => {
|
||||
mainMenuDropdown.classList.toggle('open');
|
||||
});
|
||||
|
||||
mainMenuDropdown.addEventListener('click', (event) => {
|
||||
const target = event.target;
|
||||
if (target && target.matches('button[data-target]')) {
|
||||
const id = target.getAttribute('data-target');
|
||||
const realBtn = document.getElementById(id);
|
||||
if (realBtn) {
|
||||
realBtn.click();
|
||||
}
|
||||
mainMenuDropdown.classList.remove('open');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Settings modal wiring (reusing existing settings endpoints).
|
||||
const settingsButton = document.getElementById('settings-btn');
|
||||
const settingsModal = document.getElementById('settings-modal');
|
||||
const settingsCloseButton = document.getElementById('settings-close-btn');
|
||||
|
||||
const showSettingsMessage = (text, type = 'success') => {
|
||||
const messageEl = document.getElementById('settings-message');
|
||||
if (!messageEl) return;
|
||||
messageEl.textContent = text;
|
||||
messageEl.className = `message ${type} show`;
|
||||
setTimeout(() => {
|
||||
messageEl.classList.remove('show');
|
||||
}, 5000);
|
||||
};
|
||||
|
||||
async function loadDeviceSettings() {
|
||||
try {
|
||||
const response = await fetch('/settings');
|
||||
const data = await response.json();
|
||||
const nameInput = document.getElementById('device-name-input');
|
||||
if (nameInput && data && typeof data === 'object') {
|
||||
nameInput.value = data.device_name || 'led-controller';
|
||||
}
|
||||
const chInput = document.getElementById('wifi-channel-input');
|
||||
if (chInput && data && typeof data === 'object') {
|
||||
const ch = data.wifi_channel;
|
||||
chInput.value =
|
||||
ch !== undefined && ch !== null && ch !== '' ? String(ch) : '6';
|
||||
}
|
||||
const hostInput = document.getElementById('hostname-input');
|
||||
if (hostInput && staticIpsList && data && typeof data === 'object') {
|
||||
hostInput.value = data.hostname || '';
|
||||
staticIpsList.innerHTML = '';
|
||||
(Array.isArray(data.static_ips) ? data.static_ips : []).forEach(addStaticIpRow);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading device settings:', error);
|
||||
}
|
||||
}
|
||||
|
||||
const staticIpsList = document.getElementById('static-ips-list');
|
||||
const STATIC_IP_FIELDS = [
|
||||
['ip', 'IP address', '192.168.1.50'],
|
||||
['netmask', 'Netmask', '255.255.255.0'],
|
||||
['gw', 'Gateway', '192.168.1.1'],
|
||||
['dns', 'DNS (optional)', 'gateway'],
|
||||
];
|
||||
|
||||
function addStaticIpRow(entry = {}) {
|
||||
if (!staticIpsList) return;
|
||||
const row = document.createElement('div');
|
||||
row.className = 'static-ip-row';
|
||||
row.style.cssText = 'display:flex;flex-wrap:wrap;gap:0.5rem;margin:0.5rem 0;align-items:center;';
|
||||
STATIC_IP_FIELDS.forEach(([key, label, placeholder]) => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'text';
|
||||
input.dataset.key = key;
|
||||
input.placeholder = `${label} (${placeholder})`;
|
||||
input.title = label;
|
||||
input.value = entry[key] || '';
|
||||
input.style.cssText = 'flex:1 1 9rem;min-width:0;';
|
||||
row.appendChild(input);
|
||||
});
|
||||
const remove = document.createElement('button');
|
||||
remove.type = 'button';
|
||||
remove.className = 'btn btn-secondary';
|
||||
remove.textContent = 'Remove';
|
||||
remove.addEventListener('click', () => row.remove());
|
||||
row.appendChild(remove);
|
||||
staticIpsList.appendChild(row);
|
||||
}
|
||||
|
||||
const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
|
||||
const validIp = (v) => {
|
||||
const m = IPV4.exec(v);
|
||||
return !!m && m.slice(1).every((o) => Number(o) <= 255);
|
||||
};
|
||||
|
||||
function readStaticIps() {
|
||||
const out = [];
|
||||
for (const row of staticIpsList.querySelectorAll('.static-ip-row')) {
|
||||
const entry = {};
|
||||
row.querySelectorAll('input').forEach((i) => {
|
||||
const v = i.value.trim();
|
||||
if (v) entry[i.dataset.key] = v;
|
||||
});
|
||||
if (!Object.keys(entry).length) continue;
|
||||
if (!entry.ip) throw new Error('Every static IP needs an IP address');
|
||||
for (const [k, v] of Object.entries(entry)) {
|
||||
if (!validIp(v)) throw new Error(`"${v}" is not a valid ${k} address`);
|
||||
}
|
||||
out.push(entry);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const addIpButton = document.getElementById('static-ip-add-btn');
|
||||
if (addIpButton) addIpButton.addEventListener('click', () => addStaticIpRow());
|
||||
|
||||
async function loadAPStatus() {
|
||||
try {
|
||||
const response = await fetch('/settings/wifi/ap');
|
||||
const config = await response.json();
|
||||
const statusEl = document.getElementById('ap-status');
|
||||
if (!statusEl) return;
|
||||
if (config.active) {
|
||||
statusEl.innerHTML = `
|
||||
<h4>AP Status: <span class="status-connected">Active</span></h4>
|
||||
<p><strong>SSID:</strong> ${config.ssid || 'N/A'}</p>
|
||||
<p><strong>Channel:</strong> ${config.channel || 'Auto'}</p>
|
||||
<p><strong>IP Address:</strong> ${config.ip || 'N/A'}</p>
|
||||
`;
|
||||
} else {
|
||||
statusEl.innerHTML = `
|
||||
<h4>AP Status: <span class="status-disconnected">Inactive</span></h4>
|
||||
<p>Access Point is not currently active</p>
|
||||
`;
|
||||
}
|
||||
if (config.saved_ssid) document.getElementById('ap-ssid').value = config.saved_ssid;
|
||||
if (config.saved_channel) document.getElementById('ap-channel').value = config.saved_channel;
|
||||
} catch (error) {
|
||||
console.error('Error loading AP status:', error);
|
||||
}
|
||||
}
|
||||
|
||||
if (settingsButton && settingsModal) {
|
||||
settingsButton.addEventListener('click', () => {
|
||||
settingsModal.classList.add('active');
|
||||
// Load current WiFi status/config when opening
|
||||
loadDeviceSettings();
|
||||
loadAPStatus();
|
||||
});
|
||||
}
|
||||
|
||||
if (settingsCloseButton && settingsModal) {
|
||||
settingsCloseButton.addEventListener('click', () => {
|
||||
settingsModal.classList.remove('active');
|
||||
});
|
||||
}
|
||||
|
||||
const deviceForm = document.getElementById('device-form');
|
||||
if (deviceForm) {
|
||||
deviceForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const nameInput = document.getElementById('device-name-input');
|
||||
const deviceName = nameInput ? nameInput.value.trim() : '';
|
||||
if (!deviceName) {
|
||||
showSettingsMessage('Device name is required', 'error');
|
||||
return;
|
||||
}
|
||||
const chRaw = document.getElementById('wifi-channel-input')
|
||||
? document.getElementById('wifi-channel-input').value
|
||||
: '6';
|
||||
const wifiChannel = parseInt(chRaw, 10);
|
||||
if (Number.isNaN(wifiChannel) || wifiChannel < 1 || wifiChannel > 11) {
|
||||
showSettingsMessage('WiFi channel must be between 1 and 11', 'error');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch('/settings/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
device_name: deviceName,
|
||||
wifi_channel: wifiChannel,
|
||||
}),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (response.ok) {
|
||||
showSettingsMessage(
|
||||
'Device settings saved. They will apply on next restart where relevant.',
|
||||
'success',
|
||||
);
|
||||
} else {
|
||||
showSettingsMessage(`Error: ${result.error || 'Failed to save device name'}`, 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showSettingsMessage(`Error: ${error.message}`, 'error');
|
||||
}
|
||||
});
|
||||
}
|
||||
const networkForm = document.getElementById('network-form');
|
||||
if (networkForm) {
|
||||
networkForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const hostname = document.getElementById('hostname-input').value.trim();
|
||||
if (hostname && !/^[A-Za-z0-9-]+$/.test(hostname)) {
|
||||
showSettingsMessage('Hostname may only contain letters, digits and hyphens', 'error');
|
||||
return;
|
||||
}
|
||||
let staticIps;
|
||||
try {
|
||||
staticIps = readStaticIps();
|
||||
} catch (error) {
|
||||
showSettingsMessage(error.message, 'error');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch('/settings/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ hostname, static_ips: staticIps }),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (response.ok) {
|
||||
showSettingsMessage('Network settings saved. Restart the controller to apply them.', 'success');
|
||||
} else {
|
||||
showSettingsMessage(`Error: ${result.error || 'Failed to save network settings'}`, 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showSettingsMessage(`Error: ${error.message}`, 'error');
|
||||
}
|
||||
});
|
||||
}
|
||||
const apForm = document.getElementById('ap-form');
|
||||
if (apForm) {
|
||||
apForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const formData = {
|
||||
ssid: document.getElementById('ap-ssid').value,
|
||||
password: document.getElementById('ap-password').value,
|
||||
channel: document.getElementById('ap-channel').value || null,
|
||||
};
|
||||
|
||||
if (formData.password && formData.password.length > 0 && formData.password.length < 8) {
|
||||
showSettingsMessage('AP password must be at least 8 characters', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (formData.channel) {
|
||||
formData.channel = parseInt(formData.channel, 10);
|
||||
if (formData.channel < 1 || formData.channel > 11) {
|
||||
showSettingsMessage('Channel must be between 1 and 11', 'error');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/settings/wifi/ap', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (response.ok) {
|
||||
showSettingsMessage('Access Point configured successfully!', 'success');
|
||||
setTimeout(loadAPStatus, 1000);
|
||||
} else {
|
||||
showSettingsMessage(`Error: ${result.error || 'Failed to configure AP'}`, 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showSettingsMessage(`Error: ${error.message}`, 'error');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=dn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true,historyRestoreAsHxRequest:true,reportValidityOfForms:false},parseInterval:null,location:location,_:null,version:"2.0.8"};Q.onLoad=V;Q.process=Ft;Q.on=xe;Q.off=be;Q.trigger=ae;Q.ajax=Ln;Q.find=f;Q.findAll=x;Q.closest=g;Q.remove=_;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=ze;Q.defineExtension=_n;Q.removeExtension=zn;Q.logAll=j;Q.logNone=$;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:se,canAccessLocalStorage:X,findThisElement:Se,filterValues:yn,swap:ze,hasAttribute:s,getAttributeValue:a,getClosestAttributeValue:ne,getClosestMatch:q,getExpressionVars:Rn,getHeaders:mn,getInputValues:dn,getInternalData:oe,getSwapSpecification:bn,getTriggerSpecs:st,getTarget:Ee,makeFragment:D,mergeObjects:le,makeSettleInfo:Sn,oobSwap:Te,querySelectorExt:ue,settleImmediately:Yt,shouldCancel:ht,triggerEvent:ae,triggerErrorEvent:fe,withExtensions:Vt};const de=["get","post","put","delete","patch"];const R=de.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function a(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function te(){return document}function y(e,t){return e.getRootNode?e.getRootNode({composed:t}):te()}function q(e,t){while(e&&!t(e)){e=u(e)}return e||null}function o(e,t,n){const r=a(t,n);const o=a(t,"hx-disinherit");var i=a(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function ne(t,n){let r=null;q(t,function(e){return!!(r=o(t,ce(e),n))});if(r!=="unset"){return r}}function h(e,t){return e instanceof Element&&e.matches(t)}function A(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function L(e){if("parseHTMLUnsafe"in Document){return Document.parseHTMLUnsafe(e)}const t=new DOMParser;return t.parseFromString(e,"text/html")}function N(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function r(e){const t=te().createElement("script");ie(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function i(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(i(e)){const t=r(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){H(e)}finally{e.remove()}}})}function D(e){const t=e.replace(/<head(\s[^>]*)?>[\s\S]*?<\/head>/i,"");const n=A(t);let r;if(n==="html"){r=new DocumentFragment;const i=L(e);N(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=L(t);N(r,i.body);r.title=i.title}else{const i=L('<body><template class="internal-htmx-wrapper">'+t+"</template></body>");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function re(e){if(e){e()}}function t(e,t){return Object.protoLine truncated
|
||||
@@ -0,0 +1,255 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const openBtn = document.getElementById('led-tool-btn');
|
||||
const modal = document.getElementById('led-tool-modal');
|
||||
const closeBtn = document.getElementById('led-tool-close-btn');
|
||||
const refreshPortsBtn = document.getElementById('led-tool-refresh-ports-btn');
|
||||
const form = document.getElementById('led-tool-form');
|
||||
const readBtn = document.getElementById('led-tool-read-btn');
|
||||
const resetBtn = document.getElementById('led-tool-reset-btn');
|
||||
const portSelect = document.getElementById('led-tool-port');
|
||||
const outputEl = document.getElementById('led-tool-output');
|
||||
const messageEl = document.getElementById('led-tool-message');
|
||||
|
||||
if (!openBtn || !modal || !form || !portSelect || !outputEl || !messageEl) {
|
||||
return;
|
||||
}
|
||||
|
||||
const showMessage = (text, type = 'success') => {
|
||||
messageEl.textContent = text;
|
||||
messageEl.className = `message ${type} show`;
|
||||
};
|
||||
|
||||
const setOutput = (text) => {
|
||||
outputEl.value = text || '';
|
||||
};
|
||||
|
||||
const parseApiResponse = async (response) => {
|
||||
const bodyText = await response.text();
|
||||
let data = null;
|
||||
try {
|
||||
data = bodyText ? JSON.parse(bodyText) : {};
|
||||
} catch (error) {
|
||||
data = { error: bodyText || `HTTP ${response.status}` };
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
const setFieldValue = (id, value) => {
|
||||
const el = document.getElementById(id);
|
||||
if (!el) return;
|
||||
if (value === undefined || value === null) return;
|
||||
el.value = String(value);
|
||||
};
|
||||
|
||||
const populateFormFromSettings = (settings) => {
|
||||
if (!settings || typeof settings !== 'object') return false;
|
||||
setFieldValue('led-tool-name', settings.name);
|
||||
setFieldValue('led-tool-num-leds', settings.num_leds);
|
||||
setFieldValue('led-tool-led-pin', settings.led_pin);
|
||||
setFieldValue('led-tool-brightness', settings.brightness);
|
||||
setFieldValue('led-tool-transport', settings.transport_type);
|
||||
setFieldValue('led-tool-ssid', settings.ssid);
|
||||
setFieldValue('led-tool-password', settings.password);
|
||||
setFieldValue('led-tool-wifi-channel', settings.wifi_channel);
|
||||
setFieldValue('led-tool-default', settings.default);
|
||||
return true;
|
||||
};
|
||||
|
||||
const loadPorts = async () => {
|
||||
const defaultPort = '/dev/ttyACM0';
|
||||
try {
|
||||
const response = await fetch('/led-tool/ports');
|
||||
const data = await response.json();
|
||||
const previous = portSelect.value;
|
||||
portSelect.innerHTML = '<option value="">Select a serial port</option>';
|
||||
|
||||
for (const port of data.ports || []) {
|
||||
const option = document.createElement('option');
|
||||
option.value = port.device;
|
||||
option.textContent = `${port.device} - ${port.description || 'Unknown'}`;
|
||||
portSelect.appendChild(option);
|
||||
}
|
||||
if (previous) {
|
||||
portSelect.value = previous;
|
||||
} else if ((data.ports || []).some((p) => p.device === defaultPort)) {
|
||||
portSelect.value = defaultPort;
|
||||
} else {
|
||||
const fallback = document.createElement('option');
|
||||
fallback.value = defaultPort;
|
||||
fallback.textContent = `${defaultPort} - default`;
|
||||
portSelect.appendChild(fallback);
|
||||
portSelect.value = defaultPort;
|
||||
}
|
||||
|
||||
if (!data.led_cli_exists) {
|
||||
showMessage('led-tool/cli.py was not found on the host.', 'error');
|
||||
} else if ((data.ports || []).length === 0) {
|
||||
showMessage('No serial ports found.', 'error');
|
||||
} else {
|
||||
showMessage(`Found ${(data.ports || []).length} serial port(s).`, 'success');
|
||||
}
|
||||
} catch (error) {
|
||||
showMessage(`Failed to read serial ports: ${error.message}`, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
openBtn.addEventListener('click', () => {
|
||||
modal.classList.add('active');
|
||||
loadPorts();
|
||||
});
|
||||
|
||||
if (closeBtn) {
|
||||
closeBtn.addEventListener('click', () => {
|
||||
modal.classList.remove('active');
|
||||
});
|
||||
}
|
||||
|
||||
if (refreshPortsBtn) {
|
||||
refreshPortsBtn.addEventListener('click', () => {
|
||||
loadPorts();
|
||||
});
|
||||
}
|
||||
|
||||
if (readBtn) {
|
||||
readBtn.addEventListener('click', async () => {
|
||||
const port = portSelect.value.trim();
|
||||
if (!port) {
|
||||
showMessage('Select a serial port first.', 'error');
|
||||
return;
|
||||
}
|
||||
setOutput('Reading settings from device...');
|
||||
showMessage('Reading settings over USB...', 'success');
|
||||
try {
|
||||
const response = await fetch(`/led-tool/settings?port=${encodeURIComponent(port)}`);
|
||||
const data = await parseApiResponse(response);
|
||||
if (!response.ok) {
|
||||
showMessage(data.error || 'Read failed.', 'error');
|
||||
setOutput(data.error || 'Request failed.');
|
||||
return;
|
||||
}
|
||||
const output = [
|
||||
`exit code: ${data.returncode}`,
|
||||
'',
|
||||
'stdout:',
|
||||
data.stdout || '(none)',
|
||||
'',
|
||||
'stderr:',
|
||||
data.stderr || '(none)',
|
||||
].join('\n');
|
||||
setOutput(output);
|
||||
if (data.ok) {
|
||||
const populated = populateFormFromSettings(data.settings);
|
||||
if (populated) {
|
||||
showMessage('Settings read and fields populated.', 'success');
|
||||
} else {
|
||||
showMessage('Settings read successfully.', 'success');
|
||||
}
|
||||
} else {
|
||||
showMessage('Read completed with errors. Check output.', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showMessage(`Request failed: ${error.message}`, 'error');
|
||||
setOutput(error.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (resetBtn) {
|
||||
resetBtn.addEventListener('click', async () => {
|
||||
const port = portSelect.value.trim();
|
||||
if (!port) {
|
||||
showMessage('Select a serial port first.', 'error');
|
||||
return;
|
||||
}
|
||||
setOutput('Resetting device and following output...');
|
||||
showMessage('Resetting device over USB...', 'success');
|
||||
try {
|
||||
const response = await fetch('/led-tool/reset', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ port }),
|
||||
});
|
||||
const data = await parseApiResponse(response);
|
||||
if (!response.ok) {
|
||||
showMessage(data.error || 'Reset failed.', 'error');
|
||||
setOutput(data.error || 'Request failed.');
|
||||
return;
|
||||
}
|
||||
const output = [
|
||||
`exit code: ${data.returncode}`,
|
||||
'',
|
||||
'stdout:',
|
||||
data.stdout || '(none)',
|
||||
'',
|
||||
'stderr:',
|
||||
data.stderr || '(none)',
|
||||
].join('\n');
|
||||
setOutput(output);
|
||||
if (data.ok) {
|
||||
showMessage('Device reset complete.', 'success');
|
||||
} else {
|
||||
showMessage('Reset completed with errors. Check output.', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showMessage(`Request failed: ${error.message}`, 'error');
|
||||
setOutput(error.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
form.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const port = portSelect.value.trim();
|
||||
if (!port) {
|
||||
showMessage('Select a serial port first.', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
port,
|
||||
name: document.getElementById('led-tool-name')?.value?.trim() || '',
|
||||
num_leds: document.getElementById('led-tool-num-leds')?.value?.trim() || '',
|
||||
led_pin: document.getElementById('led-tool-led-pin')?.value?.trim() || '',
|
||||
brightness: document.getElementById('led-tool-brightness')?.value?.trim() || '',
|
||||
transport: document.getElementById('led-tool-transport')?.value?.trim() || '',
|
||||
ssid: document.getElementById('led-tool-ssid')?.value?.trim() || '',
|
||||
password: document.getElementById('led-tool-password')?.value?.trim() || '',
|
||||
wifi_channel: document.getElementById('led-tool-wifi-channel')?.value?.trim() || '',
|
||||
default: document.getElementById('led-tool-default')?.value?.trim() || '',
|
||||
};
|
||||
|
||||
setOutput('Running led-tool command...');
|
||||
showMessage('Running command over USB...', 'success');
|
||||
try {
|
||||
const response = await fetch('/led-tool/settings', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = await parseApiResponse(response);
|
||||
if (!response.ok) {
|
||||
showMessage(data.error || 'Command failed.', 'error');
|
||||
setOutput(data.error || 'Request failed.');
|
||||
return;
|
||||
}
|
||||
const output = [
|
||||
`exit code: ${data.returncode}`,
|
||||
'',
|
||||
'stdout:',
|
||||
data.stdout || '(none)',
|
||||
'',
|
||||
'stderr:',
|
||||
data.stderr || '(none)',
|
||||
].join('\n');
|
||||
setOutput(output);
|
||||
if (data.ok) {
|
||||
showMessage('Settings applied via USB.', 'success');
|
||||
} else {
|
||||
showMessage('Command completed with errors. Check output.', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showMessage(`Request failed: ${error.message}`, 'error');
|
||||
setOutput(error.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
// Client-side search filter for modal lists (devices, zones, presets).
|
||||
// Hides .profiles-row children whose text doesn't match; re-applies when the list re-renders.
|
||||
|
||||
function rowSearchText(row) {
|
||||
const parts = [];
|
||||
row.querySelectorAll('*').forEach((el) => {
|
||||
if (el.closest('button, .btn')) return;
|
||||
if (el.children.length === 0 && el.textContent) parts.push(el.textContent);
|
||||
});
|
||||
if (row.dataset.deviceId) parts.push(row.dataset.deviceId);
|
||||
if (row.dataset.deviceAddress) parts.push(row.dataset.deviceAddress);
|
||||
return parts.join(' ').toLowerCase();
|
||||
}
|
||||
|
||||
function applyListSearch(list, query) {
|
||||
const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
||||
let shown = 0;
|
||||
let total = 0;
|
||||
list.querySelectorAll(':scope > .profiles-row').forEach((row) => {
|
||||
total += 1;
|
||||
const text = rowSearchText(row);
|
||||
const match = terms.every((t) => text.includes(t));
|
||||
row.classList.toggle('list-search-hidden', !match);
|
||||
if (match) shown += 1;
|
||||
});
|
||||
let empty = list.querySelector(':scope > .list-search-empty');
|
||||
if (total > 0 && shown === 0 && terms.length) {
|
||||
if (!empty) {
|
||||
empty = document.createElement('p');
|
||||
empty.className = 'muted-text list-search-empty';
|
||||
empty.textContent = 'No matches.';
|
||||
list.appendChild(empty);
|
||||
}
|
||||
} else if (empty) {
|
||||
empty.remove();
|
||||
}
|
||||
}
|
||||
|
||||
function initListSearch(inputId, listId, modalId) {
|
||||
const input = document.getElementById(inputId);
|
||||
const list = document.getElementById(listId);
|
||||
if (!input || !list) return;
|
||||
|
||||
let applying = false;
|
||||
const run = () => {
|
||||
applying = true;
|
||||
applyListSearch(list, input.value);
|
||||
observer.takeRecords();
|
||||
applying = false;
|
||||
};
|
||||
const observer = new MutationObserver(() => {
|
||||
if (!applying) run();
|
||||
});
|
||||
observer.observe(list, { childList: true });
|
||||
input.addEventListener('input', run);
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && input.value) {
|
||||
e.stopPropagation();
|
||||
input.value = '';
|
||||
run();
|
||||
}
|
||||
});
|
||||
|
||||
// Clear the search each time the modal is opened.
|
||||
const modal = modalId && document.getElementById(modalId);
|
||||
if (modal) {
|
||||
new MutationObserver(() => {
|
||||
if (modal.classList.contains('active') && input.value) {
|
||||
input.value = '';
|
||||
run();
|
||||
}
|
||||
}).observe(modal, { attributes: true, attributeFilter: ['class'] });
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
initListSearch('devices-search', 'devices-list-modal', 'devices-modal');
|
||||
initListSearch('zones-search', 'zones-list-modal', 'zones-modal');
|
||||
initListSearch('presets-search', 'presets-list', 'presets-modal');
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
// Pixel outputs (db/output.json): DDP, Art-Net, sACN, USB-DMX fixtures the Pi renders for.
|
||||
|
||||
const OUTPUT_PROTOCOL_LABELS = {
|
||||
ddp: 'DDP',
|
||||
artnet: 'Art-Net',
|
||||
sacn: 'sACN',
|
||||
dmx_serial: 'USB-DMX',
|
||||
};
|
||||
|
||||
async function fetchOutputs() {
|
||||
const res = await fetch('/outputs', { headers: { Accept: 'application/json' } });
|
||||
if (!res.ok) throw new Error('Failed to load outputs');
|
||||
return res.json();
|
||||
}
|
||||
|
||||
function outputSummary(out) {
|
||||
const proto = OUTPUT_PROTOCOL_LABELS[out.protocol] || out.protocol;
|
||||
let where = '';
|
||||
if (out.protocol === 'dmx_serial') {
|
||||
where = `${out.serial_port || '?'} ch ${out.channel || 1}`;
|
||||
} else {
|
||||
where = out.host || (out.protocol === 'sacn' ? 'multicast' : 'broadcast');
|
||||
if (out.port) where += `:${out.port}`;
|
||||
if (out.protocol !== 'ddp' && out.universe != null) where += ` u${out.universe}`;
|
||||
}
|
||||
return `${proto} · ${where} · ${out.pixel_count} px${out.enabled === false ? ' · disabled' : ''}`;
|
||||
}
|
||||
|
||||
function renderOutputsList(outputs) {
|
||||
const container = document.getElementById('outputs-list-modal');
|
||||
if (!container) return;
|
||||
container.innerHTML = '';
|
||||
const ids = Object.keys(outputs || {});
|
||||
if (ids.length === 0) {
|
||||
const p = document.createElement('p');
|
||||
p.className = 'muted-text';
|
||||
p.textContent = 'No outputs yet.';
|
||||
container.appendChild(p);
|
||||
return;
|
||||
}
|
||||
ids.forEach((id) => {
|
||||
const out = outputs[id];
|
||||
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';
|
||||
|
||||
const label = document.createElement('span');
|
||||
label.style.flex = '1';
|
||||
label.innerHTML = '';
|
||||
const name = document.createElement('strong');
|
||||
name.textContent = out.name;
|
||||
const meta = document.createElement('span');
|
||||
meta.className = 'muted-text';
|
||||
meta.textContent = ` ${outputSummary(out)}`;
|
||||
label.appendChild(name);
|
||||
label.appendChild(meta);
|
||||
|
||||
const testBtn = document.createElement('button');
|
||||
testBtn.type = 'button';
|
||||
testBtn.className = 'btn btn-secondary btn-small';
|
||||
testBtn.textContent = 'Test';
|
||||
testBtn.title = 'Red, green, blue, white, then black';
|
||||
testBtn.addEventListener('click', async () => {
|
||||
testBtn.disabled = true;
|
||||
testBtn.textContent = 'Testing…';
|
||||
try {
|
||||
const res = await fetch(`/outputs/${encodeURIComponent(id)}/test`, { method: 'POST' });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || res.statusText);
|
||||
const st = data.status || {};
|
||||
testBtn.textContent = st.errors ? `Errors: ${st.errors}` : 'Sent';
|
||||
if (st.last_error) testBtn.title = st.last_error;
|
||||
} catch (e) {
|
||||
testBtn.textContent = 'Failed';
|
||||
testBtn.title = String(e.message || e);
|
||||
} finally {
|
||||
testBtn.disabled = false;
|
||||
setTimeout(() => { testBtn.textContent = 'Test'; }, 2500);
|
||||
}
|
||||
});
|
||||
|
||||
const editBtn = document.createElement('button');
|
||||
editBtn.type = 'button';
|
||||
editBtn.className = 'btn btn-secondary btn-small';
|
||||
editBtn.textContent = 'Edit';
|
||||
editBtn.addEventListener('click', () => openOutputEditor(id, out));
|
||||
|
||||
const delBtn = document.createElement('button');
|
||||
delBtn.type = 'button';
|
||||
delBtn.className = 'btn btn-danger btn-small';
|
||||
delBtn.textContent = 'Delete';
|
||||
delBtn.addEventListener('click', async () => {
|
||||
if (!confirm(`Delete output "${out.name}"?`)) return;
|
||||
const res = await fetch(`/outputs/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
if (!res.ok) {
|
||||
alert('Failed to delete output.');
|
||||
return;
|
||||
}
|
||||
loadOutputsModal();
|
||||
});
|
||||
|
||||
row.append(label, testBtn, editBtn, delBtn);
|
||||
container.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
async function loadOutputsModal() {
|
||||
const container = document.getElementById('outputs-list-modal');
|
||||
try {
|
||||
renderOutputsList(await fetchOutputs());
|
||||
} catch (e) {
|
||||
if (container) container.textContent = 'Failed to load outputs.';
|
||||
}
|
||||
}
|
||||
|
||||
function syncOutputProtocolFields() {
|
||||
const proto = document.getElementById('edit-output-protocol').value;
|
||||
document.querySelectorAll('#edit-output-form .engine-field').forEach((el) => {
|
||||
const list = (el.dataset.protocols || '').split(/\s+/);
|
||||
el.hidden = !list.includes(proto);
|
||||
});
|
||||
}
|
||||
|
||||
function setOutputField(id, value) {
|
||||
const el = document.getElementById(id);
|
||||
if (!el) return;
|
||||
if (el.type === 'checkbox') el.checked = !!value;
|
||||
else el.value = value == null ? '' : value;
|
||||
}
|
||||
|
||||
function openOutputEditor(id, out) {
|
||||
const o = out || {
|
||||
name: '', protocol: 'ddp', pixel_count: 60, pixel_offset: 0, color_order: 'rgb',
|
||||
brightness: 255, fps: 40, channel: 1, dmx_mode: 'enttec_pro', enabled: true, reverse: false,
|
||||
};
|
||||
document.getElementById('edit-output-title').textContent = id ? 'Edit output' : 'Add output';
|
||||
setOutputField('edit-output-id', id || '');
|
||||
setOutputField('edit-output-name', o.name);
|
||||
setOutputField('edit-output-protocol', o.protocol);
|
||||
setOutputField('edit-output-host', o.host);
|
||||
setOutputField('edit-output-port', o.port);
|
||||
setOutputField('edit-output-universe', o.universe);
|
||||
setOutputField('edit-output-serial-port', o.serial_port);
|
||||
setOutputField('edit-output-dmx-mode', o.dmx_mode || 'enttec_pro');
|
||||
setOutputField('edit-output-channel', o.channel || 1);
|
||||
setOutputField('edit-output-pixel-count', o.pixel_count);
|
||||
setOutputField('edit-output-pixel-offset', o.pixel_offset || 0);
|
||||
setOutputField('edit-output-color-order', o.color_order || 'rgb');
|
||||
setOutputField('edit-output-brightness', o.brightness == null ? 255 : o.brightness);
|
||||
setOutputField('edit-output-fps', o.fps || 40);
|
||||
setOutputField('edit-output-reverse', o.reverse);
|
||||
setOutputField('edit-output-enabled', o.enabled !== false);
|
||||
const err = document.getElementById('edit-output-error');
|
||||
err.hidden = true;
|
||||
syncOutputProtocolFields();
|
||||
document.getElementById('edit-output-modal').classList.add('active');
|
||||
}
|
||||
|
||||
function readOutputForm() {
|
||||
const val = (id) => document.getElementById(id).value.trim();
|
||||
const num = (id) => (val(id) === '' ? null : Number(val(id)));
|
||||
return {
|
||||
name: val('edit-output-name'),
|
||||
protocol: val('edit-output-protocol'),
|
||||
host: val('edit-output-host'),
|
||||
port: num('edit-output-port'),
|
||||
universe: num('edit-output-universe'),
|
||||
serial_port: val('edit-output-serial-port'),
|
||||
dmx_mode: val('edit-output-dmx-mode'),
|
||||
channel: num('edit-output-channel') || 1,
|
||||
pixel_count: num('edit-output-pixel-count'),
|
||||
pixel_offset: num('edit-output-pixel-offset') || 0,
|
||||
color_order: val('edit-output-color-order'),
|
||||
brightness: num('edit-output-brightness'),
|
||||
fps: num('edit-output-fps'),
|
||||
reverse: document.getElementById('edit-output-reverse').checked,
|
||||
enabled: document.getElementById('edit-output-enabled').checked,
|
||||
};
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const btn = document.getElementById('outputs-btn');
|
||||
const modal = document.getElementById('outputs-modal');
|
||||
const editModal = document.getElementById('edit-output-modal');
|
||||
const form = document.getElementById('edit-output-form');
|
||||
if (!btn || !modal || !form) return;
|
||||
|
||||
btn.addEventListener('click', () => {
|
||||
modal.classList.add('active');
|
||||
loadOutputsModal();
|
||||
});
|
||||
document.getElementById('outputs-close-btn').addEventListener('click', () => modal.classList.remove('active'));
|
||||
document.getElementById('output-add-btn').addEventListener('click', () => openOutputEditor(null, null));
|
||||
document.getElementById('edit-output-close-btn').addEventListener('click', () => editModal.classList.remove('active'));
|
||||
document.getElementById('edit-output-protocol').addEventListener('change', syncOutputProtocolFields);
|
||||
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const id = document.getElementById('edit-output-id').value;
|
||||
const err = document.getElementById('edit-output-error');
|
||||
err.hidden = true;
|
||||
const res = await fetch(id ? `/outputs/${encodeURIComponent(id)}` : '/outputs', {
|
||||
method: id ? 'PUT' : 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(readOutputForm()),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
err.textContent = data.error || 'Save failed';
|
||||
err.hidden = false;
|
||||
return;
|
||||
}
|
||||
editModal.classList.remove('active');
|
||||
loadOutputsModal();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,582 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const patternsButton = document.getElementById('patterns-btn');
|
||||
const patternsModal = document.getElementById('patterns-modal');
|
||||
const patternsCloseButton = document.getElementById('patterns-close-btn');
|
||||
const patternsList = document.getElementById('patterns-list');
|
||||
const patternAddButton = document.getElementById('pattern-add-btn');
|
||||
const patternSendAllButton = document.getElementById('pattern-send-all-btn');
|
||||
const patternEditorModal = document.getElementById('pattern-editor-modal');
|
||||
const patternEditorCloseButton = document.getElementById('pattern-editor-close-btn');
|
||||
const patternCreateBtn = document.getElementById('pattern-create-btn');
|
||||
const patternCreateName = document.getElementById('pattern-create-name');
|
||||
const patternCreateMinDelay = document.getElementById('pattern-create-min-delay');
|
||||
const patternCreateMaxDelay = document.getElementById('pattern-create-max-delay');
|
||||
const patternCreateMaxColors = document.getElementById('pattern-create-max-colors');
|
||||
const patternCreateFile = document.getElementById('pattern-create-file');
|
||||
const patternCreateCode = document.getElementById('pattern-create-code');
|
||||
const patternCreateOverwrite = document.getElementById('pattern-create-overwrite');
|
||||
const patternCreateN = [1, 2, 3, 4, 5, 6, 7, 8].map((i) =>
|
||||
document.getElementById(`pattern-create-n${i}`),
|
||||
);
|
||||
const patternCreateNSection = document.getElementById('pattern-create-n-section');
|
||||
const patternCreateNEmpty = document.getElementById('pattern-create-n-empty');
|
||||
|
||||
if (!patternsButton || !patternsModal || !patternsList) {
|
||||
return;
|
||||
}
|
||||
|
||||
const coercePresetInt = (v, def = 0) => {
|
||||
if (typeof v === 'number' && Number.isFinite(v)) {
|
||||
return v;
|
||||
}
|
||||
const t = parseInt(String(v), 10);
|
||||
return Number.isFinite(t) ? t : def;
|
||||
};
|
||||
|
||||
const getCurrentProfileId = async () => {
|
||||
try {
|
||||
const response = await fetch('/profiles/current', { headers: { Accept: 'application/json' } });
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
}
|
||||
const data = await response.json();
|
||||
return data && (data.id || (data.profile && data.profile.id)) ? String(data.id || data.profile.id) : null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const filterPresetsForCurrentProfile = async (presetsObj) => {
|
||||
const scoped = presetsObj && typeof presetsObj === 'object' ? presetsObj : {};
|
||||
const currentProfileId = await getCurrentProfileId();
|
||||
if (!currentProfileId) {
|
||||
return scoped;
|
||||
}
|
||||
return Object.fromEntries(
|
||||
Object.entries(scoped).filter(([, preset]) => {
|
||||
if (!preset || typeof preset !== 'object') return false;
|
||||
if (!('profile_id' in preset)) return true;
|
||||
return String(preset.profile_id) === String(currentProfileId);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const tabDeviceNamesFromSection = (section) => {
|
||||
if (typeof window.parseTabDeviceNames === 'function') {
|
||||
return window.parseTabDeviceNames(section);
|
||||
}
|
||||
const namesAttr = section && section.getAttribute('data-device-names');
|
||||
return namesAttr
|
||||
? namesAttr.split(',').map((n) => n.trim()).filter((n) => n.length > 0)
|
||||
: [];
|
||||
};
|
||||
|
||||
const postDriverSequence = async (sequence, targetMacs, delayS = 0.05) => {
|
||||
const body = {
|
||||
sequence,
|
||||
targets: Array.isArray(targetMacs) && targetMacs.length ? [...new Set(targetMacs)] : undefined,
|
||||
delay_s: delayS,
|
||||
};
|
||||
const res = await fetch('/presets/push', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error((err && err.error) || res.statusText || 'Send failed');
|
||||
}
|
||||
return res.json().catch(() => ({}));
|
||||
};
|
||||
|
||||
const nReadableStringFromMeta = (meta, key) => {
|
||||
if (!meta || typeof meta !== 'object') {
|
||||
return '';
|
||||
}
|
||||
const pm = meta.parameter_mappings;
|
||||
if (pm && typeof pm === 'object' && typeof pm[key] === 'string') {
|
||||
const s = pm[key].trim();
|
||||
if (s) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
if (typeof meta[key] === 'string') {
|
||||
return meta[key].trim();
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const setPatternEditorNFields = (mode, data) => {
|
||||
const meta = data && typeof data === 'object' ? data : {};
|
||||
let visible = 0;
|
||||
const grid = patternCreateNSection && patternCreateNSection.querySelector('.n-params-grid');
|
||||
const h3 = patternCreateNSection && patternCreateNSection.querySelector('h3');
|
||||
|
||||
for (let i = 1; i <= 8; i += 1) {
|
||||
const key = `n${i}`;
|
||||
const labelEl = document.querySelector(`label[for="pattern-create-${key}"]`);
|
||||
const inputEl = document.getElementById(`pattern-create-${key}`);
|
||||
const groupEl = labelEl ? labelEl.closest('.n-param-group') : null;
|
||||
|
||||
if (mode === 'create') {
|
||||
if (labelEl) {
|
||||
labelEl.textContent = `${key}:`;
|
||||
labelEl.style.display = '';
|
||||
}
|
||||
if (inputEl) {
|
||||
inputEl.value = '';
|
||||
inputEl.placeholder = 'Readable name (optional)';
|
||||
inputEl.removeAttribute('aria-label');
|
||||
}
|
||||
if (groupEl) {
|
||||
groupEl.style.display = '';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const readable = nReadableStringFromMeta(meta, key);
|
||||
const show = Boolean(readable);
|
||||
if (labelEl) {
|
||||
labelEl.textContent = '';
|
||||
labelEl.style.display = 'none';
|
||||
}
|
||||
if (inputEl) {
|
||||
inputEl.value = show ? readable : '';
|
||||
inputEl.placeholder = '';
|
||||
if (show) {
|
||||
inputEl.setAttribute('aria-label', readable);
|
||||
} else {
|
||||
inputEl.removeAttribute('aria-label');
|
||||
inputEl.value = '';
|
||||
}
|
||||
}
|
||||
if (groupEl) {
|
||||
groupEl.style.display = show ? '' : 'none';
|
||||
}
|
||||
if (show) {
|
||||
visible += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === 'create') {
|
||||
if (patternCreateNEmpty) {
|
||||
patternCreateNEmpty.style.display = 'none';
|
||||
}
|
||||
if (grid) {
|
||||
grid.style.display = '';
|
||||
}
|
||||
if (h3) {
|
||||
h3.style.display = '';
|
||||
}
|
||||
if (patternCreateNSection) {
|
||||
patternCreateNSection.style.display = '';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (patternCreateNEmpty) {
|
||||
patternCreateNEmpty.style.display = visible === 0 ? '' : 'none';
|
||||
}
|
||||
if (grid) {
|
||||
grid.style.display = visible === 0 ? 'none' : '';
|
||||
}
|
||||
if (h3) {
|
||||
h3.style.display = visible === 0 ? 'none' : '';
|
||||
}
|
||||
};
|
||||
|
||||
const readFileAsText = (file) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result || ''));
|
||||
reader.onerror = () => reject(reader.error || new Error('read failed'));
|
||||
reader.readAsText(file);
|
||||
});
|
||||
|
||||
const collectCreatePayload = async () => {
|
||||
const name = patternCreateName ? patternCreateName.value.trim() : '';
|
||||
if (!name) {
|
||||
throw new Error('Pattern name is required.');
|
||||
}
|
||||
let code = '';
|
||||
const fileInput = patternCreateFile && patternCreateFile.files && patternCreateFile.files[0];
|
||||
if (fileInput) {
|
||||
code = await readFileAsText(fileInput);
|
||||
} else if (patternCreateCode && patternCreateCode.value.trim()) {
|
||||
code = patternCreateCode.value;
|
||||
}
|
||||
if (!code.trim()) {
|
||||
throw new Error('Choose a .py file or paste source code.');
|
||||
}
|
||||
|
||||
const payload = {
|
||||
name,
|
||||
code,
|
||||
min_delay: parseInt(patternCreateMinDelay && patternCreateMinDelay.value, 10) || 0,
|
||||
max_delay: parseInt(patternCreateMaxDelay && patternCreateMaxDelay.value, 10) || 0,
|
||||
max_colors: parseInt(patternCreateMaxColors && patternCreateMaxColors.value, 10) || 0,
|
||||
overwrite: !!(patternCreateOverwrite && patternCreateOverwrite.checked),
|
||||
};
|
||||
|
||||
patternCreateN.forEach((el, idx) => {
|
||||
const key = `n${idx + 1}`;
|
||||
if (el && el.value.trim()) {
|
||||
payload[key] = el.value.trim();
|
||||
}
|
||||
});
|
||||
|
||||
return payload;
|
||||
};
|
||||
|
||||
const resetCreateForm = () => {
|
||||
if (patternCreateName) patternCreateName.value = '';
|
||||
if (patternCreateFile) patternCreateFile.value = '';
|
||||
if (patternCreateCode) patternCreateCode.value = '';
|
||||
if (patternCreateMinDelay) patternCreateMinDelay.value = '10';
|
||||
if (patternCreateMaxDelay) patternCreateMaxDelay.value = '10000';
|
||||
if (patternCreateMaxColors) patternCreateMaxColors.value = '10';
|
||||
patternCreateN.forEach((el) => {
|
||||
if (el) el.value = '';
|
||||
});
|
||||
if (patternCreateOverwrite) patternCreateOverwrite.checked = true;
|
||||
setPatternEditorNFields('create', {});
|
||||
};
|
||||
|
||||
if (patternCreateBtn) {
|
||||
patternCreateBtn.addEventListener('click', async () => {
|
||||
try {
|
||||
const payload = await collectCreatePayload();
|
||||
const response = await fetch('/patterns/driver', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error((data && data.error) || 'Create failed');
|
||||
}
|
||||
alert(data.message || 'Pattern created.');
|
||||
resetCreateForm();
|
||||
if (patternEditorModal) {
|
||||
patternEditorModal.classList.remove('active');
|
||||
}
|
||||
await loadPatterns();
|
||||
} catch (e) {
|
||||
console.error('Create pattern failed:', e);
|
||||
alert(e.message || 'Failed to create pattern.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** on/off are implemented in driver firmware (presets.py), not as OTA ``.py`` files. */
|
||||
const FIRMWARE_BUILTIN_PATTERNS = new Set(['on', 'off']);
|
||||
|
||||
const isFirmwareBuiltinPattern = (patternName) => {
|
||||
const id = String(patternName || '')
|
||||
.trim()
|
||||
.replace(/\.py$/i, '')
|
||||
.toLowerCase();
|
||||
return FIRMWARE_BUILTIN_PATTERNS.has(id);
|
||||
};
|
||||
|
||||
const sendPatternToDevices = async (patternName) => {
|
||||
const response = await fetch(`/patterns/${encodeURIComponent(patternName)}/send`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error((data && data.error) || 'Failed to send pattern');
|
||||
}
|
||||
const sentCount = data && typeof data.sent_count === 'number' ? data.sent_count : null;
|
||||
if (sentCount === null) {
|
||||
alert(`Sent "${patternName}" to devices.`);
|
||||
} else {
|
||||
alert(`Sent "${patternName}" to ${sentCount} device(s).`);
|
||||
}
|
||||
};
|
||||
|
||||
const loadPatternMetadata = async (patternName, fallbackData) => {
|
||||
const raw = String(patternName || '').trim();
|
||||
const norm = raw.endsWith('.py') ? raw.slice(0, -3).trim() : raw;
|
||||
try {
|
||||
const response = await fetch('/patterns/definitions', {
|
||||
cache: 'no-store',
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to load pattern definitions');
|
||||
}
|
||||
const definitions = await response.json();
|
||||
if (definitions && typeof definitions === 'object') {
|
||||
if (definitions[raw]) {
|
||||
return definitions[raw];
|
||||
}
|
||||
if (norm && definitions[norm]) {
|
||||
return definitions[norm];
|
||||
}
|
||||
if (norm) {
|
||||
const lower = norm.toLowerCase();
|
||||
const matched = Object.keys(definitions).find(
|
||||
(k) => String(k).toLowerCase() === lower,
|
||||
);
|
||||
if (matched) {
|
||||
return definitions[matched];
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Load pattern definitions failed:', error);
|
||||
}
|
||||
return fallbackData || {};
|
||||
};
|
||||
|
||||
const loadPatternIntoEditor = async (patternName, fallbackData) => {
|
||||
const data = await loadPatternMetadata(patternName, fallbackData);
|
||||
if (patternCreateName) {
|
||||
patternCreateName.value = patternName;
|
||||
}
|
||||
if (patternCreateMinDelay) {
|
||||
patternCreateMinDelay.value =
|
||||
data && data.min_delay !== undefined ? String(data.min_delay) : '10';
|
||||
}
|
||||
if (patternCreateMaxDelay) {
|
||||
patternCreateMaxDelay.value =
|
||||
data && data.max_delay !== undefined ? String(data.max_delay) : '10000';
|
||||
}
|
||||
if (patternCreateMaxColors) {
|
||||
patternCreateMaxColors.value =
|
||||
data && data.max_colors !== undefined ? String(data.max_colors) : '10';
|
||||
}
|
||||
setPatternEditorNFields('edit', data);
|
||||
if (patternCreateOverwrite) {
|
||||
patternCreateOverwrite.checked = true;
|
||||
}
|
||||
if (patternCreateFile) {
|
||||
patternCreateFile.value = '';
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = String(patternName || '').trim();
|
||||
const fileSegment = /\.py$/i.test(raw) ? raw : `${raw}.py`;
|
||||
const response = await fetch(`/patterns/ota/file/${encodeURIComponent(fileSegment)}`, {
|
||||
headers: { Accept: 'text/plain' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to load pattern file');
|
||||
}
|
||||
const source = await response.text();
|
||||
if (patternCreateCode) {
|
||||
patternCreateCode.value = source || '';
|
||||
patternCreateCode.focus();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Load pattern source failed:', error);
|
||||
alert('Could not load pattern source into editor.');
|
||||
}
|
||||
};
|
||||
|
||||
const renderPatterns = (patterns) => {
|
||||
patternsList.innerHTML = '';
|
||||
const entries = Object.entries(patterns || {});
|
||||
if (!entries.length) {
|
||||
const empty = document.createElement('p');
|
||||
empty.className = 'muted-text';
|
||||
empty.textContent = 'No patterns found.';
|
||||
patternsList.appendChild(empty);
|
||||
return;
|
||||
}
|
||||
entries.forEach(([patternName, data]) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'profiles-row';
|
||||
|
||||
const label = document.createElement('span');
|
||||
label.textContent = patternName;
|
||||
|
||||
row.appendChild(label);
|
||||
|
||||
if (isFirmwareBuiltinPattern(patternName)) {
|
||||
const note = document.createElement('span');
|
||||
note.className = 'muted-text';
|
||||
note.style.fontSize = '0.85em';
|
||||
note.textContent = 'Built-in (no OTA module)';
|
||||
row.appendChild(note);
|
||||
} else {
|
||||
const sendBtn = document.createElement('button');
|
||||
sendBtn.className = 'btn btn-primary btn-small';
|
||||
sendBtn.textContent = 'Send';
|
||||
sendBtn.addEventListener('click', async () => {
|
||||
try {
|
||||
await sendPatternToDevices(patternName);
|
||||
} catch (error) {
|
||||
console.error('Send pattern failed:', error);
|
||||
alert(error.message || 'Failed to send pattern.');
|
||||
}
|
||||
});
|
||||
|
||||
const editBtn = document.createElement('button');
|
||||
editBtn.className = 'btn btn-secondary btn-small';
|
||||
editBtn.textContent = 'Edit';
|
||||
editBtn.addEventListener('click', async () => {
|
||||
if (patternEditorModal) {
|
||||
patternEditorModal.classList.add('active');
|
||||
}
|
||||
await loadPatternIntoEditor(patternName, data || {});
|
||||
});
|
||||
|
||||
row.appendChild(editBtn);
|
||||
row.appendChild(sendBtn);
|
||||
}
|
||||
|
||||
patternsList.appendChild(row);
|
||||
});
|
||||
};
|
||||
|
||||
async function loadPatterns() {
|
||||
patternsList.innerHTML = '';
|
||||
const loading = document.createElement('p');
|
||||
loading.className = 'muted-text';
|
||||
loading.textContent = 'Loading patterns...';
|
||||
patternsList.appendChild(loading);
|
||||
|
||||
try {
|
||||
const response = await fetch('/patterns', {
|
||||
cache: 'no-store',
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to load patterns');
|
||||
}
|
||||
const patterns = await response.json();
|
||||
renderPatterns(patterns);
|
||||
} catch (error) {
|
||||
console.error('Load patterns failed:', error);
|
||||
patternsList.innerHTML = '';
|
||||
const errorMessage = document.createElement('p');
|
||||
errorMessage.className = 'muted-text';
|
||||
errorMessage.textContent = 'Failed to load patterns.';
|
||||
patternsList.appendChild(errorMessage);
|
||||
}
|
||||
}
|
||||
|
||||
const openModal = () => {
|
||||
patternsModal.classList.add('active');
|
||||
loadPatterns();
|
||||
};
|
||||
|
||||
const closeModal = () => {
|
||||
patternsModal.classList.remove('active');
|
||||
};
|
||||
|
||||
patternsButton.addEventListener('click', openModal);
|
||||
if (patternAddButton) {
|
||||
patternAddButton.addEventListener('click', () => {
|
||||
resetCreateForm();
|
||||
if (patternEditorModal) {
|
||||
patternEditorModal.classList.add('active');
|
||||
}
|
||||
});
|
||||
}
|
||||
if (patternEditorCloseButton) {
|
||||
patternEditorCloseButton.addEventListener('click', () => {
|
||||
if (patternEditorModal) {
|
||||
patternEditorModal.classList.remove('active');
|
||||
}
|
||||
});
|
||||
}
|
||||
if (patternsCloseButton) {
|
||||
patternsCloseButton.addEventListener('click', closeModal);
|
||||
}
|
||||
|
||||
if (patternSendAllButton) {
|
||||
patternSendAllButton.addEventListener('click', async () => {
|
||||
const section = document.querySelector('.presets-section[data-zone-id]');
|
||||
const zoneId = section ? section.dataset.zoneId : null;
|
||||
if (!zoneId) {
|
||||
alert('Could not determine current zone.');
|
||||
return;
|
||||
}
|
||||
const deviceNames = tabDeviceNamesFromSection(section);
|
||||
if (!deviceNames.length) {
|
||||
alert('No devices found in the current zone.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const [zoneRes, presetsRes] = await Promise.all([
|
||||
fetch(`/zones/${zoneId}`, { headers: { Accept: 'application/json' } }),
|
||||
fetch('/presets', { headers: { Accept: 'application/json' } }),
|
||||
]);
|
||||
if (!zoneRes.ok || !presetsRes.ok) {
|
||||
throw new Error('Failed to load zone presets');
|
||||
}
|
||||
const zoneData = await zoneRes.json();
|
||||
const allPresetsRaw = await presetsRes.json();
|
||||
const allPresets = await filterPresetsForCurrentProfile(allPresetsRaw);
|
||||
const zonePresetIds = Array.isArray(zoneData.presets_flat)
|
||||
? zoneData.presets_flat.map((id) => String(id))
|
||||
: [];
|
||||
if (!zonePresetIds.length) {
|
||||
alert('No presets found in this zone.');
|
||||
return;
|
||||
}
|
||||
|
||||
const wirePresets = {};
|
||||
zonePresetIds.forEach((presetId) => {
|
||||
const preset = allPresets[presetId];
|
||||
if (!preset) {
|
||||
return;
|
||||
}
|
||||
const colors = Array.isArray(preset.colors) && preset.colors.length
|
||||
? preset.colors
|
||||
: ['#FFFFFF'];
|
||||
wirePresets[presetId] = {
|
||||
pattern: preset.pattern || 'off',
|
||||
colors,
|
||||
delay: typeof preset.delay === 'number' ? preset.delay : 100,
|
||||
brightness: typeof preset.brightness === 'number'
|
||||
? preset.brightness
|
||||
: (typeof preset.br === 'number' ? preset.br : 127),
|
||||
auto: typeof preset.auto === 'boolean' ? preset.auto : true,
|
||||
n1: coercePresetInt(preset.n1),
|
||||
n2: coercePresetInt(preset.n2),
|
||||
n3: coercePresetInt(preset.n3),
|
||||
n4: coercePresetInt(preset.n4),
|
||||
n5: coercePresetInt(preset.n5),
|
||||
n6: coercePresetInt(preset.n6),
|
||||
};
|
||||
});
|
||||
if (!Object.keys(wirePresets).length) {
|
||||
alert('No matching presets found to send.');
|
||||
return;
|
||||
}
|
||||
|
||||
const select = {};
|
||||
deviceNames.forEach((name) => {
|
||||
if (name) {
|
||||
select[name] = zonePresetIds.slice();
|
||||
}
|
||||
});
|
||||
const targetMacs =
|
||||
typeof window.tabsManager !== 'undefined' &&
|
||||
typeof window.tabsManager.resolveTabDeviceMacs === 'function'
|
||||
? await window.tabsManager.resolveTabDeviceMacs(deviceNames)
|
||||
: [];
|
||||
|
||||
const sequence = [
|
||||
{ v: '1', clear_presets: true, save: true },
|
||||
{ v: '1', presets: wirePresets, save: true },
|
||||
];
|
||||
if (Object.keys(select).length) {
|
||||
sequence.push({ v: '1', select });
|
||||
}
|
||||
await postDriverSequence(sequence, targetMacs, 0.05);
|
||||
} catch (error) {
|
||||
console.error('Send all patterns failed:', error);
|
||||
alert('Failed to send all patterns.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,297 @@
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const profilesButton = document.getElementById("profiles-btn");
|
||||
const profilesModal = document.getElementById("profiles-modal");
|
||||
const profilesCloseButton = document.getElementById("profiles-close-btn");
|
||||
const profilesList = document.getElementById("profiles-list");
|
||||
const newProfileInput = document.getElementById("new-profile-name");
|
||||
const newProfileSeedDjInput = document.getElementById("new-profile-seed-dj");
|
||||
const createProfileButton = document.getElementById("create-profile-btn");
|
||||
|
||||
if (!profilesButton || !profilesModal || !profilesList) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isEditModeActive = () => {
|
||||
const toggle = document.querySelector('.ui-mode-toggle');
|
||||
return !!(toggle && toggle.getAttribute('aria-pressed') === 'true');
|
||||
};
|
||||
|
||||
const updateProfileEditorControlsVisibility = () => {
|
||||
const editMode = isEditModeActive();
|
||||
const actions = profilesModal.querySelector('.profiles-actions');
|
||||
if (actions) {
|
||||
actions.style.display = editMode ? '' : 'none';
|
||||
}
|
||||
};
|
||||
|
||||
const openModal = () => {
|
||||
profilesModal.classList.add("active");
|
||||
updateProfileEditorControlsVisibility();
|
||||
loadProfiles();
|
||||
};
|
||||
|
||||
const closeModal = () => {
|
||||
profilesModal.classList.remove("active");
|
||||
};
|
||||
|
||||
const refreshTabsForActiveProfile = async () => {
|
||||
// Clear stale current zone so zone controller falls back to first zone of applied profile.
|
||||
document.cookie = "current_zone=; path=/; max-age=0";
|
||||
|
||||
if (window.tabsManager && typeof window.tabsManager.loadTabs === "function") {
|
||||
await window.tabsManager.loadTabs();
|
||||
}
|
||||
if (window.tabsManager && typeof window.tabsManager.loadTabsModal === "function") {
|
||||
await window.tabsManager.loadTabsModal();
|
||||
}
|
||||
};
|
||||
|
||||
const renderProfiles = (profiles, currentProfileId) => {
|
||||
profilesList.innerHTML = "";
|
||||
let entries = [];
|
||||
|
||||
if (Array.isArray(profiles)) {
|
||||
entries = profiles.map((profileId) => [profileId, {}]);
|
||||
} else if (profiles && typeof profiles === "object") {
|
||||
// Make sure we're iterating over profile entries, not metadata
|
||||
entries = Object.entries(profiles).filter(([key]) => {
|
||||
// Skip metadata keys like 'current_profile_id' if they exist
|
||||
return key !== 'current_profile_id' && key !== 'profiles';
|
||||
});
|
||||
}
|
||||
|
||||
if (entries.length === 0) {
|
||||
const empty = document.createElement("p");
|
||||
empty.className = "muted-text";
|
||||
empty.textContent = "No profiles found.";
|
||||
profilesList.appendChild(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
const editMode = isEditModeActive();
|
||||
entries.forEach(([profileId, profile]) => {
|
||||
const row = document.createElement("div");
|
||||
row.className = "profiles-row";
|
||||
|
||||
const label = document.createElement("span");
|
||||
label.textContent = (profile && profile.name) || profileId;
|
||||
if (String(profileId) === String(currentProfileId)) {
|
||||
label.textContent = `✓ ${label.textContent}`;
|
||||
label.style.fontWeight = "bold";
|
||||
label.style.color = "#FFD700";
|
||||
}
|
||||
|
||||
const applyButton = document.createElement("button");
|
||||
applyButton.className = "btn btn-secondary btn-small profiles-apply-btn";
|
||||
applyButton.textContent = "Apply";
|
||||
applyButton.addEventListener("click", async () => {
|
||||
try {
|
||||
const response = await fetch(`/profiles/${profileId}/apply`, {
|
||||
method: "POST",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to apply profile");
|
||||
}
|
||||
await loadProfiles();
|
||||
await refreshTabsForActiveProfile();
|
||||
} catch (error) {
|
||||
console.error("Apply profile failed:", error);
|
||||
alert("Failed to apply profile.");
|
||||
}
|
||||
});
|
||||
|
||||
const cloneButton = document.createElement("button");
|
||||
cloneButton.className = "btn btn-secondary btn-small";
|
||||
cloneButton.textContent = "Clone";
|
||||
cloneButton.addEventListener("click", async () => {
|
||||
const baseName = (profile && profile.name) || profileId;
|
||||
const suggested = `${baseName}`;
|
||||
const name = prompt("New profile name:", suggested);
|
||||
if (name === null) {
|
||||
return;
|
||||
}
|
||||
const trimmed = String(name).trim();
|
||||
if (!trimmed) {
|
||||
alert("Profile name cannot be empty.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch(`/profiles/${profileId}/clone`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||||
body: JSON.stringify({ name: trimmed }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to clone profile");
|
||||
}
|
||||
const data = await response.json().catch(() => null);
|
||||
let newProfileId = null;
|
||||
if (data && typeof data === "object") {
|
||||
if (data.id) {
|
||||
newProfileId = String(data.id);
|
||||
} else {
|
||||
const ids = Object.keys(data);
|
||||
if (ids.length > 0) {
|
||||
newProfileId = String(ids[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (newProfileId) {
|
||||
await fetch(`/profiles/${newProfileId}/apply`, {
|
||||
method: "POST",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
}
|
||||
await loadProfiles();
|
||||
await refreshTabsForActiveProfile();
|
||||
} catch (error) {
|
||||
console.error("Clone profile failed:", error);
|
||||
alert("Failed to clone profile.");
|
||||
}
|
||||
});
|
||||
|
||||
const deleteButton = document.createElement("button");
|
||||
deleteButton.className = "btn btn-danger btn-small";
|
||||
deleteButton.textContent = "Delete";
|
||||
deleteButton.addEventListener("click", async () => {
|
||||
const confirmed = confirm(`Delete profile "${label.textContent}"?`);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch(`/profiles/${profileId}`, {
|
||||
method: "DELETE",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to delete profile");
|
||||
}
|
||||
await loadProfiles();
|
||||
} catch (error) {
|
||||
console.error("Delete profile failed:", error);
|
||||
alert("Failed to delete profile.");
|
||||
}
|
||||
});
|
||||
|
||||
row.appendChild(label);
|
||||
row.appendChild(applyButton);
|
||||
if (editMode) {
|
||||
row.appendChild(cloneButton);
|
||||
row.appendChild(deleteButton);
|
||||
}
|
||||
profilesList.appendChild(row);
|
||||
});
|
||||
};
|
||||
|
||||
const loadProfiles = async () => {
|
||||
profilesList.innerHTML = "";
|
||||
const loading = document.createElement("p");
|
||||
loading.className = "muted-text";
|
||||
loading.textContent = "Loading profiles...";
|
||||
profilesList.appendChild(loading);
|
||||
|
||||
try {
|
||||
const response = await fetch("/profiles", {
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to load profiles");
|
||||
}
|
||||
const data = await response.json();
|
||||
// Handle both old format (just profiles object) and new format (with current_profile_id)
|
||||
const profiles = data.profiles || data;
|
||||
const currentProfileId = data.current_profile_id || null;
|
||||
renderProfiles(profiles, currentProfileId);
|
||||
} catch (error) {
|
||||
console.error("Load profiles failed:", error);
|
||||
profilesList.innerHTML = "";
|
||||
const errorMessage = document.createElement("p");
|
||||
errorMessage.className = "muted-text";
|
||||
errorMessage.textContent = "Failed to load profiles.";
|
||||
profilesList.appendChild(errorMessage);
|
||||
}
|
||||
};
|
||||
|
||||
const createProfile = async () => {
|
||||
if (!isEditModeActive()) {
|
||||
return;
|
||||
}
|
||||
if (!newProfileInput) {
|
||||
return;
|
||||
}
|
||||
const name = newProfileInput.value.trim();
|
||||
if (!name) {
|
||||
alert("Profile name cannot be empty.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch("/profiles", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name,
|
||||
seed_dj_zone: !!(newProfileSeedDjInput && newProfileSeedDjInput.checked),
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to create profile");
|
||||
}
|
||||
const data = await response.json().catch(() => null);
|
||||
let newProfileId = null;
|
||||
if (data && typeof data === "object") {
|
||||
if (data.id) {
|
||||
newProfileId = String(data.id);
|
||||
} else {
|
||||
const ids = Object.keys(data);
|
||||
if (ids.length > 0) {
|
||||
newProfileId = String(ids[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (newProfileId) {
|
||||
await fetch(`/profiles/${newProfileId}/apply`, {
|
||||
method: "POST",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
newProfileInput.value = "";
|
||||
if (newProfileSeedDjInput) {
|
||||
newProfileSeedDjInput.checked = false;
|
||||
}
|
||||
await loadProfiles();
|
||||
await refreshTabsForActiveProfile();
|
||||
} catch (error) {
|
||||
console.error("Create profile failed:", error);
|
||||
alert("Failed to create profile.");
|
||||
}
|
||||
};
|
||||
|
||||
profilesButton.addEventListener("click", openModal);
|
||||
if (profilesCloseButton) {
|
||||
profilesCloseButton.addEventListener("click", closeModal);
|
||||
}
|
||||
if (createProfileButton) {
|
||||
createProfileButton.addEventListener("click", createProfile);
|
||||
}
|
||||
if (newProfileInput) {
|
||||
newProfileInput.addEventListener("keypress", (event) => {
|
||||
if (event.key === "Enter") {
|
||||
createProfile();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Keep modal controls in sync with run/edit mode.
|
||||
document.querySelectorAll('.ui-mode-toggle').forEach((btn) => {
|
||||
btn.addEventListener('click', () => {
|
||||
if (profilesModal.classList.contains('active')) {
|
||||
updateProfileEditorControlsVisibility();
|
||||
loadProfiles();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,296 @@
|
||||
// Sequences: timed preset chains per zone, run by the Pi-side engine.
|
||||
|
||||
const SEQUENCES_POLL_MS = 1000;
|
||||
let sequencesPollTimer = null;
|
||||
|
||||
async function fetchJson(url) {
|
||||
const res = await fetch(url, { headers: { Accept: 'application/json' }, credentials: 'same-origin' });
|
||||
if (!res.ok) throw new Error(`${url}: ${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async function loadSequenceContext() {
|
||||
const [sequences, status, zonesData, presets] = await Promise.all([
|
||||
fetchJson('/sequences'),
|
||||
fetchJson('/sequences/status'),
|
||||
fetchJson('/zones'),
|
||||
fetchJson('/presets'),
|
||||
]);
|
||||
const order = Array.isArray(zonesData.zone_order) ? zonesData.zone_order : [];
|
||||
const zones = {};
|
||||
order.forEach((zid) => {
|
||||
if (zonesData.zones && zonesData.zones[zid]) zones[zid] = zonesData.zones[zid];
|
||||
});
|
||||
return { sequences, status, zones, presets };
|
||||
}
|
||||
|
||||
function stepSummary(seq, presets, state) {
|
||||
const steps = seq.steps || [];
|
||||
const total = steps.reduce((s, st) => s + Number(st.duration_s || 0), 0);
|
||||
let text = `${steps.length} step${steps.length === 1 ? '' : 's'} · ${total.toFixed(1)} s`;
|
||||
text += seq.loop ? (seq.repeat_count ? ` · ×${seq.repeat_count}` : ' · loop') : ' · once';
|
||||
if (state && state.running) {
|
||||
const p = presets[state.preset_id];
|
||||
text += ` · ▶ step ${state.step_index + 1}${p ? ` (${p.name})` : ''}`;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function renderSequencesList(ctx) {
|
||||
const container = document.getElementById('sequences-list-modal');
|
||||
if (!container) return;
|
||||
const editMode = typeof isEditModeActive === 'function' && isEditModeActive();
|
||||
container.innerHTML = '';
|
||||
const ids = Object.keys(ctx.sequences || {}).filter((id) => {
|
||||
const z = ctx.sequences[id].zone_id;
|
||||
return z == null || ctx.zones[z]; // only this profile's zones (plus unassigned)
|
||||
});
|
||||
if (ids.length === 0) {
|
||||
const p = document.createElement('p');
|
||||
p.className = 'muted-text';
|
||||
p.textContent = 'No sequences yet.';
|
||||
container.appendChild(p);
|
||||
return;
|
||||
}
|
||||
ids.forEach((id) => {
|
||||
const seq = ctx.sequences[id];
|
||||
const state = ctx.status[id];
|
||||
const running = !!(state && state.running);
|
||||
const zone = ctx.zones[seq.zone_id];
|
||||
|
||||
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';
|
||||
|
||||
const label = document.createElement('span');
|
||||
label.style.flex = '1';
|
||||
const name = document.createElement('strong');
|
||||
name.textContent = seq.name || `Sequence ${id}`;
|
||||
const meta = document.createElement('span');
|
||||
meta.className = 'muted-text';
|
||||
meta.textContent = ` ${zone ? zone.name : 'no zone'} · ${stepSummary(seq, ctx.presets, state)}`;
|
||||
label.append(name, meta);
|
||||
|
||||
const playBtn = document.createElement('button');
|
||||
playBtn.type = 'button';
|
||||
playBtn.className = running ? 'btn btn-danger btn-small' : 'btn btn-primary btn-small';
|
||||
playBtn.textContent = running ? 'Stop' : 'Play';
|
||||
playBtn.disabled = !zone || !(seq.steps || []).length;
|
||||
playBtn.addEventListener('click', async () => {
|
||||
playBtn.disabled = true;
|
||||
const res = await fetch(`/sequences/${encodeURIComponent(id)}/${running ? 'stop' : 'play'}`, {
|
||||
method: 'POST', credentials: 'same-origin',
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
alert(data.error || 'Failed');
|
||||
}
|
||||
refreshSequencesList();
|
||||
});
|
||||
row.append(label, playBtn);
|
||||
|
||||
if (editMode) {
|
||||
const editBtn = document.createElement('button');
|
||||
editBtn.type = 'button';
|
||||
editBtn.className = 'btn btn-secondary btn-small';
|
||||
editBtn.textContent = 'Edit';
|
||||
editBtn.addEventListener('click', () => openSequenceEditor(id, seq, ctx));
|
||||
const delBtn = document.createElement('button');
|
||||
delBtn.type = 'button';
|
||||
delBtn.className = 'btn btn-danger btn-small';
|
||||
delBtn.textContent = 'Delete';
|
||||
delBtn.addEventListener('click', async () => {
|
||||
if (!confirm(`Delete sequence "${seq.name}"?`)) return;
|
||||
await fetch(`/sequences/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
refreshSequencesList();
|
||||
});
|
||||
row.append(editBtn, delBtn);
|
||||
}
|
||||
container.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
let lastSequenceCtx = null;
|
||||
|
||||
async function refreshSequencesList() {
|
||||
try {
|
||||
lastSequenceCtx = await loadSequenceContext();
|
||||
renderSequencesList(lastSequenceCtx);
|
||||
} catch (e) {
|
||||
const container = document.getElementById('sequences-list-modal');
|
||||
if (container && !lastSequenceCtx) container.textContent = 'Failed to load sequences.';
|
||||
}
|
||||
}
|
||||
|
||||
function stopSequencesPoll() {
|
||||
if (sequencesPollTimer != null) {
|
||||
clearInterval(sequencesPollTimer);
|
||||
sequencesPollTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function addStepRow(presets, step) {
|
||||
const container = document.getElementById('edit-sequence-steps');
|
||||
const row = document.createElement('div');
|
||||
row.className = 'engine-step-row';
|
||||
|
||||
const select = document.createElement('select');
|
||||
select.className = 'engine-step-preset';
|
||||
Object.entries(presets || {}).forEach(([pid, p]) => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = pid;
|
||||
opt.textContent = p.name || pid;
|
||||
select.appendChild(opt);
|
||||
});
|
||||
if (step && step.preset_id != null) select.value = String(step.preset_id);
|
||||
|
||||
const dur = document.createElement('input');
|
||||
dur.type = 'number';
|
||||
dur.min = '0.5';
|
||||
dur.max = '600';
|
||||
dur.step = '0.5';
|
||||
dur.className = 'engine-step-duration';
|
||||
dur.value = step && step.duration_s != null ? step.duration_s : 5;
|
||||
dur.title = 'Seconds';
|
||||
|
||||
const unit = document.createElement('span');
|
||||
unit.className = 'muted-text';
|
||||
unit.textContent = 's';
|
||||
|
||||
const mk = (text, title, fn) => {
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button';
|
||||
b.className = 'btn btn-secondary btn-small';
|
||||
b.textContent = text;
|
||||
b.title = title;
|
||||
b.addEventListener('click', fn);
|
||||
return b;
|
||||
};
|
||||
const up = mk('↑', 'Move up', () => { if (row.previousElementSibling) container.insertBefore(row, row.previousElementSibling); });
|
||||
const down = mk('↓', 'Move down', () => { if (row.nextElementSibling) container.insertBefore(row.nextElementSibling, row); });
|
||||
const del = mk('✕', 'Remove step', () => row.remove());
|
||||
|
||||
row.append(select, dur, unit, up, down, del);
|
||||
container.appendChild(row);
|
||||
}
|
||||
|
||||
function openSequenceEditor(id, seq, ctx) {
|
||||
const s = seq || { name: '', zone_id: null, loop: true, repeat_count: 0, steps: [] };
|
||||
document.getElementById('edit-sequence-title').textContent = id ? 'Edit sequence' : 'New sequence';
|
||||
document.getElementById('edit-sequence-id').value = id || '';
|
||||
document.getElementById('edit-sequence-name').value = s.name || '';
|
||||
const zoneSel = document.getElementById('edit-sequence-zone');
|
||||
zoneSel.innerHTML = '';
|
||||
Object.entries(ctx.zones).forEach(([zid, z]) => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = zid;
|
||||
opt.textContent = z.name || zid;
|
||||
zoneSel.appendChild(opt);
|
||||
});
|
||||
const currentZone = s.zone_id
|
||||
|| (window.zonesManager && window.zonesManager.getCurrentZoneId && window.zonesManager.getCurrentZoneId());
|
||||
if (currentZone && ctx.zones[currentZone]) zoneSel.value = String(currentZone);
|
||||
document.getElementById('edit-sequence-loop').checked = s.loop !== false;
|
||||
document.getElementById('edit-sequence-repeat').value = s.repeat_count || 0;
|
||||
const steps = document.getElementById('edit-sequence-steps');
|
||||
steps.innerHTML = '';
|
||||
(s.steps || []).forEach((st) => addStepRow(ctx.presets, st));
|
||||
if (!(s.steps || []).length) addStepRow(ctx.presets, null);
|
||||
document.getElementById('edit-sequence-error').hidden = true;
|
||||
document.getElementById('edit-sequence-modal').classList.add('active');
|
||||
}
|
||||
|
||||
function readSequenceForm() {
|
||||
const steps = [];
|
||||
document.querySelectorAll('#edit-sequence-steps .engine-step-row').forEach((row) => {
|
||||
const pid = row.querySelector('.engine-step-preset').value;
|
||||
const dur = Number(row.querySelector('.engine-step-duration').value);
|
||||
if (pid) steps.push({ preset_id: pid, duration_s: Number.isFinite(dur) ? dur : 5 });
|
||||
});
|
||||
return {
|
||||
name: document.getElementById('edit-sequence-name').value.trim(),
|
||||
zone_id: document.getElementById('edit-sequence-zone').value || null,
|
||||
loop: document.getElementById('edit-sequence-loop').checked,
|
||||
repeat_count: Number(document.getElementById('edit-sequence-repeat').value) || 0,
|
||||
steps,
|
||||
};
|
||||
}
|
||||
|
||||
// Tell the engine a preset was picked on a zone: renders it on the zone's pixel
|
||||
// outputs and stops any sequence there. ESP32s were already sent the preset
|
||||
// by presets.js, so the engine leaves them alone (drivers: false).
|
||||
async function notifyEngineZonePlay(zoneId, presetId) {
|
||||
if (!zoneId || !presetId) return;
|
||||
try {
|
||||
await fetch(`/zones/${encodeURIComponent(zoneId)}/play`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify({ preset_id: String(presetId), drivers: false }),
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('Engine zone play failed:', e);
|
||||
}
|
||||
}
|
||||
window.notifyEngineZonePlay = notifyEngineZonePlay;
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const btn = document.getElementById('sequences-btn');
|
||||
const modal = document.getElementById('sequences-modal');
|
||||
const editModal = document.getElementById('edit-sequence-modal');
|
||||
const form = document.getElementById('edit-sequence-form');
|
||||
if (!btn || !modal || !form) return;
|
||||
|
||||
btn.addEventListener('click', () => {
|
||||
modal.classList.add('active');
|
||||
refreshSequencesList();
|
||||
stopSequencesPoll();
|
||||
sequencesPollTimer = setInterval(refreshSequencesList, SEQUENCES_POLL_MS);
|
||||
});
|
||||
document.getElementById('sequences-close-btn').addEventListener('click', () => {
|
||||
modal.classList.remove('active');
|
||||
});
|
||||
new MutationObserver(() => {
|
||||
if (!modal.classList.contains('active')) stopSequencesPoll();
|
||||
}).observe(modal, { attributes: true, attributeFilter: ['class'] });
|
||||
|
||||
document.getElementById('sequence-add-btn').addEventListener('click', async () => {
|
||||
const ctx = lastSequenceCtx || await loadSequenceContext();
|
||||
openSequenceEditor(null, null, ctx);
|
||||
});
|
||||
document.getElementById('edit-sequence-add-step-btn').addEventListener('click', () => {
|
||||
addStepRow((lastSequenceCtx && lastSequenceCtx.presets) || {}, null);
|
||||
});
|
||||
document.getElementById('edit-sequence-close-btn').addEventListener('click', () => {
|
||||
editModal.classList.remove('active');
|
||||
});
|
||||
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const id = document.getElementById('edit-sequence-id').value;
|
||||
const err = document.getElementById('edit-sequence-error');
|
||||
err.hidden = true;
|
||||
const body = readSequenceForm();
|
||||
if (!body.steps.length) {
|
||||
err.textContent = 'Add at least one step.';
|
||||
err.hidden = false;
|
||||
return;
|
||||
}
|
||||
const res = await fetch(id ? `/sequences/${encodeURIComponent(id)}` : '/sequences', {
|
||||
method: id ? 'PUT' : 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
err.textContent = data.error || 'Save failed';
|
||||
err.hidden = false;
|
||||
return;
|
||||
}
|
||||
editModal.classList.remove('active');
|
||||
refreshSequencesList();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,262 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
let selectedIndex = null;
|
||||
|
||||
const getTab = async (zoneId) => {
|
||||
const response = await fetch(`/zones/${zoneId}`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('No zone found');
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
|
||||
const saveTabColors = async (zoneId, colors) => {
|
||||
const response = await fetch(`/zones/${zoneId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ colors }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to save zone colors');
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
|
||||
const renderPalette = (paletteContainer, colors, onColorChange, onRemoveColor, onReorder) => {
|
||||
paletteContainer.innerHTML = '';
|
||||
if (!colors.length) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'muted-text';
|
||||
empty.textContent = 'No colors in palette.';
|
||||
paletteContainer.appendChild(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
colors.forEach((color, index) => {
|
||||
const swatch = document.createElement('div');
|
||||
swatch.className = 'color-swatch';
|
||||
swatch.draggable = true;
|
||||
swatch.dataset.index = String(index);
|
||||
if (index === selectedIndex) {
|
||||
swatch.classList.add('selected');
|
||||
}
|
||||
|
||||
const preview = document.createElement('div');
|
||||
preview.className = 'color-swatch-preview';
|
||||
preview.style.backgroundColor = color;
|
||||
|
||||
const label = document.createElement('span');
|
||||
label.className = 'color-swatch-label';
|
||||
label.textContent = color;
|
||||
|
||||
const colorPicker = document.createElement('input');
|
||||
colorPicker.type = 'color';
|
||||
colorPicker.className = 'color-picker-input';
|
||||
colorPicker.value = color;
|
||||
colorPicker.addEventListener('change', async (event) => {
|
||||
const newColor = event.target.value;
|
||||
await onColorChange(index, newColor);
|
||||
});
|
||||
|
||||
const removeButton = document.createElement('button');
|
||||
removeButton.className = 'btn btn-danger btn-small';
|
||||
removeButton.textContent = 'Remove';
|
||||
removeButton.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
await onRemoveColor(index);
|
||||
});
|
||||
|
||||
swatch.addEventListener('dragstart', (event) => {
|
||||
event.dataTransfer.setData('text/plain', String(index));
|
||||
event.dataTransfer.effectAllowed = 'move';
|
||||
});
|
||||
swatch.addEventListener('dragover', (event) => {
|
||||
event.preventDefault();
|
||||
event.dataTransfer.dropEffect = 'move';
|
||||
});
|
||||
swatch.addEventListener('drop', async (event) => {
|
||||
event.preventDefault();
|
||||
const fromIndex = parseInt(event.dataTransfer.getData('text/plain'), 10);
|
||||
const toIndex = parseInt(swatch.dataset.index || '-1', 10);
|
||||
if (Number.isNaN(fromIndex) || Number.isNaN(toIndex) || fromIndex === toIndex) {
|
||||
return;
|
||||
}
|
||||
await onReorder(fromIndex, toIndex);
|
||||
});
|
||||
|
||||
swatch.appendChild(preview);
|
||||
swatch.appendChild(label);
|
||||
swatch.appendChild(colorPicker);
|
||||
swatch.appendChild(removeButton);
|
||||
swatch.addEventListener('click', () => {
|
||||
selectedIndex = index;
|
||||
renderPalette(paletteContainer, colors, onColorChange, onRemoveColor, onReorder);
|
||||
colorPicker.click();
|
||||
});
|
||||
|
||||
paletteContainer.appendChild(swatch);
|
||||
});
|
||||
};
|
||||
|
||||
const initTabPalette = async () => {
|
||||
const paletteContainer = document.getElementById('color-palette');
|
||||
const addButton = document.getElementById('zone-color-add-btn');
|
||||
const addFromPaletteButton = document.getElementById('zone-color-add-from-palette-btn');
|
||||
const colorInput = document.getElementById('zone-color-input');
|
||||
|
||||
if (!paletteContainer || !addButton || !colorInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
const zoneId = paletteContainer.dataset.zoneId;
|
||||
if (!zoneId) {
|
||||
renderPalette(paletteContainer, []);
|
||||
return;
|
||||
}
|
||||
|
||||
let tabData;
|
||||
try {
|
||||
tabData = await getTab(zoneId);
|
||||
} catch (error) {
|
||||
renderPalette(paletteContainer, []);
|
||||
return;
|
||||
}
|
||||
|
||||
let colors = tabData.colors || [];
|
||||
if (!Array.isArray(colors)) {
|
||||
colors = [];
|
||||
}
|
||||
const onRemoveColor = async (index) => {
|
||||
if (index === null || index < 0 || index >= colors.length) {
|
||||
alert('Select a color to remove.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const updated = colors.filter((_, i) => i !== index);
|
||||
const saved = await saveTabColors(zoneId, updated);
|
||||
colors = saved.colors || updated;
|
||||
selectedIndex = null;
|
||||
renderPalette(paletteContainer, colors, onColorChange, onRemoveColor, onReorder);
|
||||
} catch (error) {
|
||||
console.error('Failed to remove color:', error);
|
||||
alert('Failed to remove color.');
|
||||
}
|
||||
};
|
||||
|
||||
const onReorder = async (fromIndex, toIndex) => {
|
||||
if (fromIndex < 0 || fromIndex >= colors.length || toIndex < 0 || toIndex >= colors.length) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const updated = [...colors];
|
||||
const [moved] = updated.splice(fromIndex, 1);
|
||||
updated.splice(toIndex, 0, moved);
|
||||
const saved = await saveTabColors(zoneId, updated);
|
||||
colors = saved.colors || updated;
|
||||
selectedIndex = toIndex;
|
||||
renderPalette(paletteContainer, colors, onColorChange, onRemoveColor, onReorder);
|
||||
} catch (error) {
|
||||
console.error('Failed to reorder colors:', error);
|
||||
alert('Failed to reorder colors.');
|
||||
}
|
||||
};
|
||||
|
||||
const onColorChange = async (index, newColor) => {
|
||||
if (!newColor || index < 0 || index >= colors.length) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const updated = [...colors];
|
||||
updated[index] = newColor;
|
||||
const saved = await saveTabColors(zoneId, updated);
|
||||
colors = saved.colors || updated;
|
||||
selectedIndex = index;
|
||||
renderPalette(paletteContainer, colors, onColorChange, onRemoveColor, onReorder);
|
||||
} catch (error) {
|
||||
console.error('Failed to update color:', error);
|
||||
alert('Failed to update color.');
|
||||
}
|
||||
};
|
||||
|
||||
renderPalette(paletteContainer, colors, onColorChange, onRemoveColor, onReorder);
|
||||
|
||||
addButton.onclick = async () => {
|
||||
const newColor = colorInput.value;
|
||||
if (!newColor) {
|
||||
return;
|
||||
}
|
||||
if (colors.includes(newColor)) {
|
||||
alert('Color already in palette.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const updated = [...colors, newColor];
|
||||
const saved = await saveTabColors(zoneId, updated);
|
||||
colors = saved.colors || updated;
|
||||
selectedIndex = colors.length - 1;
|
||||
renderPalette(paletteContainer, colors, onColorChange, onRemoveColor, onReorder);
|
||||
} catch (error) {
|
||||
console.error('Failed to add color:', error);
|
||||
alert('Failed to add color.');
|
||||
}
|
||||
};
|
||||
|
||||
if (addFromPaletteButton) {
|
||||
addFromPaletteButton.onclick = () => {
|
||||
const openButton = document.getElementById('color-palette-btn');
|
||||
if (openButton) {
|
||||
openButton.click();
|
||||
}
|
||||
const modal = document.getElementById('color-palette-modal');
|
||||
const modalList = document.getElementById('palette-container');
|
||||
if (modal) {
|
||||
modal.classList.add('active');
|
||||
}
|
||||
if (!modalList) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handlePick = async (event) => {
|
||||
const row = event.target.closest('[data-color]');
|
||||
if (!row) {
|
||||
return;
|
||||
}
|
||||
const picked = row.dataset.color;
|
||||
if (!picked) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (!colors.includes(picked)) {
|
||||
const updated = [...colors, picked];
|
||||
const saved = await saveTabColors(zoneId, updated);
|
||||
colors = saved.colors || updated;
|
||||
selectedIndex = colors.indexOf(picked);
|
||||
renderPalette(paletteContainer, colors, onColorChange, onRemoveColor, onReorder);
|
||||
}
|
||||
if (modal) {
|
||||
modal.classList.remove('active');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to add palette color:', error);
|
||||
alert('Failed to add palette color.');
|
||||
} finally {
|
||||
modalList.removeEventListener('click', handlePick);
|
||||
}
|
||||
};
|
||||
|
||||
modalList.addEventListener('click', handlePick);
|
||||
};
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
document.body.addEventListener('htmx:afterSwap', (event) => {
|
||||
if (event.target && event.target.id === 'zone-content') {
|
||||
selectedIndex = null;
|
||||
initTabPalette();
|
||||
}
|
||||
});
|
||||
|
||||
initTabPalette();
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user