Files
led-controller/web/static/dmx_bridge.js
T
jimmyandClaude Haiku 5.5 edf35e9c71 Channel 11 defaults, ESP-NOW driver config and rig/desktop updates
Moves the controller, bridge and led-driver default ESP-NOW channel to 11 and
updates the led-driver and led-tool submodule pointers. Includes the rest of the
working tree: web UI, desktop and sim-controller changes, API and bridge code,
graphify output, and the .gitea and fixture-driver folders.

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

373 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// DMX bridges in Settings > Bridges: the DMX part of the bridge dialog (universes, their outputs and fixtures) and
// the DMX definitions dialog. The records are /dmx-bridges and /dmx-definitions; a bridge runs while "dmx:<id>" is
// in the bridge list (/settings/bridge). help.js owns the bridge dialog and calls window.DmxBridges.
(function () {
'use strict';
const OUTPUT_TYPES = [['artnet', 'Art-Net'], ['sacn', 'sACN (E1.31)'], ['dmx_serial', 'USB-DMX'], ['sim', 'Simulator']];
const DMX_MODES = [['enttec_pro', 'Enttec DMX USB Pro'], ['open_dmx', 'Open DMX']];
let defs = {}; // id -> definition
let ports = []; // serial ports the controller sees
let editing = null; // {id|null, rec}
const $ = (id) => document.getElementById(id);
async function json(url, opts) {
const r = await fetch(url, Object.assign({ cache: 'no-store' }, opts || {}));
let body = {};
try {
body = await r.json();
} catch (e) {
body = {};
}
if (!r.ok) throw new Error(body.error || `${r.status} ${r.statusText}`);
return body;
}
const send = (url, method, body) => json(url, {
method, headers: { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body),
});
async function loadDefs() {
defs = await json('/dmx-definitions');
return defs;
}
const channelCount = (defId) => ((defs[defId] && defs[defId].channels) || []).length;
function el(tag, props, ...children) {
const e = document.createElement(tag);
Object.entries(props || {}).forEach(([k, v]) => {
if (k === 'class') e.className = v;
else if (k === 'on') Object.entries(v).forEach(([ev, fn]) => e.addEventListener(ev, fn));
else if (k in e) e[k] = v;
else e.setAttribute(k, v);
});
children.flat().forEach((c) => e.append(c));
return e;
}
function select(options, value, onChange) {
const s = el('select', { on: { change: () => onChange(s.value) } });
options.forEach(([v, label]) => s.append(el('option', { value: v, textContent: label })));
s.value = value;
return s;
}
function error(id, text) {
const e = $(id);
e.textContent = text || '';
e.hidden = !text;
}
/* -------------------------------------------------------------- bridge */
// The first address after the universe's fixtures that fits n channels
function nextAddress(u, n) {
let end = 0;
(u.fixtures || []).forEach((f) => {
end = Math.max(end, (parseInt(f.address, 10) || 1) + channelCount(f.definition) - 1);
});
return Math.min(end + 1, Math.max(1, 513 - n));
}
function outputRow(u, o, i) {
const row = el('div', { class: 'dmx-row' });
const serial = o.type === 'dmx_serial';
row.append(select(OUTPUT_TYPES, o.type || 'artnet', (v) => { o.type = v; render(); }));
if (serial) {
const portIn = el('input', {
type: 'text', value: o.serial_port || '', placeholder: '/dev/ttyUSB0', list: 'dmx-serial-ports', 'aria-label': 'Serial port',
on: { input: () => { o.serial_port = portIn.value.trim(); } },
});
row.append(portIn, select(DMX_MODES, o.dmx_mode || 'enttec_pro', (v) => { o.dmx_mode = v; }));
} else {
const host = el('input', {
type: 'text', value: o.host || '', 'aria-label': 'Host',
placeholder: o.type === 'sacn' ? 'host (blank = multicast)' : 'host (blank = broadcast)',
on: { input: () => { o.host = host.value.trim(); } },
});
const port = el('input', {
type: 'number', class: 'dmx-num', min: 1, max: 65535, value: o.port == null ? '' : o.port,
placeholder: o.type === 'sacn' ? '5568' : '6454', 'aria-label': 'Port', title: 'Port (blank = default)',
on: { input: () => { o.port = port.value === '' ? null : Number(port.value); } },
});
const uni = el('input', {
type: 'number', class: 'dmx-num', min: 0, max: 63999, value: o.universe == null ? '' : o.universe,
placeholder: `univ ${u.number || 0}`, 'aria-label': 'Universe on the wire',
title: 'Universe on the wire (blank = the universe number)',
on: { input: () => { o.universe = uni.value === '' ? null : Number(uni.value); } },
});
if (o.type === 'sim') { // straight to the rig simulator's page: no host or port
row.append(el('span', { class: 'dmx-info', textContent: 'to the rig simulator' }), uni);
} else {
row.append(host, port, uni);
}
}
const on = el('input', { type: 'checkbox', checked: o.enabled !== false, on: { change: () => { o.enabled = on.checked; } } });
row.append(el('label', { class: 'dmx-check' }, on, 'on'));
row.append(el('button', {
type: 'button', class: 'btn btn-danger btn-small', textContent: 'Remove',
on: { click: () => { u.outputs.splice(i, 1); render(); } },
}));
return row;
}
function fixtureRow(u, f, i) {
const row = el('div', { class: 'dmx-row' });
const info = el('span', { class: 'dmx-info' });
const updateInfo = () => {
const n = channelCount(f.definition);
const a = parseInt(f.address, 10) || 1;
info.textContent = n ? `${n} ch · ${a}–${a + n - 1}` : 'no definition';
};
const name = el('input', {
type: 'text', value: f.name || '', placeholder: 'Fixture name', maxLength: 63, 'aria-label': 'Fixture name',
on: { input: () => { f.name = name.value; } },
});
const defOpts = Object.entries(defs).map(([id, d]) => [id, d.name]);
if (!defOpts.length) defOpts.push(['', '(no definitions)']);
const def = select(defOpts, f.definition || defOpts[0][0], (v) => { f.definition = v; updateInfo(); });
f.definition = def.value;
const addr = el('input', {
type: 'number', class: 'dmx-num', min: 1, max: 512, value: f.address || 1, 'aria-label': 'Start address',
title: 'Start address (1 to 512)',
on: { input: () => { f.address = addr.value === '' ? '' : Number(addr.value); updateInfo(); } },
});
const mac = el('input', {
type: 'text', class: 'dmx-mac', value: f.mac || '', placeholder: 'new MAC on save', maxLength: 17,
'aria-label': 'MAC', title: 'The fixture driver\'s MAC (blank: a new one is made)',
on: { input: () => { f.mac = mac.value.trim(); } },
});
const renew = el('button', {
type: 'button', class: 'btn btn-secondary btn-small', textContent: 'New MAC',
title: 'Clear the MAC: a new one is made when the bridge is saved (the fixture shows up as a new device)',
on: { click: () => { f.mac = ''; mac.value = ''; } },
});
const del = el('button', {
type: 'button', class: 'btn btn-danger btn-small', textContent: 'Remove',
on: { click: () => { u.fixtures.splice(i, 1); render(); } },
});
updateInfo();
row.append(name, def, addr, info, mac, renew, del);
return row;
}
function universeCard(u, ui) {
const rec = editing.rec;
const card = el('div', { class: 'dmx-universe' });
const name = el('input', {
type: 'text', value: u.name || '', placeholder: `Universe ${ui + 1}`, maxLength: 63,
on: { input: () => { u.name = name.value; } },
});
const number = el('input', {
type: 'number', min: 0, max: 63999, value: u.number == null ? ui : u.number,
on: { input: () => { u.number = number.value === '' ? null : Number(number.value); } },
});
card.append(el('div', { class: 'dmx-universe-head' },
el('div', {}, el('label', { textContent: 'Universe name' }), name),
el('div', { class: 'dmx-narrow' }, el('label', { textContent: 'Number' }), number),
el('button', {
type: 'button', class: 'btn btn-danger btn-small', textContent: 'Remove universe',
on: { click: () => { rec.universes.splice(ui, 1); render(); } },
})));
card.append(el('h4', { textContent: 'Outputs' }));
if (!u.outputs.length) card.append(el('small', { class: 'muted-text', textContent: 'No outputs: the universe is built but not sent.' }));
u.outputs.forEach((o, i) => card.append(outputRow(u, o, i)));
card.append(el('div', { class: 'profiles-actions' }, el('button', {
type: 'button', class: 'btn btn-secondary btn-small', textContent: 'Add output',
on: { click: () => { u.outputs.push({ type: 'artnet', host: '', port: null, universe: null, enabled: true }); render(); } },
})));
card.append(el('h4', { textContent: 'Fixtures' }));
if (!u.fixtures.length) card.append(el('small', { class: 'muted-text', textContent: 'No fixtures yet.' }));
u.fixtures.forEach((f, i) => card.append(fixtureRow(u, f, i)));
card.append(el('div', { class: 'profiles-actions' }, el('button', {
type: 'button', class: 'btn btn-secondary btn-small', textContent: 'Add fixture',
on: {
click: () => {
const defId = (u.fixtures.length && u.fixtures[u.fixtures.length - 1].definition) || Object.keys(defs)[0] || '';
u.fixtures.push({
name: `${u.name || 'Fixture'} ${u.fixtures.length + 1}`, definition: defId,
address: nextAddress(u, channelCount(defId)), mac: '',
});
render();
},
},
})));
return card;
}
function render() {
const box = $('edit-bridge-dmx-universes');
box.textContent = '';
let dl = $('dmx-serial-ports');
if (!dl) {
dl = el('datalist', { id: 'dmx-serial-ports' });
document.body.append(dl);
}
dl.textContent = '';
ports.forEach((p) => dl.append(el('option', { value: p })));
editing.rec.universes.forEach((u, ui) => box.append(universeCard(u, ui)));
if (!editing.rec.universes.length) {
box.append(el('p', { class: 'muted-text', textContent: 'Add a universe, then its outputs and fixtures.' }));
}
}
const newUniverse = (n) => ({
name: `Universe ${n + 1}`, number: n, fixtures: [],
outputs: n ? [] : [{ type: 'artnet', host: '', port: null, universe: null, enabled: true }],
});
// Load bridge id (null: a new one) into the dialog's DMX section; returns its name
async function load(id) {
await loadDefs();
const br = await json('/settings/bridge');
ports = br.ports || [];
const rec = id ? await json(`/dmx-bridges/${encodeURIComponent(id)}`) : { name: '', universes: [newUniverse(0)] };
rec.universes = (rec.universes || []).map((u) => Object.assign({ outputs: [], fixtures: [] }, u));
editing = { id: id || null, rec };
render();
return rec.name || '';
}
// Save what the dialog holds under this name. A new bridge is started (its address added to the bridges).
// Throws with the server's message when a check fails.
async function save(name) {
if (!editing) throw new Error('Nothing to save');
const rec = editing.rec;
rec.name = (name || '').trim();
if (!rec.name) throw new Error('The bridge needs a name');
const body = { name: rec.name, universes: rec.universes };
if (editing.id) {
await send(`/dmx-bridges/${encodeURIComponent(editing.id)}`, 'PUT', body);
return { id: editing.id, created: false };
}
const id = String((await send('/dmx-bridges', 'POST', body)).id);
editing.id = id; // a failed start below must not make a second record on the next save
await start(id);
return { id, created: true };
}
function addUniverse() {
if (!editing) return;
editing.rec.universes.push(newUniverse(editing.rec.universes.length));
render();
}
async function remove(id) {
await send(`/dmx-bridges/${encodeURIComponent(id)}`, 'DELETE'); // also takes it off the running bridges
}
async function start(id) {
const br = await json('/settings/bridge');
const addrs = (br.bridges || []).map((b) => b.addr);
await send('/settings/bridge', 'PUT', { bridges: [...addrs, `dmx:${id}`] });
}
/* --------------------------------------------------------- definitions */
let defEditing = null; // id, '' for a new one, null when the form is closed
function renderDefs() {
const list = $('dmx-defs-list');
list.textContent = '';
const ids = Object.keys(defs).sort((a, b) => defs[a].name.localeCompare(defs[b].name));
ids.forEach((id) => {
const d = defs[id];
const meta = [d.manufacturer, d.model, d.mode].filter(Boolean).join(' · ');
list.append(el('div', { class: 'group-list-row' },
el('div', { class: 'group-list-row-info' },
el('div', { class: 'group-list-row-title', textContent: d.name }),
el('div', { class: 'group-list-row-meta muted-text', textContent: `${d.channels.length} channels${meta ? ' · ' + meta : ''}` })),
el('div', { class: 'group-list-row-actions' }, el('button', {
type: 'button', class: 'btn btn-secondary btn-small', textContent: 'Edit', on: { click: () => editDef(id) },
}))));
});
if (!ids.length) list.append(el('small', { class: 'muted-text', textContent: 'No definitions.' }));
}
function editDef(id) {
defEditing = id;
const d = id ? defs[id] : { name: '', manufacturer: '', model: '', mode: '', channels: ['Dimmer', 'Red', 'Green', 'Blue'], defaults: {} };
$('dmx-def-title').textContent = id ? `Edit ${d.name}` : 'New definition';
$('dmx-def-name').value = d.name || '';
$('dmx-def-manufacturer').value = d.manufacturer || '';
$('dmx-def-model').value = d.model || '';
$('dmx-def-mode').value = d.mode || '';
$('dmx-def-channels').value = (d.channels || []).join('\n');
$('dmx-def-defaults').value = Object.entries(d.defaults || {}).map(([k, v]) => `${k} = ${v}`).join('\n');
$('dmx-def-delete-btn').hidden = !id;
error('dmx-def-error', '');
$('dmx-def-form').hidden = false;
$('dmx-def-name').focus();
}
async function saveDef(e) {
e.preventDefault();
const channels = $('dmx-def-channels').value.split('\n').map((s) => s.trim()).filter(Boolean);
const defaults = {};
for (const line of $('dmx-def-defaults').value.split('\n')) {
if (!line.trim()) continue;
const m = /^(.+?)\s*=\s*(\d+)\s*$/.exec(line.trim());
if (!m) {
error('dmx-def-error', `Not "Channel = value": ${line.trim()}`);
return;
}
defaults[m[1].trim()] = Number(m[2]);
}
const body = {
name: $('dmx-def-name').value.trim(), manufacturer: $('dmx-def-manufacturer').value.trim(),
model: $('dmx-def-model').value.trim(), mode: $('dmx-def-mode').value.trim(), channels, defaults,
};
try {
if (defEditing) await send(`/dmx-definitions/${encodeURIComponent(defEditing)}`, 'PUT', body);
else await send('/dmx-definitions', 'POST', body);
await loadDefs();
$('dmx-def-form').hidden = true;
renderDefs();
if (editing && !$('edit-bridge-dmx-field').hidden) render();
} catch (err) {
error('dmx-def-error', err.message);
}
}
async function openDefs() {
try {
await loadDefs();
} catch (e) {
alert(`Could not read the DMX definitions: ${e.message}`);
return;
}
$('dmx-def-form').hidden = true;
renderDefs();
$('dmx-defs-modal').classList.add('active');
}
document.addEventListener('DOMContentLoaded', () => {
const addUni = $('edit-bridge-dmx-add-universe');
if (addUni) addUni.addEventListener('click', addUniverse);
if (!$('dmx-def-form')) return;
$('dmx-def-form').addEventListener('submit', saveDef);
$('dmx-defs-new-btn').addEventListener('click', () => editDef(''));
$('dmx-defs-close-btn').addEventListener('click', () => $('dmx-defs-modal').classList.remove('active'));
$('dmx-def-delete-btn').addEventListener('click', async () => {
if (!defEditing || !await uiConfirm(`Delete definition "${defs[defEditing].name}"?`)) return;
try {
await send(`/dmx-definitions/${encodeURIComponent(defEditing)}`, 'DELETE');
await loadDefs();
$('dmx-def-form').hidden = true;
renderDefs();
} catch (err) {
error('dmx-def-error', err.message);
}
});
const defsBtn = $('dmx-defs-btn');
if (defsBtn) defsBtn.addEventListener('click', openDefs);
});
window.DmxBridges = { load, save, remove, start, openDefs };
})();