sim: fixture editor for DDP and Art-Net/DMX fixtures

The rig sim receives Art-Net (UDP 6454, answers ArtPoll) and DDP (each port the
room's DDP strips use) in sim_net.c and passes changed universes and pixels to
the page over /sim/ws, now with a kind byte in front of each binary frame.

Rooms gain fixture types: ddp strips, artnet pixel strips, and artnet cans and
movers that read named channels from the room's dmx_definitions (the qlcplus
stage map's format). Overlapping DMX channels are refused. Cans and movers are
decoded and drawn as in the qlcplus stage simulator (dmx.js, dmx-draw.js).

In Edit mode: pick a type to add, edit port/offset/universe/address/colour
order/definition, see a can's or mover's live channels, make a controller
output aimed at the sim and send its test. The room dialog lists DMX
definitions, with presets, a channel editor, and .qxf and stage map import.

GET /sim/api/dmx shows what the receiver has had. Tests: test/api/test_sim_net.py
and test/browser/dmx_decode.test.mjs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-11-17 18:13:58 +13:00
1 parent 2fdd55323b
commit 35207a868a
16 files changed
+2848 -107

No files matched your search

+1 -1
View File
@@ -35,7 +35,7 @@ set(MAIN_SRC
list(TRANSFORM MAIN_SRC PREPEND ${ROOT}/main/) list(TRANSFORM MAIN_SRC PREPEND ${ROOT}/main/)
# The host stand-ins for the board's hardware (mic, OTA, littlefs, timers) and the app_main that starts it # The host stand-ins for the board's hardware (mic, OTA, littlefs, timers) and the app_main that starts it
set(SIM_SRC sim_main.c sim_stubs.c sim_timer.c sim_rig.c) set(SIM_SRC sim_main.c sim_stubs.c sim_timer.c sim_rig.c sim_net.c)
list(TRANSFORM SIM_SRC PREPEND ${ROOT}/sim-controller/components/sim/) list(TRANSFORM SIM_SRC PREPEND ${ROOT}/sim-controller/components/sim/)
set(THIRD_PARTY set(THIRD_PARTY
+2
View File
@@ -296,6 +296,8 @@ Network pixel fixtures. An output is `{id, name, protocol: "ddp" | "artnet" | "s
Zones do not render to outputs: only the test pattern is sent. Zones do not render to outputs: only the test pattern is sent.
The simulated rig (`/sim/`, host builds) receives Art-Net and DDP, so an output aimed at `127.0.0.1` shows on its DDP and Art-Net fixtures; see `led-simulator/README.md` (Network fixtures) and `GET /sim/api/dmx`.
## WebSocket — `/ws` ## WebSocket — `/ws`
On connect the controller sends `{"type": "device_tcp_snapshot", "connected_ips": []}` (there are no Wi-Fi driver sessions). Each text frame is a driver message (JSON object), sent as `/presets/push` would send it: an optional `to` (MAC) addresses one driver, otherwise it is broadcast. A frame that is not a JSON object, or a failed send, gets `{"error": ...}` back. A plain GET gets 426. On connect the controller sends `{"type": "device_tcp_snapshot", "connected_ips": []}` (there are no Wi-Fi driver sessions). Each text frame is a driver message (JSON object), sent as `/presets/push` would send it: an optional `to` (MAC) addresses one driver, otherwise it is broadcast. A frame that is not a JSON object, or a failed send, gets `{"error": ...}` back. A plain GET gets 426.
+45 -3
View File
@@ -62,6 +62,8 @@ strip types in `definitions`, and `fixtures` keyed by id, each placed by positio
`leds × pitch_m` long. `leds` on a fixture overrides its type's count (1–512). `leds × pitch_m` long. `leds` on a fixture overrides its type's count (1–512).
- **`mac`** identifies the driver. Each bar's flash is kept per MAC, so a bar in two rooms (a copied room, say) is - **`mac`** identifies the driver. Each bar's flash is kept per MAC, so a bar in two rooms (a copied room, say) is
the same bar with the same presets. New bars get a MAC no room uses yet. the same bar with the same presets. New bars get a MAC no room uses yet.
- A fixture's **`type`** is `espnow` (the default: a bar with its own driver), `ddp` or `artnet`; see
[Network fixtures](#network-fixtures).
- The first run makes the `default` room: 16 bars × 119 LEDs in 2 columns × 8 rows, pixel 0 at the centre line, - The first run makes the `default` room: 16 bars × 119 LEDs in 2 columns × 8 rows, pixel 0 at the centre line,
`sim-01` … `sim-16` = `02:51:4d:00:00:01` … `…:10`. The rig's bridge is `02:51:4d:00:00:00`. `sim-01` … `sim-16` = `02:51:4d:00:00:01` … `…:10`. The rig's bridge is `02:51:4d:00:00:00`.
@@ -89,6 +91,43 @@ controller's rig layout:
A bar whose LED count changes keeps running with the old count until it is power-cycled, as `num_leds` is read at A bar whose LED count changes keeps running with the old count until it is power-cycled, as `num_leds` is read at
boot. boot.
### Network fixtures
Besides the ESP-NOW bars, a room can hold fixtures that something sends to over the network: the controller's own
Outputs, QLC+, or any DDP or Art-Net sender. The controller's sim receives them over UDP (`sim_net.c`: Art-Net on
6454, DDP on each port the active room's DDP strips use, 4048 by default) and passes each changed universe or
DDP buffer to the page at up to 40 frames a second. It answers ArtPoll, so QLC+ lists the node. If QLC+ on the same
machine already holds 6454, set `LED_SIM_ARTNET_PORT` to another port (`0` turns Art-Net off).
| `type` | `kind` | Fields | What it is |
| --- | --- | --- | --- |
| `ddp` | | `def`, `leds`, `port` (4048), `offset` (first pixel), `color_order` | an LED strip fed by DDP |
| `artnet` | `pixels` | `def`, `leds`, `universe`, `address` (1–512), `color_order` | an LED strip fed by Art-Net: the first universe from `address`, then 170 pixels a universe from channel 1, as the controller's Art-Net output sends them |
| `artnet` | `can` | `dmx_def`, `universe`, `address`, `direction` | a par can |
| `artnet` | `mover` | `dmx_def`, `universe`, `address`, `zero`, `pan_reverse` | a moving head; `zero` is its heading at pan centre |
Cans and movers behave as in the qlcplus stage simulator (technicalkiwi/qlcplus `simulator/`). Their channels come
from the room's **`dmx_definitions`**: `{name: {manufacturer, model, mode, channels: [name, ...]}}`, the same shape
as a qlcplus `stage/map.json`. The channel names choose what each slot does: `Dimmer`, `Strobe`, `Red`, `Green`,
`Blue`, `White`, `Macro`, `Speed` for cans; `Pan`, `Pan Fine`, `Tilt`, `Tilt Fine`, `Pan/Tilt Speed`, `Zoom`,
`Focus`, `Lens Rotate`, `Center Brightness`, `Center Strobe`, `Red 1` … `White 7`, `Colour Macro`,
`Colour Temperature`, `Static Effect`, `Dynamic Effect` for movers (`web/dmx.js`). Art-Net fixtures may not share
DMX channels; the room is refused if they do.
On the page, in Edit mode:
- Pick the type beside **Add** (ESP-NOW bar, DDP strip, Art-Net pixel strip, DMX can, DMX mover). A click on the
floor adds that type. New DDP strips start after the last one on port 4048, Art-Net pixel strips on the first
free universe, and cans and movers at the first free DMX address.
- The side panel edits the port and first pixel, the universe and address, the colour order, the DMX definition,
and a mover's pan zero and reversal. For a can or mover it lists the channels with their live values.
- **Create controller output** (DDP and Art-Net pixel strips) adds an Output to the controller aimed at the sim
(`127.0.0.1`), and **Send test** runs its red, green, blue, white, black test. Outputs send from pixel 0 and
channel 1, so the button needs First pixel 0 or DMX address 1.
- **Size, strip types & DMX…** also lists the DMX definitions: add a preset (the qlcplus beamZ BCC145 and Small Eye
7 mover), write one (one channel name per line), import a QLC+ fixture definition (`.qxf`, one definition per
mode), or import a qlcplus `stage/map.json` (its definitions, and its cans and movers placed in the room).
### API (on the controller) ### API (on the controller)
| | | | | |
@@ -99,8 +138,9 @@ boot.
| `POST /sim/api/rooms` | `{name, width, depth, copy_from?}` makes a room | | `POST /sim/api/rooms` | `{name, width, depth, copy_from?}` makes a room |
| `GET`, `PUT`, `DELETE /sim/api/rooms/<name>` | one room: read it, replace it (validated), delete it (not the active one) | | `GET`, `PUT`, `DELETE /sim/api/rooms/<name>` | one room: read it, replace it (validated), delete it (not the active one) |
| `POST /sim/api/room` | `{name}` switches the rig to that room | | `POST /sim/api/room` | `{name}` switches the rig to that room |
| `GET /sim/api/next-mac` | a MAC no room uses | | `POST /sim/api/next-mac` | `{taken: [mac, ...]}`: a MAC no room or the page uses |
| `WS /sim/ws` | the page's radio: binary `dst_mac + packet` down, `src_mac + packet` up; text `{"t":"flash"}` up | | `GET /sim/api/dmx[?data=1]` | what the Art-Net and DDP receiver has had: packets per universe and port, the last sender; `data=1` adds the bytes as hex |
| `WS /sim/ws` | the page's radio. Down, binary: `0x00 + dst_mac + packet` (ESP-NOW), `0x01 + u16 universe + 512 bytes` (Art-Net), `0x02 + u16 port + u32 offset + RGB` (DDP), little-endian. Up: binary `src_mac + packet`; text `{"t":"flash"}` |
## How it fits together ## How it fits together
@@ -113,14 +153,16 @@ led-controller (host build) ──"browser" bridge──▶ WS /sim/ws ──▶
| Where | What | | Where | What |
| --- | --- | | --- | --- |
| `sim-controller/components/sim/sim_rig.c` | serves the page and the wasm from `www_dist/sim.pack`, the page's WebSocket, rooms and flash | | `sim-controller/components/sim/sim_rig.c` | serves the page and the wasm from `www_dist/sim.pack`, the page's WebSocket, rooms and flash |
| `sim-controller/components/sim/sim_net.c` | receives Art-Net and DDP for the network fixtures and passes them to the page |
| `main/bridge.c` | the `browser` bridge kind next to UDP and serial | | `main/bridge.c` | the `browser` bridge kind next to UDP and serial |
| `tools/build_sim_web.sh` | packs `web/` and `web/wasm/` into `www_dist/sim.pack`. It is empty when the drivers are not built, so `make desktop` works without Emscripten. | | `tools/build_sim_web.sh` | packs `web/` and `web/wasm/` into `www_dist/sim.pack`. It is empty when the drivers are not built, so `make desktop` works without Emscripten. |
| `../sim-driver/` | the Emscripten build of the driver (`led_driver`) and the pattern engine for the gallery (`led_fx`) | | `../sim-driver/` | the Emscripten build of the driver (`led_driver`) and the pattern engine for the gallery (`led_fx`) |
| `web/app.js` | the room canvas, editor, power control, packet routing by MAC, and placements for `POST /devices/layout` | | `web/app.js` | the room canvas, editor, power control, packet routing by MAC, and placements for `POST /devices/layout` |
| `web/driver-worker.js` | loads `led_driver.mjs` and boots one bar | | `web/driver-worker.js` | loads `led_driver.mjs` and boots one bar |
| `web/dmx.js`, `web/dmx-draw.js` | the DMX decoder and the can and mover drawing, ported from the qlcplus stage simulator |
| `web/gallery.js` | one `led_fx` instance per pattern, each stepped every 10 ms of its own clock | | `web/gallery.js` | one `led_fx` instance per pattern, each stepped every 10 ms of its own clock |
Not simulated: the drivers' Wi-Fi, their own web UI and HTTP API, DDP and USB. Bars do not hear each other's Not simulated: the drivers' Wi-Fi, their own web UI and HTTP API, DDP to the bars themselves, sACN and USB. Bars do not hear each other's
ESP-NOW. ESP-NOW.
## Headless (older) ## Headless (older)
+691 -29
View File
@@ -2,7 +2,9 @@
* *
* Each bar is a module worker running the C++ led-driver built to WebAssembly (driver-worker.js). The page is * Each bar is a module worker running the C++ led-driver built to WebAssembly (driver-worker.js). The page is
* the radio between them and the controller's "browser" bridge (WebSocket /sim/ws): * the radio between them and the controller's "browser" bridge (WebSocket /sim/ws):
* controller -> page binary dest_mac(6) + ESP-NOW packet (the controller transmits) * controller -> page binary 0x00 + dest_mac(6) + ESP-NOW packet (the controller transmits)
* controller -> page binary 0x01 + u16 universe + 512 bytes (an Art-Net universe changed)
* controller -> page binary 0x02 + u16 port + u32 offset + RGB (a DDP port's pixels changed)
* page -> controller binary src_mac(6) + ESP-NOW packet (a driver transmits) * page -> controller binary src_mac(6) + ESP-NOW packet (a driver transmits)
* controller -> page text {"t":"takeover"} (another page opened the rig) * controller -> page text {"t":"takeover"} (another page opened the rig)
* page -> controller text {"t":"flash","mac":..,"data":..} (a driver committed its NVS store) * page -> controller text {"t":"flash","mac":..,"data":..} (a driver committed its NVS store)
@@ -10,8 +12,12 @@
* Where the bars are is the active room. In Edit mode the room can be changed: add bars by clicking the floor, * Where the bars are is the active room. In Edit mode the room can be changed: add bars by clicking the floor,
* drag to move, drag the end handle to turn, Delete to remove. Every change is saved (PUT /sim/api/rooms/<name>) * drag to move, drag the end handle to turn, Delete to remove. Every change is saved (PUT /sim/api/rooms/<name>)
* and the bars' places go to the controller's rig layout (POST /devices/layout). * and the bars' places go to the controller's rig layout (POST /devices/layout).
*
* Besides the ESP-NOW bars a room can hold network fixtures, which the controller's sim receives over UDP and
* passes on here: DDP strips, Art-Net pixel strips, and DMX cans and movers drawn the way the qlcplus stage
* simulator draws them (dmx.js decodes, dmx-draw.js draws).
*/ */
/* global RigLayout */ /* global RigLayout, RigDmx, RigDmxDraw */
(function () { (function () {
'use strict'; 'use strict';
@@ -74,8 +80,16 @@
drag: null, drag: null,
saveTimer: 0, saveTimer: 0,
lastDef: '', lastDef: '',
universes: new Map(), // Art-Net universe -> Uint8Array(512), as the sim last received it
ddp: new Map(), // DDP port -> Uint8Array of RGB from offset 0
netAt: new Map(), // 'u<n>' / 'p<port>' -> when it last arrived (ms)
netDirty: false,
outputs: new Map(), // fixture id -> controller output id made for it on this page
}; };
const NET_FRESH_MS = 2000; // a network fixture is "receiving" while data came in this recently
const NET_LEDS_MAX = 4096; // SIM_NET_DDP_PIXELS in sim_net.h
// ----- helpers ----------------------------------------------------------- // ----- helpers -----------------------------------------------------------
function macBytes(s) { function macBytes(s) {
@@ -152,8 +166,10 @@
return { return {
info, info,
id: info.id, id: info.id,
type: info.type,
kind: info.kind,
mac: info.mac, mac: info.mac,
macBytes: macBytes(info.mac), macBytes: info.mac ? macBytes(info.mac) : null,
name: info.label, name: info.label,
bootedLeds: 0, bootedLeds: 0,
state: 'off', state: 'off',
@@ -164,9 +180,14 @@
rx: 0, rx: 0,
tx: 0, tx: 0,
error: '', error: '',
live: null, // a can's or mover's decoded view (RigDmx.viewFixture)
}; };
} }
function isNet(s) {
return s.type !== 'espnow';
}
function setState(s, state, error = '') { function setState(s, state, error = '') {
s.state = state; s.state = state;
s.error = error; s.error = error;
@@ -195,7 +216,7 @@
} }
function powerOn(s) { function powerOn(s) {
if (app.takenOver) { if (app.takenOver || isNet(s)) {
return; return;
} }
if (s.state !== 'off' && s.state !== 'crashed') { if (s.state !== 'off' && s.state !== 'crashed') {
@@ -388,6 +409,96 @@
} }
} }
/** An Art-Net universe or a DDP port's pixels from the sim's receiver (sim_net.h). */
function onNetFrame(u8) {
const dv = new DataView(u8.buffer, u8.byteOffset, u8.byteLength);
if (u8[0] === 1 && u8.length >= 3 + 512) {
const uni = dv.getUint16(1, true);
app.universes.set(uni, u8.slice(3, 3 + 512));
app.netAt.set(`u${uni}`, performance.now());
} else if (u8[0] === 2 && u8.length >= 7) {
const port = dv.getUint16(1, true);
const off = dv.getUint32(3, true);
const data = u8.subarray(7);
let buf = app.ddp.get(port);
if (!buf || buf.length < off + data.length) {
const grown = new Uint8Array(off + data.length);
if (buf) {
grown.set(buf);
}
buf = grown;
}
buf.set(data, off);
app.ddp.set(port, buf);
app.netAt.set(`p${port}`, performance.now());
}
app.netDirty = true;
}
/** Wire bytes to r, g, b. color_order names the colour in each wire slot ("grb": green first), as in outputs.c. */
function toRgb(src, order) {
if (!/^(rgb|rbg|grb|gbr|brg|bgr)$/.test(order) || order === 'rgb') {
return src;
}
const at = [0, 1, 2].map((k) => 'rgb'.indexOf(order[k])); // wire slot k carries colour at[k]
const out = new Uint8Array(src.length);
for (let i = 0; i + 2 < src.length; i += 3) {
for (let k = 0; k < 3; k += 1) {
out[i + at[k]] = src[i + k];
}
}
return out;
}
/** Where a network fixture's data comes from, and whether it is arriving. */
function netSource(f) {
if (f.type === 'ddp') {
return `p${f.port}`;
}
return `u${f.universe}`;
}
function netFresh(f) {
const t = app.netAt.get(netSource(f));
return t !== undefined && performance.now() - t < NET_FRESH_MS;
}
/** Fill the network fixtures' frames (pixels) and views (cans, movers) from what has arrived. */
function updateNet() {
for (const s of app.strips) {
const f = app.room.fixtures[s.id];
if (!f || !isNet(s)) {
continue;
}
const was = s.state;
s.state = netFresh(f) ? 'running' : 'off';
if (s.state !== was) {
app.dirty = true;
}
if (s.info.point) {
const def = (app.room.dmx_definitions || {})[f.dmx_def];
s.live = RigDmx.viewFixture(
{ kind: f.kind, universe: f.universe, address: f.address, channel_names: def ? def.channels : [], pan_reverse: f.pan_reverse },
app.universes,
);
continue;
}
const leds = s.info.leds;
let raw;
if (f.type === 'ddp') {
const buf = app.ddp.get(f.port);
raw = new Uint8Array(leds * 3);
if (buf) {
const a = (f.offset || 0) * 3;
raw.set(buf.subarray(a, Math.min(buf.length, a + leds * 3)));
}
} else {
raw = RigDmx.artnetPixels(app.universes, f.universe, f.address, leds);
}
s.frame = toRgb(raw, f.color_order || 'rgb');
}
}
function connectBridge() { function connectBridge() {
if (app.takenOver) { if (app.takenOver) {
return; return;
@@ -421,7 +532,12 @@
} }
return; return;
} }
onDownlink(new Uint8Array(ev.data)); const u8 = new Uint8Array(ev.data);
if (u8[0] === 0) {
onDownlink(u8.subarray(1));
} else if (u8[0] === 1 || u8[0] === 2) {
onNetFrame(u8);
}
}; };
ws.onclose = () => { ws.onclose = () => {
app.wsOpen = false; app.wsOpen = false;
@@ -443,7 +559,7 @@
const next = []; const next = [];
for (const info of infos) { for (const info of infos) {
let s = old.get(info.id); let s = old.get(info.id);
if (s && s.mac !== info.mac) { if (s && (s.mac !== info.mac || s.type !== info.type || s.kind !== info.kind)) {
powerOff(s); powerOff(s);
s = null; s = null;
} }
@@ -467,7 +583,8 @@
} }
} }
app.strips = next; app.strips = next;
app.byMac = new Map(next.map((s) => [s.mac, s])); app.byMac = new Map(next.filter((s) => s.mac).map((s) => [s.mac, s]));
app.netDirty = true;
layoutView(); layoutView();
updateChips(); updateChips();
renderDrawer(); renderDrawer();
@@ -533,6 +650,7 @@
const sel = $('room-select'); const sel = $('room-select');
sel.replaceChildren(...cfg.rooms.map((n) => new Option(n, n, false, n === cfg.room_name))); sel.replaceChildren(...cfg.rooms.map((n) => new Option(n, n, false, n === cfg.room_name)));
app.lastDef = Object.keys(app.room.definitions)[0]; app.lastDef = Object.keys(app.room.definitions)[0];
app.room.dmx_definitions = app.room.dmx_definitions || {};
app.zoom = 1; // each room opens fitted app.zoom = 1; // each room opens fitted
app.pan = { x: 0, y: 0 }; app.pan = { x: 0, y: 0 };
syncStrips(); syncStrips();
@@ -553,24 +671,101 @@
return mac.replace(/:/g, ''); return mac.replace(/:/g, '');
} }
/** A label like can-1 that no fixture in the room has. */
function nextNetLabel(prefix) {
const taken = new Set(Object.entries(app.room.fixtures).flatMap(([id, f]) => [id, f.label]));
for (let n = 1; ; n += 1) {
if (!taken.has(`${prefix}-${n}`)) {
return `${prefix}-${n}`;
}
}
}
/** The first DMX address from universe 0 up where count channels are free; fromStart: only at address 1 (a pixel
* strip, so a controller output, which sends from channel 1, can feed it). */
function nextDmxAddress(count, fromStart = false) {
const used = [];
for (const f of Object.values(app.room.fixtures)) {
if (f.type === 'artnet') {
used.push(...RigDmx.dmxRuns(f, app.room, RigLayout.fixtureLeds(app.room, f)));
}
}
for (let u = 0; u < 32768; u += 1) {
const runs = used.filter((r) => r[0] === u).sort((a, b) => a[1] - b[1]);
let a = 0;
for (const [, s0, e0] of runs) {
if (s0 - a >= count || (fromStart && a === 0 && s0 >= count)) {
break;
}
a = Math.max(a, e0);
if (fromStart) {
break; // address 1 is taken in this universe
}
}
if (a + count <= 512 && !(fromStart && a > 0)) {
return { universe: u, address: a + 1 };
}
}
return { universe: 0, address: 1 };
}
/** The DMX definition for a new can or mover: the last one used for that kind, else a qlcplus preset. */
function dmxDefFor(kind) {
const defs = app.room.dmx_definitions;
const want = kind === 'mover' ? 'Small Eye 7 Mover' : 'beamZ BCC145';
const isMover = (d) => d.channels.some((c) => /^pan$/i.test(c)) && d.channels.some((c) => /^tilt$/i.test(c));
const used = Object.values(app.room.fixtures).find((f) => f.kind === kind && defs[f.dmx_def]);
if (used) {
return used.dmx_def;
}
const fit = Object.keys(defs).find((k) => isMover(defs[k]) === (kind === 'mover'));
if (fit) {
return fit;
}
defs[want] = JSON.parse(JSON.stringify(RigDmx.PRESET_DEFINITIONS[want]));
return want;
}
async function addFixture(x, y) { async function addFixture(x, y) {
const type = $('add-type').value || 'espnow';
const pos = { x: round3(Math.round(x / SNAP_M) * SNAP_M), y: round3(Math.round(y / SNAP_M) * SNAP_M) };
const def = app.lastDef in app.room.definitions ? app.lastDef : Object.keys(app.room.definitions)[0];
let label;
if (type === 'espnow') {
let mac; let mac;
try { try {
const taken = Object.values(app.room.fixtures).map((f) => f.mac); const taken = Object.values(app.room.fixtures).map((f) => f.mac).filter(Boolean);
mac = (await api('POST', '/sim/api/next-mac', { taken })).mac; mac = (await api('POST', '/sim/api/next-mac', { taken })).mac;
} catch (err) { } catch (err) {
banner(`Could not add a strip: ${err.message}`); banner(`Could not add a strip: ${err.message}`);
return; return;
} }
const label = nextLabel(mac); label = nextLabel(mac);
app.room.fixtures[label] = { label, def, mac, ...pos, direction: 90 };
} else if (type === 'ddp') {
label = nextNetLabel('ddp');
// after the last DDP strip on 4048, so a new strip gets its own pixels
let offset = 0;
for (const f of Object.values(app.room.fixtures)) {
if (f.type === 'ddp' && f.port === 4048) {
offset = Math.max(offset, (f.offset || 0) + RigLayout.fixtureLeds(app.room, f));
}
}
app.room.fixtures[label] = { label, type, def, port: 4048, offset: Math.min(offset, NET_LEDS_MAX - 1), color_order: 'rgb', ...pos, direction: 90 };
} else if (type === 'artnet') {
label = nextNetLabel('art');
const leds = app.room.definitions[def].leds;
const at = nextDmxAddress(Math.min(510, leds * 3), true);
app.room.fixtures[label] = { label, type, kind: 'pixels', def, ...at, color_order: 'rgb', ...pos, direction: 90 };
} else {
label = nextNetLabel(type);
const dmxDef = dmxDefFor(type);
const at = nextDmxAddress(app.room.dmx_definitions[dmxDef].channels.length);
app.room.fixtures[label] = { app.room.fixtures[label] = {
label, label, type: 'artnet', kind: type, dmx_def: dmxDef, ...at, ...pos, direction: 0,
def: app.lastDef in app.room.definitions ? app.lastDef : Object.keys(app.room.definitions)[0], ...(type === 'mover' ? { zero: 0, pan_reverse: false } : {}),
mac,
x: round3(Math.round(x / SNAP_M) * SNAP_M),
y: round3(Math.round(y / SNAP_M) * SNAP_M),
direction: 90,
}; };
}
changed(); changed();
select(app.strips.find((s) => s.id === label) || null); select(app.strips.find((s) => s.id === label) || null);
renderDrawer(); renderDrawer();
@@ -631,6 +826,9 @@
const ty = (y) => Math.round((H / 2 + (y - app.room.depth / 2) * s) * 10) / 10; const ty = (y) => Math.round((H / 2 + (y - app.room.depth / 2) * s) * 10) / 10;
const out = {}; const out = {};
for (const st of RigLayout.roomStrips(app.room)) { for (const st of RigLayout.roomStrips(app.room)) {
if (!st.mac) {
continue; // a network fixture: the controller has no device for it
}
out[st.mac.replace(/:/g, '')] = { x0: tx(st.x), y0: ty(st.y), x1: tx(st.x1), y1: ty(st.y1) }; out[st.mac.replace(/:/g, '')] = { x0: tx(st.x), y0: ty(st.y), x1: tx(st.x1), y1: ty(st.y1) };
} }
return out; return out;
@@ -699,15 +897,36 @@
} }
/** What a network fixture listens to, for the drawer's subtitle. */
function netWhere(f) {
if (f.type === 'ddp') {
return `DDP :${f.port} · from pixel ${f.offset || 0}`;
}
const what = f.kind === 'pixels' ? 'Art-Net pixels' : `DMX ${f.kind} · ${f.dmx_def}`;
return `${what} · universe ${f.universe} · address ${f.address}`;
}
function renderFacts() { function renderFacts() {
const s = app.selected; const s = app.selected;
if (!s) { if (!s) {
return; return;
} }
const st = $('d-state'); const st = $('d-state');
const i = s.info;
const f = app.room.fixtures[s.id] || {};
if (isNet(s)) {
const on = netFresh(f);
st.textContent = on ? 'receiving' : 'no data';
st.className = `state-${on ? 'running' : 'off'}`;
const where = i.point ? `heading ${f.kind === 'mover' ? f.zero || 0 : f.direction}°` : `heading ${i.direction}° · ${i.leds} LEDs`;
$('d-pos').textContent = `${i.x.toFixed(2)}, ${i.y.toFixed(2)} m · ${where}`;
const t = app.netAt.get(netSource(f));
$('d-packets').textContent = t === undefined ? 'nothing yet' : `last ${((performance.now() - t) / 1000).toFixed(1)} s ago`;
$('d-note').hidden = true;
return;
}
st.textContent = s.state + (s.error && s.state === 'crashed' ? ` – ${s.error.split('\n').slice(-2).join(' ')}` : ''); st.textContent = s.state + (s.error && s.state === 'crashed' ? ` – ${s.error.split('\n').slice(-2).join(' ')}` : '');
st.className = `state-${s.state}`; st.className = `state-${s.state}`;
const i = s.info;
$('d-pos').textContent = `${i.x.toFixed(2)}, ${i.y.toFixed(2)} m · heading ${i.direction}° · ${i.leds} LEDs`; $('d-pos').textContent = `${i.x.toFixed(2)}, ${i.y.toFixed(2)} m · heading ${i.direction}° · ${i.leds} LEDs`;
$('d-packets').textContent = `${s.rx} received · ${s.tx} sent`; $('d-packets').textContent = `${s.rx} received · ${s.tx} sent`;
const stale = s.state !== 'off' && s.bootedLeds && s.bootedLeds !== i.leds; const stale = s.state !== 'off' && s.bootedLeds && s.bootedLeds !== i.leds;
@@ -715,6 +934,117 @@
$('d-note').textContent = stale ? `Running with ${s.bootedLeds} LEDs: power-cycle it to use ${i.leds}.` : ''; $('d-note').textContent = stale ? `Running with ${s.bootedLeds} LEDs: power-cycle it to use ${i.leds}.` : '';
} }
/** A can's or mover's channels as they arrive, like the qlcplus detail panel. */
function renderLive() {
const s = app.selected;
const table = $('d-channels');
const f = s && app.room.fixtures[s.id];
if (!f || !s.info.point) {
table.hidden = true;
return;
}
renderFacts();
const def = app.room.dmx_definitions[f.dmx_def];
const names = def ? def.channels : [];
const values = (s.live && s.live.channels) || [];
table.hidden = false;
const body = table.tBodies[0];
if (body.rows.length !== names.length || body.dataset.def !== f.dmx_def || body.dataset.addr !== String(f.address)) {
body.dataset.def = f.dmx_def;
body.dataset.addr = String(f.address);
body.replaceChildren(...names.map((n, k) => {
const tr = document.createElement('tr');
tr.innerHTML = '<td class="muted"></td><td></td><td class="num"></td>';
tr.cells[0].textContent = String(f.address + k);
tr.cells[1].textContent = n;
return tr;
}));
}
for (let k = 0; k < names.length; k += 1) {
const v = values[k] || 0;
const cell = body.rows[k].cells[2];
if (cell.textContent !== String(v)) {
cell.textContent = String(v);
body.rows[k].classList.toggle('on', v > 0);
}
}
}
/** The controller output that would send to this fixture, or why there is none. */
function outputFor(f) {
const leds = RigLayout.fixtureLeds(app.room, f);
const base = { name: `sim ${f.label}`.slice(0, 60), host: '127.0.0.1', pixel_count: leds, color_order: f.color_order || 'rgb', enabled: true };
if (f.type === 'ddp') {
if (f.offset) {
return { why: 'Controller outputs send DDP from pixel 0: set First pixel to 0 to make one.' };
}
return { body: { ...base, protocol: 'ddp', port: f.port } };
}
if (f.type === 'artnet' && f.kind === 'pixels') {
if (f.address !== 1) {
return { why: 'Controller outputs send Art-Net pixels from channel 1: set the DMX address to 1 to make one.' };
}
return { body: { ...base, protocol: 'artnet', universe: f.universe } };
}
return { why: '' };
}
function renderOutput() {
const s = app.selected;
const f = s && app.room.fixtures[s.id];
const box = $('d-net');
const pixels = f && isNet(s) && !s.info.point;
box.hidden = !pixels;
if (!pixels) {
return;
}
const o = outputFor(f);
$('d-mkout').disabled = !o.body;
$('d-testout').hidden = !app.outputs.has(s.id);
if (!$('d-out-note').dataset.sticky) {
$('d-out-note').textContent = o.why || 'Adds an output in the controller\'s Outputs, sending to this sim (127.0.0.1).';
}
}
async function makeOutput() {
const s = app.selected;
const f = s && app.room.fixtures[s.id];
const o = f && outputFor(f);
if (!o || !o.body) {
return;
}
const note = $('d-out-note');
try {
const out = await api('POST', '/outputs', o.body);
const id = out && (out.id || (out.output && out.output.id));
app.outputs.set(s.id, id);
note.textContent = `Made output "${o.body.name}"${id ? ` (${id})` : ''}. Send test sends red, green, blue, white, then black.`;
} catch (err) {
note.textContent = `Could not make the output: ${err.message}`;
}
note.dataset.sticky = '1';
renderOutput();
}
async function testOutput() {
const s = app.selected;
const id = s && app.outputs.get(s.id);
if (!id) {
return;
}
const note = $('d-out-note');
$('d-testout').disabled = true;
note.textContent = 'Sending the test…';
try {
const r = await api('POST', `/outputs/${encodeURIComponent(id)}/test`, { step_s: 1 });
const st = (r && r.status) || {};
note.textContent = `Test sent: ${st.packets ?? '?'} packets${st.last_error ? ` · ${st.last_error}` : ''}.`;
} catch (err) {
note.textContent = `Test failed: ${err.message}`;
}
$('d-testout').disabled = false;
}
function renderEditForm() { function renderEditForm() {
const s = app.selected; const s = app.selected;
const f = s && app.room.fixtures[s.id]; const f = s && app.room.fixtures[s.id];
@@ -722,23 +1052,55 @@
if (!app.edit || !f) { if (!app.edit || !f) {
return; return;
} }
const type = f.type || 'espnow';
const point = RigLayout.isPoint(f);
const show = {
strip: !point,
ddp: type === 'ddp',
artnet: type === 'artnet',
pixels: type !== 'espnow' && !point,
dmx: point,
mover: point && f.kind === 'mover',
heading: !(point && f.kind === 'mover'),
};
for (const el of $('d-edit').querySelectorAll('[data-for]')) {
el.hidden = !show[el.dataset.for];
}
$('e-x-name').textContent = point ? 'x' : 'Pixel 0 x';
$('e-y-name').textContent = point ? 'y' : 'Pixel 0 y';
$('e-leds').max = String(type === 'espnow' ? 512 : NET_LEDS_MAX);
const set = (id, v) => {
if (document.activeElement !== $(id)) {
$(id).value = v;
}
};
if (!point) {
const sel = $('e-def'); const sel = $('e-def');
sel.replaceChildren( sel.replaceChildren(
...Object.entries(app.room.definitions).map( ...Object.entries(app.room.definitions).map(
([k, d]) => new Option(`${k} (${d.leds} LEDs, ${Math.round(1 / d.pitch_m)}/m)`, k, false, k === f.def), ([k, d]) => new Option(`${k} (${d.leds} LEDs, ${Math.round(1 / d.pitch_m)}/m)`, k, false, k === f.def),
), ),
); );
const set = (id, v) => {
if (document.activeElement !== $(id)) {
$(id).value = v;
}
};
set('e-label', f.label);
set('e-leds', f.leds ?? ''); set('e-leds', f.leds ?? '');
$('e-leds').placeholder = String(app.room.definitions[f.def].leds); $('e-leds').placeholder = String(app.room.definitions[f.def].leds);
} else {
$('e-dmxdef').replaceChildren(
...Object.entries(app.room.dmx_definitions).map(
([k, d]) => new Option(`${k} (${d.channels.length} ch)`, k, false, k === f.dmx_def),
),
);
}
set('e-label', f.label);
set('e-x', round3(f.x)); set('e-x', round3(f.x));
set('e-y', round3(f.y)); set('e-y', round3(f.y));
set('e-dir', f.direction); set('e-dir', f.direction);
set('e-port', f.port ?? 4048);
set('e-offset', f.offset ?? 0);
set('e-universe', f.universe ?? 0);
set('e-address', f.address ?? 1);
set('e-order', f.color_order || 'rgb');
set('e-zero', f.zero ?? 0);
$('e-panrev').checked = Boolean(f.pan_reverse);
} }
function renderDrawer() { function renderDrawer() {
@@ -764,9 +1126,19 @@
return; return;
} }
$('d-name').textContent = s.name; $('d-name').textContent = s.name;
$('d-meta').textContent = `${s.id} · ${s.mac}`; const f = app.room.fixtures[s.id] || {};
$('d-meta').textContent = isNet(s) ? `${s.id} · ${netWhere(f)}` : `${s.id} · ${s.mac}`;
$('d-power').hidden = isNet(s);
$('d-log-head').hidden = isNet(s);
$('d-log').hidden = isNet(s);
if (app.drawerFor !== s) {
app.drawerFor = s;
delete $('d-out-note').dataset.sticky;
}
renderFacts(); renderFacts();
renderEditForm(); renderEditForm();
renderOutput();
renderLive();
const off = s.state === 'off' || s.state === 'crashed'; const off = s.state === 'off' || s.state === 'crashed';
$('d-on').disabled = !off || app.takenOver; $('d-on').disabled = !off || app.takenOver;
$('d-off').disabled = off; $('d-off').disabled = off;
@@ -819,14 +1191,25 @@
if (raw === '' || !n) { if (raw === '' || !n) {
delete f.leds; delete f.leds;
} else { } else {
f.leds = Math.max(1, Math.min(512, n)); f.leds = Math.max(1, Math.min(isNet(s) ? NET_LEDS_MAX : 512, n));
} }
} else if (key === 'color_order' || key === 'dmx_def') {
f[key] = raw;
} else if (key === 'pan_reverse') {
f.pan_reverse = Boolean(raw);
} else if (['port', 'offset', 'universe', 'address'].includes(key)) {
const lim = { port: [1, 65535], offset: [0, NET_LEDS_MAX - 1], universe: [0, 32767], address: [1, 512] }[key];
const n = Math.round(Number(raw));
if (!Number.isFinite(n)) {
return;
}
f[key] = Math.max(lim[0], Math.min(lim[1], n));
} else { } else {
const v = Number(raw); const v = Number(raw);
if (!Number.isFinite(v)) { if (!Number.isFinite(v)) {
return; return;
} }
f[key] = key === 'direction' ? wrapDeg(v) : Math.round(v * 1000) / 1000; f[key] = key === 'direction' || key === 'zero' ? wrapDeg(v) : Math.round(v * 1000) / 1000;
} }
changed(); changed();
} }
@@ -847,9 +1230,191 @@
$('r-width').value = app.room.width; $('r-width').value = app.room.width;
$('r-depth').value = app.room.depth; $('r-depth').value = app.room.depth;
renderDefs(); renderDefs();
renderDmxDefs();
$('r-dmx-edit').hidden = true;
roomNote('');
$('room-dialog').showModal(); $('room-dialog').showModal();
} }
// ----- DMX definitions: the channel lists of the room's cans and movers -------------------
/** A line under the room dialog's DMX tools: what an import did (ok) or why it failed. */
function roomNote(text, ok = false) {
$('r-error').textContent = text;
$('r-error').className = ok ? 'muted small' : 'error';
}
function renderDmxDefs() {
const defs = app.room.dmx_definitions;
const rows = Object.entries(defs).map(([k, d]) => {
const used = Object.values(app.room.fixtures).filter((f) => f.dmx_def === k).length;
const tr = document.createElement('tr');
tr.innerHTML = '<td><code></code><div class="muted small"></div></td><td></td><td class="muted"></td><td></td><td></td>';
tr.querySelector('code').textContent = k;
tr.querySelector('div').textContent = [d.manufacturer, d.model].filter(Boolean).join(' ');
tr.cells[1].textContent = d.mode || '';
tr.cells[2].textContent = `${d.channels.length} ch · ${used ? `${used} fixture${used === 1 ? '' : 's'}` : 'unused'}`;
const edit = document.createElement('button');
edit.type = 'button';
edit.className = 'link';
edit.textContent = 'edit';
edit.onclick = () => openDmxEdit(k);
tr.cells[3].append(edit);
if (!used) {
const del = document.createElement('button');
del.type = 'button';
del.className = 'link';
del.textContent = 'remove';
del.onclick = () => {
delete defs[k];
changed();
renderDmxDefs();
};
tr.cells[4].append(del);
}
return tr;
});
if (!rows.length) {
const tr = document.createElement('tr');
tr.innerHTML = '<td colspan="5" class="muted">None yet. Adding a DMX can or mover adds a qlcplus preset.</td>';
rows.push(tr);
}
$('r-dmx').replaceChildren(...rows);
const presets = Object.keys(RigDmx.PRESET_DEFINITIONS).filter((k) => !(k in defs));
$('r-dmx-preset').replaceChildren(new Option(presets.length ? 'Add a preset…' : 'Presets: all added', ''),
...presets.map((k) => new Option(`${k} (${RigDmx.PRESET_DEFINITIONS[k].channels.length} ch)`, k)));
}
/** Edit (or, with no name, make) a DMX definition in the form under the table. */
function openDmxEdit(name, draft) {
const d = draft || app.room.dmx_definitions[name] || { manufacturer: '', model: '', mode: '', channels: [] };
app.dmxEditing = { name: name || '', d };
$('r-dmx-name').value = name || '';
$('r-dmx-mode').value = d.mode || '';
$('r-dmx-chans').value = d.channels.join('\n');
$('r-dmx-error').textContent = '';
$('r-dmx-edit').hidden = false;
$('r-dmx-name').focus();
}
function saveDmxEdit() {
const ed = app.dmxEditing;
const defs = app.room.dmx_definitions;
const name = $('r-dmx-name').value.trim();
const channels = $('r-dmx-chans').value.split('\n').map((c) => c.trim()).filter(Boolean);
const err = (t) => {
$('r-dmx-error').textContent = t;
};
if (!name || name.length > 60) {
return err('A definition needs a name (up to 60 characters).');
}
if (name !== ed.name && name in defs) {
return err('There is already a definition with that name.');
}
if (!channels.length || channels.length > 512 || channels.some((c) => c.length > 40)) {
return err('List 1-512 channels, one per line, each up to 40 characters.');
}
const d = { manufacturer: ed.d.manufacturer || '', model: ed.d.model || '', mode: $('r-dmx-mode').value.trim(), channels };
if (ed.name && ed.name !== name) {
delete defs[ed.name];
for (const f of Object.values(app.room.fixtures)) {
if (f.dmx_def === ed.name) {
f.dmx_def = name;
}
}
}
defs[name] = d;
$('r-dmx-edit').hidden = true;
changed();
renderDmxDefs();
}
async function readFile(input) {
const file = input.files && input.files[0];
input.value = '';
return file ? file.text() : null;
}
/** A QLC+ fixture definition: one DMX definition per mode, named "<model> <mode>". */
async function importQxf(input) {
const text = await readFile(input);
if (text === null) {
return;
}
let modes;
try {
modes = RigDmx.parseQxf(text);
} catch (err) {
roomNote(`Could not read that fixture definition: ${err.message}`);
return;
}
const defs = app.room.dmx_definitions;
for (const m of modes) {
let name = `${m.manufacturer} ${m.model}${modes.length > 1 ? ` ${m.mode}` : ''}`.trim().slice(0, 60) || 'fixture';
for (let n = 2; name in defs; n += 1) {
name = `${name.replace(/ \(\d+\)$/, '')} (${n})`;
}
defs[name] = { manufacturer: m.manufacturer.slice(0, 60), model: m.model.slice(0, 60), mode: m.mode.slice(0, 60),
channels: m.channels.map((c) => c.slice(0, 40)) };
}
roomNote(`Added ${modes.length} definition${modes.length === 1 ? '' : 's'} from the .qxf.`, true);
changed();
renderDmxDefs();
}
/** A qlcplus stage/map.json: its definitions, and its cans and movers placed in this room (y moved so they fit). */
async function importStageMap(input) {
const text = await readFile(input);
if (text === null) {
return;
}
let map;
try {
map = JSON.parse(text);
} catch (_e) {
roomNote('That file is not JSON.');
return;
}
const defs = app.room.dmx_definitions;
for (const [k, d] of Object.entries(map.definitions || {})) {
if (Array.isArray(d.channels) && d.channels.length) {
defs[k.slice(0, 60)] = { manufacturer: String(d.manufacturer || ''), model: String(d.model || ''),
mode: String(d.mode || ''), channels: d.channels.map((c) => String(c).slice(0, 40)) };
}
}
const fx = Object.entries(map.fixtures || {}).filter(([, f]) => Number.isFinite(f.x) && Number.isFinite(f.y));
const ys = fx.map(([, f]) => f.y);
const xs = fx.map(([, f]) => Math.abs(f.x));
const dy = ys.length ? 0.5 - Math.min(...ys) : 0;
let added = 0;
for (const [key, f] of fx) {
const kind = f.kind === 'mover' ? 'mover' : 'can';
const dmxDef = f.def && defs[f.def] ? f.def : dmxDefFor(kind);
let id = String(key).replace(/[^A-Za-z0-9_.#-]/g, '') || nextNetLabel(kind);
while (id in app.room.fixtures) {
id = nextNetLabel(id);
}
const address = f.address != null ? Number(f.address) + 1 : f.dmx != null ? Number(f.dmx) : nextDmxAddress(defs[dmxDef].channels.length).address;
app.room.fixtures[id] = {
label: String(f.label || key).slice(0, 47), type: 'artnet', kind, dmx_def: dmxDef,
universe: Number(f.universe) || 0, address, x: round3(f.x), y: round3(f.y + dy),
direction: wrapDeg(Number(f.direction) || 0),
...(kind === 'mover' ? { zero: wrapDeg(Number(f.zero) || 0), pan_reverse: Boolean(f.pan_reverse) } : {}),
};
added += 1;
}
if (fx.length) {
// grow the room to hold them
app.room.width = Math.max(app.room.width, Math.ceil((Math.max(...xs) * 2 + 1) * 10) / 10, Number(map.building_width) || 0);
app.room.depth = Math.max(app.room.depth, Math.ceil((Math.max(...ys) + dy + 0.5) * 10) / 10);
$('r-width').value = app.room.width;
$('r-depth').value = app.room.depth;
}
roomNote(`Added ${Object.keys(map.definitions || {}).length} definitions and ${added} fixtures from ${map.name || 'the stage map'}.`, true);
changed();
renderDmxDefs();
}
function renderDefs() { function renderDefs() {
const rows = Object.entries(app.room.definitions).map(([k, d]) => { const rows = Object.entries(app.room.definitions).map(([k, d]) => {
const used = Object.values(app.room.fixtures).filter((f) => f.def === k).length; const used = Object.values(app.room.fixtures).filter((f) => f.def === k).length;
@@ -904,6 +1469,21 @@
} }
}; };
} }
$('r-dmx-preset').onchange = () => {
const k = $('r-dmx-preset').value;
if (k && !(k in app.room.dmx_definitions)) {
app.room.dmx_definitions[k] = JSON.parse(JSON.stringify(RigDmx.PRESET_DEFINITIONS[k]));
changed();
}
renderDmxDefs();
};
$('r-dmx-new').onclick = () => openDmxEdit('');
$('r-dmx-cancel').onclick = () => {
$('r-dmx-edit').hidden = true;
};
$('r-dmx-save').onclick = saveDmxEdit;
$('r-dmx-qxf').onchange = () => importQxf($('r-dmx-qxf'));
$('r-dmx-map').onchange = () => importStageMap($('r-dmx-map'));
$('r-add-def').onclick = () => { $('r-add-def').onclick = () => {
const name = $('r-def-name').value.trim(); const name = $('r-def-name').value.trim();
const leds = Math.round(Number($('r-def-leds').value)); const leds = Math.round(Number($('r-def-leds').value));
@@ -1113,8 +1693,41 @@
s.lit = lit; s.lit = lit;
} }
/** A can or mover: its light under everything, its body on top (see frame). */
function pointFixture(s) {
const f = app.room.fixtures[s.id] || {};
return { id: s.id, kind: s.kind, label: s.name, x: s.info.x, y: s.info.y, direction: f.direction || 0, zero: f.zero || 0 };
}
function drawPointHandle(s, sg) {
if (!app.edit) {
return;
}
const ctx = app.ctx;
ctx.strokeStyle = app.sel.has(s) ? SELECT : LABEL;
ctx.lineWidth = 1.5;
ctx.setLineDash([3, 3]);
ctx.beginPath();
ctx.moveTo(sg.ax, sg.ay);
ctx.lineTo(sg.bx, sg.by);
ctx.stroke();
ctx.setLineDash([]);
ctx.beginPath();
ctx.arc(sg.bx, sg.by, HANDLE_R, 0, Math.PI * 2);
ctx.stroke();
}
function frame() { function frame() {
if (app.view && app.dirty) { if (app.room && app.netDirty) {
app.netDirty = false;
updateNet();
app.dirty = true;
if (app.selected && isNet(app.selected)) {
renderLive();
}
}
const animated = app.room && app.strips.some((s) => s.info.point && s.live && RigDmxDraw.animated(pointFixture(s), s.live));
if (app.view && (app.dirty || animated)) {
app.dirty = false; app.dirty = false;
const ctx = app.ctx; const ctx = app.ctx;
const c = app.canvas; const c = app.canvas;
@@ -1122,7 +1735,24 @@
ctx.fillStyle = BG; ctx.fillStyle = BG;
ctx.fillRect(0, 0, c.width / app.dpr, c.height / app.dpr); ctx.fillRect(0, 0, c.width / app.dpr, c.height / app.dpr);
drawRoom(); drawRoom();
app.strips.forEach((s, i) => drawStrip(s, app.geo[i])); app.strips.forEach((s, i) => !s.info.point && drawStrip(s, app.geo[i]));
const points = app.strips.map((s, i) => [s, app.geo[i]]).filter(([s]) => s.info.point);
if (points.length) {
const v = app.view;
ctx.save();
ctx.beginPath();
ctx.rect(v.sx(-app.room.width / 2), v.sy(app.room.depth), app.room.width * v.scale, app.room.depth * v.scale);
ctx.clip(); // beams stay on the floor
ctx.globalCompositeOperation = 'lighter';
for (const [s] of points) {
RigDmxDraw.drawLight(ctx, v, pointFixture(s), s.live || { patched: false });
}
ctx.restore();
for (const [s, sg] of points) {
drawPointHandle(s, sg);
s.bodyR = RigDmxDraw.drawBody(ctx, v, pointFixture(s), s.live || { patched: false }, app.sel.has(s));
}
}
if (app.marquee) { if (app.marquee) {
const m = app.marquee; const m = app.marquee;
ctx.save(); ctx.save();
@@ -1140,6 +1770,9 @@
/** Whether a strip's segment passes through the box (canvas px), sampled along its length. */ /** Whether a strip's segment passes through the box (canvas px), sampled along its length. */
function stripTouchesBox(sg, x0, y0, x1, y1) { function stripTouchesBox(sg, x0, y0, x1, y1) {
if (sg.point) {
return sg.ax >= x0 && sg.ax <= x1 && sg.ay >= y0 && sg.ay <= y1;
}
for (let i = 0; i <= 20; i += 1) { for (let i = 0; i <= 20; i += 1) {
const t = i / 20; const t = i / 20;
const x = sg.ax + (sg.bx - sg.ax) * t; const x = sg.ax + (sg.bx - sg.ax) * t;
@@ -1164,7 +1797,8 @@
let best = null; let best = null;
let bestD = 10; let bestD = 10;
app.strips.forEach((s, i) => { app.strips.forEach((s, i) => {
const d = RigLayout.distToStrip(app.geo[i], x, y); const sg = app.geo[i];
const d = sg.point ? Math.max(0, Math.hypot(x - sg.ax, y - sg.ay) - (s.bodyR || 13)) : RigLayout.distToStrip(sg, x, y);
if (d < bestD) { if (d < bestD) {
bestD = d; bestD = d;
best = s; best = s;
@@ -1309,7 +1943,8 @@
} }
} else { } else {
const deg = (Math.atan2(wx - f.x, wy - f.y) * 180) / Math.PI; const deg = (Math.atan2(wx - f.x, wy - f.y) * 180) / Math.PI;
f.direction = wrapDeg(ev.shiftKey ? deg : Math.round(deg / SNAP_DEG) * SNAP_DEG); f[f.type === 'artnet' && f.kind === 'mover' ? 'zero' : 'direction'] =
wrapDeg(ev.shiftKey ? deg : Math.round(deg / SNAP_DEG) * SNAP_DEG);
} }
d.moved = true; d.moved = true;
const infos = new Map(RigLayout.roomStrips(app.room).map((i) => [i.id, i])); const infos = new Map(RigLayout.roomStrips(app.room).map((i) => [i.id, i]));
@@ -1387,6 +2022,18 @@
); );
}; };
$('centre-strips').onclick = () => centreStrips(); $('centre-strips').onclick = () => centreStrips();
try {
$('add-type').value = localStorage.getItem('ledsim.addType') || 'espnow';
} catch (_e) {
// storage unavailable: start with ESP-NOW bars
}
$('add-type').onchange = () => {
try {
localStorage.setItem('ledsim.addType', $('add-type').value);
} catch (_e) {
// the choice lasts for this page only
}
};
$('d-close').onclick = () => select(null); $('d-close').onclick = () => select(null);
$('d-on').onclick = () => app.selected && powerOn(app.selected); $('d-on').onclick = () => app.selected && powerOn(app.selected);
$('d-off').onclick = () => app.selected && powerOff(app.selected); $('d-off').onclick = () => app.selected && powerOff(app.selected);
@@ -1404,6 +2051,21 @@
$('e-x').onchange = () => fixtureField('x', $('e-x').value); $('e-x').onchange = () => fixtureField('x', $('e-x').value);
$('e-y').onchange = () => fixtureField('y', $('e-y').value); $('e-y').onchange = () => fixtureField('y', $('e-y').value);
$('e-dir').onchange = () => fixtureField('direction', $('e-dir').value); $('e-dir').onchange = () => fixtureField('direction', $('e-dir').value);
for (const [id, key] of [['e-port', 'port'], ['e-offset', 'offset'], ['e-universe', 'universe'], ['e-address', 'address'],
['e-order', 'color_order'], ['e-dmxdef', 'dmx_def'], ['e-zero', 'zero']]) {
$(id).onchange = () => fixtureField(key, $(id).value);
}
$('e-panrev').onchange = () => fixtureField('pan_reverse', $('e-panrev').checked);
$('d-mkout').onclick = makeOutput;
$('d-testout').onclick = testOutput;
setInterval(() => {
if (app.selected && isNet(app.selected)) {
renderFacts(); // "last … s ago"
}
if (app.strips.some(isNet)) {
app.netDirty = true; // a fixture whose data stopped goes back to "no data"
}
}, 500);
wireDialogs(); wireDialogs();
wireCanvas(); wireCanvas();
new ResizeObserver(() => layoutView()).observe($('rig')); new ResizeObserver(() => layoutView()).observe($('rig'));
+343
View File
@@ -0,0 +1,343 @@
/* Drawing the simulated rig's DMX cans and movers: glow, beam, floor spot and body.
* Ported from the qlcplus stage simulator (technicalkiwi/qlcplus simulator/static/app.js), same look and timing.
* Headings are degrees clockwise from +y, y up the screen, as in both sims. The live view is RigDmx.viewFixture().
*
* RigDmxDraw.drawLight(ctx, view, fixture, live) beam and glow (call with globalCompositeOperation 'lighter')
* RigDmxDraw.drawBody(ctx, view, fixture, live, selected)
* RigDmxDraw.animated(live) whether it changes with time (strobe, chase, smoothing)
*
* view: {sx(x), sy(y), scale}: metres -> canvas px; fixture: {id, kind: 'can'|'mover', label, x, y, direction, zero}
*/
(function (g) {
'use strict';
const PAR_PALETTE = [
[255, 0, 0], [255, 96, 0], [255, 200, 0], [255, 255, 0], [0, 255, 0],
[0, 255, 160], [0, 64, 255], [140, 0, 255], [255, 0, 160], [255, 255, 255],
];
// Below this plan reach a mover is pointing near straight down.
const SPOT_M = 0.5;
// Throw to the floor for the spot under a mover.
const DROP_M = 2.5;
// A can's beam: fixed along its heading.
const CAN_BEAM = { beam: 2.2, zoom: 25, focus: 0.35 };
const aims = new Map();
const now = () => performance.now() / 1000;
function luma(r, gr, b) {
return 0.2126 * r + 0.7152 * gr + 0.0722 * b;
}
function hsv(hue, value) {
const h = ((hue % 1) + 1) % 1;
const i = Math.floor(h * 6);
const f = h * 6 - i;
const q = value * (1 - f);
const t = value * f;
const map = [[value, t, 0], [q, value, 0], [0, value, t], [0, q, value], [t, 0, value], [value, 0, q]];
return map[i % 6].map((c) => Math.round(c * 255));
}
function scaleColour(colour, dimmer) {
const level = (dimmer || 0) / 255;
return colour.map((c) => Math.round(c * level));
}
function paletteColour(live, gradient) {
const palette = live.palette && live.palette.length ? live.palette : PAR_PALETTE;
const phase = now() * (live.speed_hz || 0.35);
const index = Math.floor(phase) % palette.length;
if (!gradient) {
return palette[index];
}
const next = palette[(index + 1) % palette.length];
const blend = phase - Math.floor(phase);
return palette[index].map((c, slot) => Math.round(c + (next[slot] - c) * blend));
}
function canColour(live) {
const mode = live.function || 'mix';
const dimmer = live.dimmer || 0;
if (mode === 'jump' || mode === 'gradient') {
return scaleColour(paletteColour(live, mode === 'gradient'), dimmer);
}
if (mode === 'pulse') {
const wave = 0.5 - 0.5 * Math.cos(now() * (live.speed_hz || 0.4) * Math.PI * 2);
const depth = 0.05 + 0.95 * wave;
return [live.r || 0, live.g || 0, live.b || 0].map((c) => Math.round(c * depth));
}
if (mode === 'sound') {
const speed = live.speed_hz || 1;
const variant = live.sound === 2 ? 2 : 1;
const bpm = (variant === 2 ? 156 : 104) * (0.55 + Math.min(speed, 8) / 10);
const beat = ((now() * bpm) / 60) % 1;
let hit = beat < 0.08 ? 1 : 0.04;
if (variant === 2 && beat > 0.5 && beat < 0.58) {
hit = 1;
}
const colour = (live.palette && live.palette[variant === 2 ? 4 : 0]) || PAR_PALETTE[variant === 2 ? 4 : 0];
return scaleColour(colour, dimmer).map((c) => Math.round(c * hit));
}
return [live.r || 0, live.g || 0, live.b || 0];
}
function effectPixels(live) {
const source = (live.pixels || []).map((p) => p.slice());
if (!live.dynamic || !source.length) {
return source;
}
const count = source.length;
const lit = source.find((p) => p[0] + p[1] + p[2] > 0);
const fallback = lit || scaleColour([255, 255, 255], live.dimmer || 0);
const t = now() * (live.speed_hz || 1);
return source.map((pixel, index) => {
const colour = pixel[0] + pixel[1] + pixel[2] > 0 ? pixel : fallback;
if (live.dynamic === 'rainbow') {
return hsv((t * 0.2 + index / count) % 1, (live.dimmer || 0) / 255);
}
let level = 1;
if (live.dynamic === 'chase') {
level = Math.floor(t) % count === index ? 1 : 0.08;
} else if (live.dynamic === 'reverse') {
level = Math.floor(t) % count === count - 1 - index ? 1 : 0.08;
} else if (live.dynamic === 'bounce') {
const span = Math.max(1, count - 1);
level = Math.round(Math.abs((t % (2 * span)) - span)) === index ? 1 : 0.08;
} else if (live.dynamic === 'pulse') {
level = 0.15 + 0.85 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2));
} else if (live.dynamic === 'pairs') {
level = Math.floor(t) % 2 === index % 2 ? 1 : 0.08;
}
return colour.map((c) => Math.round(c * level));
});
}
function mixPixels(pixels) {
let red = 0, green = 0, blue = 0, weight = 0;
for (const p of pixels) {
const w = p[0] + p[1] + p[2];
red += p[0] * w;
green += p[1] * w;
blue += p[2] * w;
weight += w;
}
return weight <= 0 ? [0, 0, 0] : [Math.round(red / weight), Math.round(green / weight), Math.round(blue / weight)];
}
function shutter(live) {
if (!live.strobe_hz) {
return 1;
}
const t = now();
if (live.strobe_mode === 'random') {
const bucket = Math.floor(t * live.strobe_hz);
return (Math.abs(Math.sin(bucket * 12.9898) * 43758.5453) % 1) > 0.55 ? 1 : 0;
}
const period = 1 / live.strobe_hz;
return t % period < period * 0.42 ? 1 : 0;
}
// Pan and reach ease toward the target at the fixture's Pan/Tilt Speed
function aimed(id, live, zero) {
const targetPan = (zero || 0) + (live.pan_deg || 0);
const targetBeam = live.beam_m || 0;
const t = now();
let st = aims.get(id);
if (!st) {
st = { pan: targetPan, beam: targetBeam, t, settled: true };
aims.set(id, st);
return st;
}
const dt = Math.min(0.05, Math.max(0, t - st.t));
st.t = t;
const fast = live.move == null ? 1 : live.move;
if (fast > 0.97) {
st.pan = targetPan;
st.beam = targetBeam;
} else {
const k = 1 - Math.exp(-dt / (0.05 + (1 - fast) * 1.8));
st.pan += (targetPan - st.pan) * k;
st.beam += (targetBeam - st.beam) * k;
}
st.settled = Math.abs(targetPan - st.pan) < 0.05 && Math.abs(targetBeam - st.beam) < 0.002;
return st;
}
function appearance(fixture, live) {
const pixels = fixture.kind === 'mover' ? effectPixels(live) : null;
const [r, gr, b] = fixture.kind === 'can'
? canColour(live)
: pixels && live.dynamic ? mixPixels(pixels) : [live.r || 0, live.g || 0, live.b || 0];
const gate = shutter(live);
return {
r: Math.round(r * gate),
g: Math.round(gr * gate),
b: Math.round(b * gate),
dimmer: live.dimmer || 0,
pixels: pixels && pixels.map((p) => p.map((c) => Math.round(c * gate))),
};
}
function drawGlow(ctx, v, fixture, color) {
const level = (color.r + color.g + color.b) / (255 * 3);
if (level <= 0.01) {
return;
}
const x = v.sx(fixture.x);
const y = v.sy(fixture.y);
const radius = (fixture.kind === 'mover' ? 70 : 54) * (0.45 + level) * bodyScale(v);
const gradient = ctx.createRadialGradient(x, y, 2, x, y, radius);
gradient.addColorStop(0, `rgba(${color.r},${color.g},${color.b},${0.55 * level + 0.15})`);
gradient.addColorStop(1, `rgba(${color.r},${color.g},${color.b},0)`);
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
}
function drawSpot(ctx, v, fixture, pan, reach, half, color, spread) {
const rad = (pan * Math.PI) / 180;
const cx = v.sx(fixture.x + Math.sin(rad) * reach);
const cy = v.sy(fixture.y + Math.cos(rad) * reach);
const radius = Math.max(4, DROP_M * Math.tan(half) * v.scale);
const gradient = ctx.createRadialGradient(cx, cy, 0, cx, cy, radius);
const alpha = 0.85 * (1 - spread * 0.35);
gradient.addColorStop(0, `rgba(${color.r},${color.g},${color.b},${alpha})`);
gradient.addColorStop(0.7, `rgba(${color.r},${color.g},${color.b},${alpha * 0.6})`);
gradient.addColorStop(1, `rgba(${color.r},${color.g},${color.b},0)`);
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, Math.PI * 2);
ctx.fill();
}
function drawBeam(ctx, v, fixture, live, color, fixed) {
const level = (color.r + color.g + color.b) / 255;
if (live.patched === false || level <= 0.02) {
return;
}
const aim = fixed || aimed(fixture.id, live, fixture.zero);
// Mover reach is signed: below zero the head has tilted past straight down.
const reach = fixed ? fixed.beam : aim.beam;
// DMX focus 0 is a wide wash. Focus 255 holds the zoom angle. Fixed beams pass spread: 0 tight, 1 wide.
const spread = fixed ? fixed.focus : 1 - (live.focus || 0);
const zoom = fixed ? fixed.zoom : live.zoom_deg || 8;
const tight = zoom / 2;
const wide = Math.max(tight, 40);
const half = ((tight + (wide - tight) * spread) * Math.PI) / 180;
if (fixture.kind === 'mover' && Math.abs(reach) < SPOT_M) {
drawSpot(ctx, v, fixture, aim.pan, reach, half, color, spread);
return;
}
const length = Math.abs(reach);
if (!length) {
return;
}
const rad = ((aim.pan + (reach < 0 ? 180 : 0)) * Math.PI) / 180;
const at = (a) => [v.sx(fixture.x + Math.sin(a) * length), v.sy(fixture.y + Math.cos(a) * length)];
const tip = at(rad);
const left = at(rad - half);
const right = at(rad + half);
const x0 = v.sx(fixture.x);
const y0 = v.sy(fixture.y);
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(left[0], left[1]);
ctx.lineTo(right[0], right[1]);
ctx.closePath();
const gradient = ctx.createLinearGradient(x0, y0, tip[0], tip[1]);
const alpha = 0.85 * (1 - spread * 0.35);
gradient.addColorStop(0, `rgba(${color.r},${color.g},${color.b},${alpha})`);
gradient.addColorStop(1, `rgba(${color.r},${color.g},${color.b},0)`);
ctx.fillStyle = gradient;
ctx.fill();
}
function lensRotation(live) {
if (live.spin_dps) {
return (now() * live.spin_dps * Math.PI) / 180;
}
return ((live.lens_deg || 0) * Math.PI) / 180;
}
// Bodies are drawn at a fixed pixel size in qlcplus; here they follow the zoom a little so a big room stays legible
function bodyScale(v) {
return Math.max(0.6, Math.min(1.6, v.scale / 90));
}
/** Beam and glow. Call with ctx.globalCompositeOperation = 'lighter'. */
function drawLight(ctx, v, fixture, live) {
const color = appearance(fixture, live);
if (fixture.kind === 'mover') {
drawBeam(ctx, v, fixture, live, color, null);
} else {
drawBeam(ctx, v, fixture, live, color, { pan: fixture.direction || 0, ...CAN_BEAM });
}
drawGlow(ctx, v, fixture, color);
}
function drawBody(ctx, v, fixture, live, selected) {
const color = appearance(fixture, live);
const x = v.sx(fixture.x);
const y = v.sy(fixture.y);
const pixels = color.pixels || [];
const head = fixture.kind === 'mover' && pixels.length ? pixels[0] : [color.r, color.g, color.b];
const lit = head[0] + head[1] + head[2] > 8;
const k = bodyScale(v);
const size = (fixture.kind === 'mover' ? 15 : 13) * k;
ctx.beginPath();
if (fixture.kind === 'mover') {
ctx.rect(x - size, y - size, size * 2, size * 2);
} else {
ctx.arc(x, y, size, 0, Math.PI * 2);
}
ctx.fillStyle = lit ? `rgb(${head[0]},${head[1]},${head[2]})` : '#2a2a30';
ctx.fill();
ctx.lineWidth = selected ? 2.5 : 1.5;
ctx.strokeStyle = selected ? '#5aa9ff' : live.patched === false ? '#5c5c66' : '#c8c8d0';
ctx.stroke();
if (fixture.kind === 'mover' && pixels.length > 1) {
const ring = pixels.slice(1);
const spin = lensRotation(live);
ring.forEach((p, index) => {
const angle = spin + (index / ring.length) * Math.PI * 2 - Math.PI / 2;
ctx.beginPath();
ctx.arc(x + Math.cos(angle) * (size + 7 * k), y + Math.sin(angle) * (size + 7 * k), 3.5 * k, 0, Math.PI * 2);
ctx.fillStyle = p[0] + p[1] + p[2] > 0 ? `rgb(${p[0]},${p[1]},${p[2]})` : '#333';
ctx.fill();
});
}
if (fixture.kind === 'can') {
// a tick on the rim shows the way the can points
const a = ((fixture.direction || 0) * Math.PI) / 180;
ctx.beginPath();
ctx.moveTo(x + Math.sin(a) * size, y - Math.cos(a) * size);
ctx.lineTo(x + Math.sin(a) * (size + 6 * k), y - Math.cos(a) * (size + 6 * k));
ctx.lineWidth = 2;
ctx.strokeStyle = selected ? '#5aa9ff' : '#c8c8d0';
ctx.stroke();
}
ctx.fillStyle = lit && luma(head[0], head[1], head[2]) > 140 ? '#16161a' : '#f2f2f4';
ctx.font = `600 ${Math.round(11 * k)}px system-ui, sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(fixture.label, x, y);
ctx.textBaseline = 'alphabetic';
return size;
}
/** Whether the fixture's look changes with time, so the canvas must keep redrawing. */
function animated(fixture, live) {
if (live.strobe_hz || live.dynamic || live.spin_dps) {
return true;
}
if (fixture.kind === 'can' && ['jump', 'gradient', 'pulse', 'sound'].includes(live.function)) {
return true;
}
const st = aims.get(fixture.id);
return fixture.kind === 'mover' && !!st && !st.settled;
}
g.RigDmxDraw = { drawLight, drawBody, animated, bodyScale };
})(typeof self !== 'undefined' ? self : globalThis);
+492
View File
@@ -0,0 +1,492 @@
// DMX fixtures for the simulated rig: a frame's channels to colour, beam and strobe.
// Ported from the qlcplus stage simulator (technicalkiwi/qlcplus simulator/decode.py), same rules and constants.
// Channel order comes from the room's DMX definitions: names such as Dimmer, Red, Pan and Zoom select the slots.
// Loaded as a classic script before app.js: everything is on RigDmx.
(function (g) {
'use strict';
const PIXEL = /^(red|green|blue|white) (\d+)$/i;
const PAN_DEGREES = 540.0;
// Tilt 127 is straight down. 0 leans along the pan heading, 255 away from it.
const TILT_DEGREES = 270.0;
// Plan reach of a beam at or above horizontal.
const BEAM_MAX_M = 4.7;
const ZOOM_MIN = 5.0;
const ZOOM_MAX = 45.0;
// BCC145 8ch: strobe 0–7 is open. Small Eye centre strobe 0–3 is open.
const CAN_STROBE_OPEN = 7;
const MOVER_STROBE_OPEN = 3;
// beamZ BCC145 8ch macro: 0–50 RGBW mix, 51–100 fixed colour, 101–150 jump, 151–200 pulse,
// 201–250 gradient, 251–255 sound. Speed is slow to fast.
const PAR_PALETTE = [
[255, 0, 0], [255, 96, 0], [255, 200, 0], [255, 255, 0], [0, 255, 0],
[0, 255, 160], [0, 64, 255], [140, 0, 255], [255, 0, 160], [255, 255, 255],
];
// Small Eye 43ch colour macros, static masks, and dynamic chases. 0–9 is no function.
const MOVER_MACROS = [
[255, 0, 0], [255, 80, 0], [255, 255, 0], [0, 255, 0], [0, 255, 255],
[0, 40, 255], [160, 0, 255], [255, 0, 180], [255, 255, 255], [255, 180, 80],
];
const STATIC_MASKS = [
['all', [1, 1, 1, 1, 1, 1, 1]],
['odds', [1, 0, 1, 0, 1, 0, 1]],
['evens', [0, 1, 0, 1, 0, 1, 0]],
['center', [0, 0, 0, 1, 0, 0, 0]],
['ends', [1, 0, 0, 0, 0, 0, 1]],
['left', [1, 1, 1, 1, 0, 0, 0]],
['right', [0, 0, 0, 1, 1, 1, 1]],
['one', null],
];
const DYNAMIC = ['chase', 'reverse', 'rainbow', 'bounce', 'pulse', 'pairs'];
const DYNAMIC_LABELS = {
chase: 'chase', reverse: 'reverse chase', rainbow: 'rainbow', bounce: 'bounce', pulse: 'pixel pulse', pairs: 'pairs',
};
const MOVER_43 = [
'Pan', 'Pan Fine', 'Tilt', 'Tilt Fine', 'Pan/Tilt Speed', 'Lens Rotate', 'Zoom', 'Focus',
'Center Brightness', 'Center Strobe',
'Red 1', 'Green 1', 'Blue 1', 'White 1',
'Red 2', 'Green 2', 'Blue 2', 'White 2',
'Red 3', 'Green 3', 'Blue 3', 'White 3',
'Red 4', 'Green 4', 'Blue 4', 'White 4',
'Red 5', 'Green 5', 'Blue 5', 'White 5',
'Red 6', 'Green 6', 'Blue 6', 'White 6',
'Red 7', 'Green 7', 'Blue 7', 'White 7',
'Colour Temperature', 'Colour Macro', 'Static Effect', 'Dynamic Effect', 'Reset',
];
/** The two fixtures of the qlcplus stage map, as DMX definitions. */
const PRESET_DEFINITIONS = {
'beamZ BCC145': {
manufacturer: 'beamZ', model: 'BCC145', mode: '8 Channel',
channels: ['Dimmer', 'Strobe', 'Red', 'Green', 'Blue', 'White', 'Macro', 'Speed'],
},
'Small Eye 7 Mover': { manufacturer: 'Small Eye 7', model: 'Mover', mode: '43 Channel', channels: MOVER_43.slice() },
};
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
const r2 = (v, d) => Math.round(v * 10 ** d) / 10 ** d + 0; // + 0: no -0
function find(names, wanted) {
const w = wanted.toLowerCase();
const i = names.findIndex((n) => n.toLowerCase() === w);
return i < 0 ? null : i;
}
function value(channels, names, wanted, dflt = 0) {
const i = find(names, wanted);
return i === null || i >= channels.length ? dflt : channels[i];
}
function mixRgbw(red, green, blue, white, dimmer) {
const level = clamp(dimmer, 0, 255) / 255;
return [
Math.round(Math.min(255, red + white) * level),
Math.round(Math.min(255, green + white) * level),
Math.round(Math.min(255, blue + white) * level),
];
}
function pixelGroups(channels, names, dimmer) {
const groups = new Map();
names.forEach((name, i) => {
const m = PIXEL.exec(name.trim());
if (!m) {
return;
}
const n = Number(m[2]);
if (!groups.has(n)) {
groups.set(n, {});
}
groups.get(n)[m[1].toLowerCase()] = i;
});
const at = (g, c) => (g[c] === undefined || g[c] >= channels.length ? 0 : channels[g[c]]);
return [...groups.keys()].sort((a, b) => a - b).map((n) => {
const g = groups.get(n);
return mixRgbw(at(g, 'red'), at(g, 'green'), at(g, 'blue'), at(g, 'white'), dimmer);
});
}
/** count slots from a 0-based address in a 512-byte frame */
function slotsAt(frame, address, count) {
const out = [];
for (let o = 0; o < count; o++) {
const i = address + o;
out.push(frame && i >= 0 && i < frame.length ? frame[i] : 0);
}
return out;
}
function strobeHz(v, openMax) {
if (v <= openMax) {
return 0;
}
const span = Math.max(1, 255 - openMax);
return r2(1 + ((v - openMax) / span) * 18, 2);
}
/** Indexed lens position, 0–60°. Spin ranges are not an index. */
function lensAngle(v) {
return v <= 127 ? r2((v / 127) * 60, 1) : 0;
}
/** Degrees per second, negative counter-clockwise: 0–127 index, 128–188 CCW fast to slow, 189–193 stop, 194–255 CW. */
function lensSpin(v) {
if (v >= 128 && v <= 188) {
return r2(-(40 + ((188 - v) / 60) * 320), 1);
}
if (v >= 194 && v <= 255) {
return r2(40 + ((v - 194) / 61) * 320, 1);
}
return 0;
}
/** Brightness-weighted mix, so one lit pixel stays its own colour. */
function beamColour(pixels) {
let red = 0, green = 0, blue = 0, weight = 0;
for (const [pr, pg, pb] of pixels) {
const w = pr + pg + pb;
red += pr * w;
green += pg * w;
blue += pb * w;
weight += w;
}
return weight <= 0 ? [0, 0, 0] : [Math.round(red / weight), Math.round(green / weight), Math.round(blue / weight)];
}
function scale(colour, dimmer) {
const level = clamp(dimmer, 0, 255) / 255;
return colour.map((c) => Math.round(c * level));
}
function speedHz(speed, slow = 0.35, fast = 8.0) {
return r2(slow + (clamp(speed, 0, 255) / 255) * (fast - slow), 2);
}
function canMode(macro) {
if (macro <= 50) return 'mix';
if (macro <= 100) return 'fixed';
if (macro <= 150) return 'jump';
if (macro <= 200) return 'pulse';
if (macro <= 250) return 'gradient';
return 'sound';
}
/** Map value onto count bands from start through 255: [index, 0–1 position], or null. */
function rangePick(v, start, count) {
if (v < start || count <= 0) {
return null;
}
const span = 256 - start;
const index = Math.min(count - 1, Math.floor(((v - start) * count) / span));
const band = span / count;
const frac = (v - start - index * band) / band;
return [index, clamp(frac, 0, 0.999)];
}
/** 0 leaves the colour alone. Higher values warm it, the way a CTO does. */
function applyCto(red, green, blue, amount) {
if (amount <= 0) {
return [red, green, blue];
}
const warm = clamp(amount, 0, 255) / 255;
return [red, Math.round(green * (1 - 0.35 * warm)), Math.round(blue * (1 - 0.75 * warm))];
}
const CAN_LABELS = {
mix: 'RGBW', fixed: 'fixed colour', jump: 'colour jump', pulse: 'colour pulse', gradient: 'colour gradient',
};
function canView(dimmer, strobe, red, green, blue, white, macro, speed, channels) {
const mode = canMode(macro);
const mixed = mixRgbw(red, green, blue, white, dimmer);
let peak = mixRgbw(red, green, blue, white, 255);
if (peak.every((c) => c === 0)) {
peak = [255, 255, 255];
}
let shown = mixed;
let palette = null;
let sound = 0;
let hz = 0;
if (mode === 'fixed') {
const index = Math.min(PAR_PALETTE.length - 1, Math.floor((Math.max(0, macro - 51) * PAR_PALETTE.length) / 50));
shown = scale(PAR_PALETTE[index], dimmer);
} else if (mode === 'pulse') {
shown = scale(peak, dimmer);
hz = speedHz(speed, 0.4, 6.0);
} else if (mode === 'jump' || mode === 'gradient' || mode === 'sound') {
palette = PAR_PALETTE.map((c) => c.slice());
hz = speedHz(speed);
shown = scale(PAR_PALETTE[0], dimmer);
if (mode === 'sound') {
sound = macro >= 254 ? 2 : 1;
}
}
const view = {
r: shown[0], g: shown[1], b: shown[2],
dimmer,
strobe_hz: strobeHz(strobe, CAN_STROBE_OPEN),
strobe_mode: strobe > CAN_STROBE_OPEN ? 'strobe' : 'open',
effect: mode !== 'mix',
function: mode,
function_label: mode === 'sound' ? (sound === 2 ? 'sound 2' : 'sound 1') : CAN_LABELS[mode],
speed_hz: hz,
sound,
channels,
};
if (palette) {
view.palette = palette;
}
return view;
}
function decodeCan(channels) {
const at = (i) => (i < channels.length ? channels[i] : 0);
return canView(at(0), at(1), at(2), at(3), at(4), at(5), at(6), at(7), channels);
}
function decodeCanNamed(channels, names) {
const dimmer = find(names, 'Dimmer') === null ? 255 : value(channels, names, 'Dimmer');
return canView(
dimmer,
value(channels, names, 'Strobe'),
value(channels, names, 'Red'),
value(channels, names, 'Green'),
value(channels, names, 'Blue'),
value(channels, names, 'White'),
value(channels, names, 'Macro'),
value(channels, names, 'Speed'),
channels,
);
}
/** Centre strobe: open, linear strobe, then three random-strobe bands. */
function moverStrobe(v) {
if (v <= MOVER_STROBE_OPEN) return [0, 'open'];
if (v <= 200) return [strobeHz(v, MOVER_STROBE_OPEN), 'strobe'];
if (v <= 215) return [6, 'random'];
if (v <= 234) return [12, 'random'];
return [18, 'random'];
}
function decodeMoverNamed(channels, names) {
const v = (n) => value(channels, names, n);
const pan = (v('Pan') << 8) | v('Pan Fine');
const tilt = (v('Tilt') << 8) | v('Tilt Fine');
const zoom = v('Zoom');
const rotate = v('Lens Rotate');
const dimmer = find(names, 'Center Brightness') === null ? 255 : v('Center Brightness');
const strobe = v('Center Strobe');
const pixels = pixelGroups(channels, names, dimmer);
const cto = v('Colour Temperature');
const macro = rangePick(v('Colour Macro'), 10, MOVER_MACROS.length);
const stat = rangePick(v('Static Effect'), 10, STATIC_MASKS.length);
const dynamic = rangePick(v('Dynamic Effect'), 10, DYNAMIC.length);
let source = pixels.map((p) => p.slice());
let fn = 'pixels';
let label = 'pixels';
let dynamicName = null;
let speed = 0;
if (macro) {
const colour = scale(MOVER_MACROS[macro[0]], dimmer);
source = Array.from({ length: 7 }, () => colour.slice());
fn = 'macro';
label = 'colour macro';
}
if ((stat || dynamic) && !source.some((p) => p[0] + p[1] + p[2] > 0)) {
const white = scale([255, 255, 255], dimmer);
source = Array.from({ length: 7 }, () => white.slice());
}
if (stat && !dynamic) {
let [name, mask] = STATIC_MASKS[stat[0]];
if (name === 'one') {
const pixel = Math.min(6, Math.floor(stat[1] * 7));
mask = Array.from({ length: 7 }, (_, i) => (i === pixel ? 1 : 0));
}
source = source.map((p, i) => (mask[i] ? p : [0, 0, 0]));
fn = 'static';
label = name === 'one' ? 'one pixel' : `static ${name}`;
}
if (dynamic) {
dynamicName = DYNAMIC[dynamic[0]];
speed = r2(0.4 + dynamic[1] * 6, 2);
fn = 'dynamic';
label = DYNAMIC_LABELS[dynamicName];
}
const tinted = source.map((p) => applyCto(p[0], p[1], p[2], cto));
const [red, green, blue] = beamColour(tinted);
const [rate, strobeMode] = moverStrobe(strobe);
const reset = v('Reset');
const panSpeed = v('Pan/Tilt Speed');
const panDeg = ((pan - 32768) / 65536) * PAN_DEGREES;
const zoomDeg = ZOOM_MIN + (zoom / 255) * (ZOOM_MAX - ZOOM_MIN);
const tiltDeg = ((tilt - 32768) / 65536) * TILT_DEGREES;
// Reach along the pan heading on the plan. Negative points behind it.
const lean = clamp(-tiltDeg, -90, 90);
const beamM = BEAM_MAX_M * Math.sin((lean * Math.PI) / 180);
return {
r: red, g: green, b: blue,
dimmer,
strobe_hz: rate,
strobe_mode: strobeMode,
effect: fn !== 'pixels',
function: fn,
function_label: label,
speed_hz: speed,
dynamic: dynamicName,
pan_deg: r2(panDeg, 2),
tilt_deg: r2(tiltDeg, 2),
zoom_deg: r2(zoomDeg, 2),
beam_m: r2(beamM, 3),
pixels: tinted,
spin_dps: lensSpin(rotate),
lens_deg: lensAngle(rotate),
focus: r2(v('Focus') / 255, 3),
move: r2(1 - panSpeed / 255, 3),
cto,
reset: reset >= 200 && reset <= 205,
channels,
};
}
function decodeMover(channels) {
return decodeMoverNamed(channels, MOVER_43);
}
/** Read a fixture using the channel names of its DMX definition. */
function decodeNamed(channels, names, { kind } = {}) {
if (kind === 'mover' || (find(names, 'Pan') !== null && find(names, 'Tilt') !== null)) {
return decodeMoverNamed(channels, names);
}
return decodeCanNamed(channels, names);
}
/**
* The live view of a can or mover.
* fixture: {kind, universe, address (DMX 1–512), channel_names, pan_reverse}; universes: Map<number, Uint8Array(512)>
*/
function viewFixture(fixture, universes) {
if (!fixture.address || fixture.universe === undefined || fixture.universe === null) {
return { patched: false, r: 0, g: 0, b: 0, dimmer: 0, strobe_hz: 0, channels: [] };
}
const names = fixture.channel_names || [];
const count = names.length || (fixture.kind === 'mover' ? 43 : 8);
const frame = universes.get(fixture.universe);
const channels = slotsAt(frame, fixture.address - 1, count);
let view;
if (names.length) {
view = decodeNamed(channels, names, { kind: fixture.kind });
} else if (fixture.kind === 'mover') {
view = decodeMover(channels);
} else {
view = decodeCan(channels);
}
if (fixture.pan_reverse && 'pan_deg' in view) {
view.pan_deg = -view.pan_deg;
}
view.patched = true;
return view;
}
/**
* The RGB bytes of a pixel strip fed by Art-Net: the first universe from the address, then 170 pixels a
* universe from channel 1 (the way the controller's Art-Net output sends them). Same rule as dmx_runs() in sim_rig.c.
*/
function artnetPixels(universes, universe, address, leds) {
const out = new Uint8Array(leds * 3);
let px = 0;
let u = universe;
let a0 = address - 1;
while (px < leds) {
const frame = universes.get(u);
const fit = Math.floor((512 - a0) / 3);
const take = Math.min(fit, leds - px);
if (frame) {
out.set(frame.subarray(a0, a0 + take * 3), px * 3);
}
px += take;
u += 1;
a0 = 0;
if (u - universe > 32) {
break;
}
}
return out;
}
/** The DMX channels [universe, start0, end0) an Art-Net fixture uses (for the editor's next free address). */
function dmxRuns(fixture, room, leds) {
const u = fixture.universe ?? 0;
const a0 = (fixture.address ?? 1) - 1;
if ((fixture.kind ?? 'pixels') !== 'pixels') {
const d = (room.dmx_definitions || {})[fixture.dmx_def];
return [[u, a0, a0 + (d ? d.channels.length : 0)]];
}
const runs = [];
let left = leds;
let n = 0;
while (left > 0 && n < 32) {
const take = Math.min(n === 0 ? Math.floor((512 - a0) / 3) : 170, left);
const start = n === 0 ? a0 : 0;
runs.push([u + n, start, start + take * 3]);
left -= take;
n++;
}
return runs;
}
/** Channel names of a QLC+ fixture definition (.qxf) for each mode: [{manufacturer, model, mode, channels}] */
function parseQxf(text) {
const doc = new DOMParser().parseFromString(text, 'application/xml');
if (doc.querySelector('parsererror')) {
throw new Error('not an XML file');
}
const tag = (el, name) => [...el.children].filter((c) => c.localName === name);
const root = doc.documentElement;
const text1 = (name) => (tag(root, name)[0]?.textContent || '').trim();
const manufacturer = text1('Manufacturer');
const model = text1('Model');
const modes = tag(root, 'Mode');
if (!modes.length) {
throw new Error('no <Mode> in this fixture definition');
}
return modes.map((mode) => {
const chans = tag(mode, 'Channel')
.sort((a, b) => Number(a.getAttribute('Number')) - Number(b.getAttribute('Number')))
.map((c) => c.textContent.trim());
return { manufacturer, model, mode: mode.getAttribute('Name') || '', channels: chans };
});
}
g.RigDmx = {
PAN_DEGREES,
TILT_DEGREES,
BEAM_MAX_M,
ZOOM_MIN,
ZOOM_MAX,
CAN_STROBE_OPEN,
MOVER_STROBE_OPEN,
PAR_PALETTE,
MOVER_43,
PRESET_DEFINITIONS,
mixRgbw,
slotsAt,
strobeHz,
lensAngle,
lensSpin,
applyCto,
decodeCan,
decodeMover,
decodeNamed,
viewFixture,
artnetPixels,
dmxRuns,
parseQxf,
};
})(typeof self !== 'undefined' ? self : globalThis);
+69 -11
View File
@@ -27,9 +27,18 @@
<button type="button" id="zoom-in" class="secondary" aria-label="Zoom in" title="Zoom in (wheel)">+</button> <button type="button" id="zoom-in" class="secondary" aria-label="Zoom in" title="Zoom in (wheel)">+</button>
</span> </span>
<span id="edit-tools" class="edit-tools" hidden> <span id="edit-tools" class="edit-tools" hidden>
<button type="button" id="add-strip">Add strip</button> <span class="add-group" role="group" aria-label="Add a fixture">
<select id="add-type" aria-label="Fixture type" title="What a click on the floor adds">
<option value="espnow">ESP-NOW bar</option>
<option value="ddp">DDP strip</option>
<option value="artnet">Art-Net pixel strip</option>
<option value="can">DMX can</option>
<option value="mover">DMX mover</option>
</select>
<button type="button" id="add-strip">Add</button>
</span>
<button type="button" id="centre-strips" class="secondary" title="Move all the strips so they sit in the middle of the room">Centre strips</button> <button type="button" id="centre-strips" class="secondary" title="Move all the strips so they sit in the middle of the room">Centre strips</button>
<button type="button" id="room-settings" class="secondary">Size &amp; strip types…</button> <button type="button" id="room-settings" class="secondary">Size, strip types &amp; DMX…</button>
<button type="button" id="room-new" class="secondary">New room…</button> <button type="button" id="room-new" class="secondary">New room…</button>
<button type="button" id="room-delete" class="secondary">Delete room</button> <button type="button" id="room-delete" class="secondary">Delete room</button>
<span class="muted" id="save-state"></span> <span class="muted" id="save-state"></span>
@@ -45,7 +54,7 @@
<div id="banner" class="banner" hidden></div> <div id="banner" class="banner" hidden></div>
<div class="edit-hint" id="edit-hint"> <div class="edit-hint" id="edit-hint">
Add strip or click the floor to add one · drag the floor to select the strips in a box (Shift: add to the selection; zoomed in, a plain drag pans instead) ·Shift-click a strip to add or remove it · drag a selected strip to move them all (Alt: no snap) · drag its end circle to turn it (Shift: no snap) · Delete removes the selection · wheel or +/− zooms, right-drag, middle-drag or Space-drag pans Pick a type and press Add, or click the floor to add one · drag the floor to select the strips in a box (Shift: add to the selection; zoomed in, a plain drag pans instead) ·Shift-click a strip to add or remove it · drag a selected strip to move them all (Alt: no snap) · drag its end circle to turn it (Shift: no snap) · Delete removes the selection · wheel or +/− zooms, right-drag, middle-drag or Space-drag pans
</div> </div>
<main class="stage"> <main class="stage">
@@ -71,22 +80,41 @@
<dt>Position</dt><dd id="d-pos">–</dd> <dt>Position</dt><dd id="d-pos">–</dd>
<dt>Packets</dt><dd id="d-packets">–</dd> <dt>Packets</dt><dd id="d-packets">–</dd>
</dl> </dl>
<div class="net-actions" id="d-net" hidden>
<button type="button" id="d-mkout" class="secondary" title="Add a controller output (Outputs) that sends to this fixture">Create controller output</button>
<button type="button" id="d-testout" class="secondary" hidden>Send test</button>
<p class="note" id="d-out-note"></p>
</div>
<table class="channels" id="d-channels" hidden>
<thead><tr><th>Ch</th><th>Name</th><th>Value</th></tr></thead>
<tbody></tbody>
</table>
<p class="note" id="d-note" hidden></p> <p class="note" id="d-note" hidden></p>
<form class="edit-form" id="d-edit" hidden onsubmit="return false"> <form class="edit-form" id="d-edit" hidden onsubmit="return false">
<label>Label <input id="e-label" maxlength="47"></label> <label>Label <input id="e-label" maxlength="47"></label>
<label>Strip type <select id="e-def"></select></label> <label data-for="strip">Strip type <select id="e-def"></select></label>
<label>LEDs <input id="e-leds" type="number" min="1" max="512" step="1" title="Empty: the strip type's count"></label> <label data-for="strip">LEDs <input id="e-leds" type="number" min="1" max="512" step="1" title="Empty: the strip type's count"></label>
<label>Pixel 0 x (m) <input id="e-x" type="number" step="0.05"></label> <label data-for="ddp">DDP port <input id="e-port" type="number" min="1" max="65535" step="1"></label>
<label>Pixel 0 y (m) <input id="e-y" type="number" step="0.05"></label> <label data-for="ddp">First pixel <input id="e-offset" type="number" min="0" max="4095" step="1" title="Where this strip starts in what arrives on the port (pixels)"></label>
<label>Heading (°) <input id="e-dir" type="number" step="15" title="Degrees clockwise from up: 90 runs right, -90 runs left"></label> <label data-for="artnet">Universe <input id="e-universe" type="number" min="0" max="32767" step="1"></label>
<button type="button" id="d-delete" class="danger">Remove strip</button> <label data-for="artnet">DMX address <input id="e-address" type="number" min="1" max="512" step="1"></label>
<label data-for="pixels">Colour order <select id="e-order">
<option>rgb</option><option>rbg</option><option>grb</option><option>gbr</option><option>brg</option><option>bgr</option>
</select></label>
<label data-for="dmx">DMX definition <select id="e-dmxdef"></select></label>
<label data-for="mover">Pan zero (°) <input id="e-zero" type="number" step="15" title="Heading at pan centre, degrees clockwise from up"></label>
<label data-for="mover" class="check"><input type="checkbox" id="e-panrev"> Pan reversed</label>
<label><span><span id="e-x-name">Pixel 0 x</span> (m)</span> <input id="e-x" type="number" step="0.05"></label>
<label><span><span id="e-y-name">Pixel 0 y</span> (m)</span> <input id="e-y" type="number" step="0.05"></label>
<label data-for="heading">Heading (°) <input id="e-dir" type="number" step="15" title="Degrees clockwise from up: 90 runs right, -90 runs left"></label>
<button type="button" id="d-delete" class="danger">Remove</button>
</form> </form>
<div class="drawer-actions"> <div class="drawer-actions" id="d-power">
<button type="button" id="d-on">Power on</button> <button type="button" id="d-on">Power on</button>
<button type="button" id="d-reset">Reset</button> <button type="button" id="d-reset">Reset</button>
<button type="button" id="d-off" class="secondary">Power off</button> <button type="button" id="d-off" class="secondary">Power off</button>
</div> </div>
<div class="log-head"> <div class="log-head" id="d-log-head">
<span>Serial</span> <span>Serial</span>
<button type="button" class="link" id="d-clear">clear</button> <button type="button" class="link" id="d-clear">clear</button>
</div> </div>
@@ -113,6 +141,34 @@
</tr> </tr>
</tfoot> </tfoot>
</table> </table>
<h3>DMX definitions</h3>
<p class="muted small">The channel list of each can or mover, in DMX order, as in the qlcplus stage map. Names such as
Dimmer, Strobe, Red, Green, Blue, White, Macro, Speed, Pan, Tilt, Zoom, Focus or "Red 1" pick what each channel does.</p>
<table class="defs" id="r-dmx-table">
<thead><tr><th>Definition</th><th>Mode</th><th>Channels</th><th></th><th></th></tr></thead>
<tbody id="r-dmx"></tbody>
</table>
<div class="dialog-row dmx-add">
<select id="r-dmx-preset" aria-label="Preset">
<option value="">Add a preset…</option>
</select>
<button type="button" id="r-dmx-new" class="secondary">New definition</button>
<label class="button secondary file">Import QLC+ .qxf <input type="file" id="r-dmx-qxf" accept=".qxf,.xml" hidden></label>
<label class="button secondary file" title="A qlcplus stage/map.json: its definitions and fixtures are added to this room">Import stage map <input type="file" id="r-dmx-map" accept=".json" hidden></label>
</div>
<div class="dmx-edit" id="r-dmx-edit" hidden>
<div class="dialog-row">
<label>Name <input id="r-dmx-name" maxlength="60"></label>
<label>Mode <input id="r-dmx-mode" maxlength="60"></label>
</div>
<label>Channels, one per line <textarea id="r-dmx-chans" rows="10" spellcheck="false"></textarea></label>
<p class="error" id="r-dmx-error"></p>
<div class="dialog-actions">
<button type="button" id="r-dmx-cancel" class="secondary">Cancel</button>
<button type="button" id="r-dmx-save">Save definition</button>
</div>
</div>
<p class="error" id="r-error"></p>
<div class="dialog-actions"><button type="button" id="r-close">Done</button></div> <div class="dialog-actions"><button type="button" id="r-close">Done</button></div>
</dialog> </dialog>
@@ -134,6 +190,8 @@
</dialog> </dialog>
<script src="/sim/layout.js"></script> <script src="/sim/layout.js"></script>
<script src="/sim/dmx.js"></script>
<script src="/sim/dmx-draw.js"></script>
<script src="/sim/app.js"></script> <script src="/sim/app.js"></script>
</body> </body>
</html> </html>
+24 -4
View File
@@ -3,17 +3,33 @@
* A room (rooms/<name>.json, see rooms.py) spans x -width/2..width/2 and y 0..depth, metres, * A room (rooms/<name>.json, see rooms.py) spans x -width/2..width/2 and y 0..depth, metres,
* y up on screen. A fixture's x, y is pixel 0; the strip runs along `direction` (degrees clockwise * y up on screen. A fixture's x, y is pixel 0; the strip runs along `direction` (degrees clockwise
* from +y) for leds x pitch_m metres. roomStrips() mirrors rooms.room_strips() on the server. * from +y) for leds x pitch_m metres. roomStrips() mirrors rooms.room_strips() on the server.
* Art-Net cans and movers (type "artnet", kind "can" / "mover") are points with no LEDs of their own.
*/ */
(function (g) { (function (g) {
'use strict'; 'use strict';
/** DMX cans and movers are points: their x, y is the light, the turn handle sits HANDLE_M along the heading. */
const HANDLE_M = 0.45;
function isPoint(f) {
return f.type === 'artnet' && (f.kind === 'can' || f.kind === 'mover');
}
function fixtureLeds(room, f) { function fixtureLeds(room, f) {
if (isPoint(f)) {
return 0;
}
return Number(f.leds) || room.definitions[f.def].leds; return Number(f.leds) || room.definitions[f.def].leds;
} }
/** A mover's handle turns its zero (the heading at pan centre), a can's or a strip's its direction. */
function heading(f) {
return f.type === 'artnet' && f.kind === 'mover' ? Number(f.zero) || 0 : f.direction;
}
function fixtureEnd(room, f) { function fixtureEnd(room, f) {
const len = fixtureLeds(room, f) * room.definitions[f.def].pitch_m; const len = isPoint(f) ? HANDLE_M : fixtureLeds(room, f) * room.definitions[f.def].pitch_m;
const a = (f.direction * Math.PI) / 180; const a = (heading(f) * Math.PI) / 180;
return [f.x + len * Math.sin(a), f.y + len * Math.cos(a)]; return [f.x + len * Math.sin(a), f.y + len * Math.cos(a)];
} }
@@ -26,6 +42,9 @@
n: i + 1, n: i + 1,
id, id,
label: f.label, label: f.label,
type: f.type || 'espnow',
kind: f.type === 'artnet' ? f.kind || 'pixels' : 'pixels',
point: isPoint(f),
mac: f.mac, mac: f.mac,
leds: fixtureLeds(room, f), leds: fixtureLeds(room, f),
x: f.x, x: f.x,
@@ -33,6 +52,7 @@
x1, x1,
y1, y1,
direction: f.direction, direction: f.direction,
zero: Number(f.zero) || 0,
}; };
}); });
} }
@@ -68,7 +88,7 @@
const bx = view.sx(s.x1); const bx = view.sx(s.x1);
const by = view.sy(s.y1); const by = view.sy(s.y1);
const len = Math.hypot(bx - ax, by - ay); const len = Math.hypot(bx - ax, by - ay);
return { ax, ay, bx, by, len, ang: Math.atan2(by - ay, bx - ax), pitch: len / s.leds }; return { ax, ay, bx, by, len, ang: Math.atan2(by - ay, bx - ax), pitch: s.leds ? len / s.leds : 0, point: s.point };
}); });
} }
@@ -80,5 +100,5 @@
return Math.hypot(x - (sg.ax + t * dx), y - (sg.ay + t * dy)); return Math.hypot(x - (sg.ax + t * dx), y - (sg.ay + t * dy));
} }
g.RigLayout = { roomStrips, fit, stripGeometry, distToStrip, fixtureLeds }; g.RigLayout = { roomStrips, fit, stripGeometry, distToStrip, fixtureLeds, isPoint };
})(typeof self !== 'undefined' ? self : globalThis); })(typeof self !== 'undefined' ? self : globalThis);
+44
View File
@@ -249,3 +249,47 @@ table.defs input { width: 100%; }
/* In the controller's split view (an iframe beside it) */ /* In the controller's split view (an iframe beside it) */
body.embedded .not-embedded { display: none; } body.embedded .not-embedded { display: none; }
/* ---- network fixtures: DDP and Art-Net (sim_net.c), DMX cans and movers (dmx.js, dmx-draw.js) ---- */
.add-group { display: inline-flex; align-items: center; gap: 4px; }
.edit-form label[hidden], .log[hidden], .log-head[hidden], .drawer-actions[hidden] { display: none; }
.edit-form label.check { flex-direction: row; align-items: center; gap: 6px; align-self: end; }
.net-actions { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.net-actions[hidden] { display: none; }
.net-actions .note { flex-basis: 100%; color: var(--muted); }
table.channels { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
table.channels[hidden] { display: none; }
table.channels th { text-align: left; color: var(--muted); font-weight: normal; padding: 2px 4px; border-bottom: 1px solid var(--line); }
table.channels td { padding: 2px 4px; }
table.channels td.num { text-align: right; width: 4em; }
table.channels tr.on td { color: var(--text); }
table.channels tr:not(.on) td:not(.muted) { color: var(--muted); }
dialog h3 { margin: 6px 0 0; font-size: 13px; }
dialog .small, .small { font-size: 12px; margin: 0; }
.dmx-add { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
label.button.file {
display: inline-block;
flex-direction: row;
cursor: pointer;
color: var(--text);
border: 1px solid var(--line);
background: var(--panel-2);
border-radius: 6px;
padding: 5px 11px;
}
label.button.file:hover { background: #232730; }
.dmx-edit { display: flex; flex-direction: column; gap: 8px; padding: 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel-2); }
.dmx-edit[hidden] { display: none; }
.dmx-edit textarea {
font: 12px ui-monospace, Menlo, Consolas, monospace;
color: var(--text);
background: var(--panel);
border: 1px solid var(--line);
border-radius: 6px;
padding: 6px;
resize: vertical;
}
dialog { max-height: calc(100vh - 32px); overflow: auto; }
.edit-form { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }
.edit-form input:not([type=checkbox]), .edit-form select { width: 100%; box-sizing: border-box; }
.drawer { overflow-x: hidden; }
+1 -1
View File
@@ -1,4 +1,4 @@
idf_component_register(SRCS "sim_main.c" "sim_stubs.c" "sim_timer.c" "sim_rig.c" idf_component_register(SRCS "sim_main.c" "sim_stubs.c" "sim_timer.c" "sim_rig.c" "sim_net.c"
INCLUDE_DIRS "include" "." INCLUDE_DIRS "include" "."
REQUIRES esp_http_server esp_timer esp_event cjson main freertos) REQUIRES esp_http_server esp_timer esp_event cjson main freertos)
target_link_libraries(${COMPONENT_LIB} INTERFACE m) target_link_libraries(${COMPONENT_LIB} INTERFACE m)
+443
View File
@@ -0,0 +1,443 @@
/*
* Art-Net and DDP received for the simulated rig's network fixtures: see sim_net.h.
* The Art-Net side follows the qlcplus stage simulator (technicalkiwi/qlcplus simulator/artnet.py).
*/
#include "sim_net.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "lwip/sockets.h"
static const char *TAG = "sim_net";
#define ARTNET_PORT 6454
#define OP_POLL 0x2000
#define OP_POLL_REPLY 0x2100
#define OP_DMX 0x5000
#define MAX_UNIVERSES 64
#define TICK_MS 25 // 40 frames a second to the page
typedef struct {
int uni; // -1: unused
uint8_t data[512];
bool dirty;
uint32_t packets;
} universe_t;
typedef struct {
uint16_t port; // 0: unused
int fd;
char error[64];
uint8_t rgb[SIM_NET_DDP_PIXELS * 3];
size_t len; // bytes written so far (the highest offset + length)
bool dirty;
uint32_t packets;
char last_from[16];
} ddp_t;
static SemaphoreHandle_t s_mu;
static universe_t s_uni[MAX_UNIVERSES];
static ddp_t s_ddp[SIM_NET_MAX_DDP_PORTS];
static uint16_t s_want[SIM_NET_MAX_DDP_PORTS]; // the ports the room asks for
static int s_nwant;
static bool s_want_changed;
static int s_art_fd = -1, s_art_port = ARTNET_PORT;
static char s_art_error[64], s_art_from[16];
static uint32_t s_art_packets, s_art_polls;
static int udp_bind(uint16_t port, char *err, size_t errn)
{
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
snprintf(err, errn, "socket: errno %d", errno);
return -1;
}
int one = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
#ifdef SO_REUSEPORT
setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
#endif
setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one));
struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(port), .sin_addr.s_addr = htonl(INADDR_ANY) };
if (bind(fd, (struct sockaddr *)&a, sizeof(a)) != 0) {
snprintf(err, errn, "bind %u: errno %d", port, errno);
close(fd);
return -1;
}
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
err[0] = 0;
return fd;
}
static universe_t *universe_slot(int uni)
{
universe_t *free_slot = NULL;
for (int i = 0; i < MAX_UNIVERSES; i++) {
if (s_uni[i].uni == uni) {
return &s_uni[i];
}
if (s_uni[i].uni < 0 && !free_slot) {
free_slot = &s_uni[i];
}
}
if (free_slot) {
free_slot->uni = uni;
memset(free_slot->data, 0, sizeof(free_slot->data));
}
return free_slot;
}
// The address this machine uses toward the peer (the IP an ArtPollReply names)
static void local_ip_toward(const struct sockaddr_in *peer, uint8_t ip[4])
{
static const uint8_t LOOP[4] = { 127, 0, 0, 1 };
memcpy(ip, LOOP, 4);
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
return;
}
struct sockaddr_in to = *peer, me;
socklen_t n = sizeof(me);
if (connect(fd, (struct sockaddr *)&to, sizeof(to)) == 0 && getsockname(fd, (struct sockaddr *)&me, &n) == 0) {
memcpy(ip, &me.sin_addr.s_addr, 4);
}
close(fd);
}
static void poll_reply(const struct sockaddr_in *from)
{
uint8_t pkt[239] = { 0 };
memcpy(pkt, "Art-Net\0", 8);
pkt[8] = OP_POLL_REPLY & 0xFF;
pkt[9] = OP_POLL_REPLY >> 8;
pkt[11] = 14;
local_ip_toward(from, pkt + 12);
pkt[16] = ARTNET_PORT & 0xFF;
pkt[17] = ARTNET_PORT >> 8;
pkt[19] = 1;
pkt[25] = 0xD0;
memcpy(pkt + 26, "led-sim", 7); // short name (17 bytes from 26)
memcpy(pkt + 44, "LED controller simulated rig", 28); // long name (63 bytes from 44)
pkt[173] = 1; // NumPorts
pkt[174] = 0x80; // port 0 outputs DMX
pkt[182] = 0x80; // GoodOutput: data is being output
sendto(s_art_fd, pkt, sizeof(pkt), 0, (const struct sockaddr *)from, sizeof(*from));
}
static void artnet_rx(const uint8_t *p, int n, const struct sockaddr_in *from)
{
if (n < 10 || memcmp(p, "Art-Net\0", 8) != 0) {
return;
}
int op = p[8] | (p[9] << 8);
if (op == OP_POLL) {
s_art_polls++;
poll_reply(from);
return;
}
if (op != OP_DMX || n < 18) {
return;
}
int uni = p[14] | ((p[15] & 0x7F) << 8);
int len = (p[16] << 8) | p[17];
if (len < 2 || len > 512 || 18 + len > n) {
return;
}
xSemaphoreTake(s_mu, portMAX_DELAY);
universe_t *u = universe_slot(uni);
if (u) {
memcpy(u->data, p + 18, (size_t)len);
u->dirty = true;
u->packets++;
}
s_art_packets++;
inet_ntop(AF_INET, &from->sin_addr, s_art_from, sizeof(s_art_from));
xSemaphoreGive(s_mu);
}
static void ddp_rx(ddp_t *d, const uint8_t *p, int n, const struct sockaddr_in *from)
{
if (n < 10 || (p[0] & 0xC0) != 0x40) {
return;
}
int hdr = (p[0] & 0x10) ? 14 : 10; // the timecode flag adds 4 bytes
uint32_t off = ((uint32_t)p[4] << 24) | ((uint32_t)p[5] << 16) | ((uint32_t)p[6] << 8) | p[7];
uint32_t len = ((uint32_t)p[8] << 8) | p[9];
if (n < hdr || len > (uint32_t)(n - hdr) || off >= sizeof(d->rgb)) {
return;
}
if (off + len > sizeof(d->rgb)) {
len = sizeof(d->rgb) - off;
}
xSemaphoreTake(s_mu, portMAX_DELAY);
memcpy(d->rgb + off, p + hdr, len);
if (off + len > d->len) {
d->len = off + len;
}
d->dirty = true;
d->packets++;
inet_ntop(AF_INET, &from->sin_addr, d->last_from, sizeof(d->last_from));
xSemaphoreGive(s_mu);
}
// Bring the DDP sockets in line with the ports the room asks for
static void sync_ddp(void)
{
xSemaphoreTake(s_mu, portMAX_DELAY);
if (!s_want_changed) {
xSemaphoreGive(s_mu);
return;
}
s_want_changed = false;
uint16_t want[SIM_NET_MAX_DDP_PORTS];
int nwant = s_nwant;
memcpy(want, s_want, sizeof(want));
for (int i = 0; i < SIM_NET_MAX_DDP_PORTS; i++) { // close the ports no longer wanted
bool keep = false;
for (int k = 0; k < nwant; k++) {
keep |= s_ddp[i].port && s_ddp[i].port == want[k];
}
if (s_ddp[i].port && !keep) {
if (s_ddp[i].fd >= 0) {
close(s_ddp[i].fd);
}
ESP_LOGI(TAG, "DDP: stopped listening on %u", s_ddp[i].port);
memset(&s_ddp[i], 0, sizeof(s_ddp[i]));
s_ddp[i].fd = -1;
}
}
for (int k = 0; k < nwant; k++) { // open the new ones
bool have = false;
for (int i = 0; i < SIM_NET_MAX_DDP_PORTS; i++) {
have |= s_ddp[i].port == want[k];
}
for (int i = 0; !have && i < SIM_NET_MAX_DDP_PORTS; i++) {
if (!s_ddp[i].port) {
s_ddp[i].port = want[k];
s_ddp[i].fd = udp_bind(want[k], s_ddp[i].error, sizeof(s_ddp[i].error));
if (s_ddp[i].fd >= 0) {
ESP_LOGI(TAG, "DDP: listening on UDP %u", want[k]);
} else {
ESP_LOGW(TAG, "DDP: %s", s_ddp[i].error);
}
have = true;
}
}
}
xSemaphoreGive(s_mu);
}
// Send what changed since the last tick to the page
static void flush(void)
{
static uint8_t frame[1 + 6 + SIM_NET_DDP_PIXELS * 3];
for (int i = 0; i < MAX_UNIVERSES; i++) {
xSemaphoreTake(s_mu, portMAX_DELAY);
bool send = s_uni[i].uni >= 0 && s_uni[i].dirty;
if (send) {
frame[0] = 1;
frame[1] = s_uni[i].uni & 0xFF;
frame[2] = s_uni[i].uni >> 8;
memcpy(frame + 3, s_uni[i].data, 512);
s_uni[i].dirty = false;
}
xSemaphoreGive(s_mu);
if (send) {
sim_rig_page_send(frame, 3 + 512);
}
}
for (int i = 0; i < SIM_NET_MAX_DDP_PORTS; i++) {
xSemaphoreTake(s_mu, portMAX_DELAY);
size_t len = s_ddp[i].len;
bool send = s_ddp[i].port && s_ddp[i].dirty;
if (send) {
frame[0] = 2;
frame[1] = s_ddp[i].port & 0xFF;
frame[2] = s_ddp[i].port >> 8;
memset(frame + 3, 0, 4); // offset 0: the whole buffer
memcpy(frame + 7, s_ddp[i].rgb, len);
s_ddp[i].dirty = false;
}
xSemaphoreGive(s_mu);
if (send) {
sim_rig_page_send(frame, 7 + len);
}
}
}
static void net_task(void *arg)
{
(void)arg;
static uint8_t buf[1500];
TickType_t last = xTaskGetTickCount();
for (;;) {
sync_ddp();
fd_set rd;
FD_ZERO(&rd);
int top = -1;
if (s_art_fd >= 0) {
FD_SET(s_art_fd, &rd);
top = s_art_fd;
}
for (int i = 0; i < SIM_NET_MAX_DDP_PORTS; i++) {
if (s_ddp[i].fd >= 0 && s_ddp[i].port) {
FD_SET(s_ddp[i].fd, &rd);
top = s_ddp[i].fd > top ? s_ddp[i].fd : top;
}
}
struct timeval tv = { .tv_sec = 0, .tv_usec = 5000 };
int ready = top >= 0 ? select(top + 1, &rd, NULL, NULL, &tv) : 0;
if (top < 0) {
vTaskDelay(pdMS_TO_TICKS(TICK_MS));
}
if (ready > 0) {
struct sockaddr_in from;
socklen_t fl;
int n;
if (s_art_fd >= 0 && FD_ISSET(s_art_fd, &rd)) {
while (fl = sizeof(from), (n = recvfrom(s_art_fd, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fl)) > 0) {
artnet_rx(buf, n, &from);
}
}
for (int i = 0; i < SIM_NET_MAX_DDP_PORTS; i++) {
if (s_ddp[i].fd >= 0 && s_ddp[i].port && FD_ISSET(s_ddp[i].fd, &rd)) {
while (fl = sizeof(from),
(n = recvfrom(s_ddp[i].fd, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fl)) > 0) {
ddp_rx(&s_ddp[i], buf, n, &from);
}
}
}
} else {
vTaskDelay(1); // let the other tasks in (select blocks the host thread, not the scheduler)
}
TickType_t now = xTaskGetTickCount();
if (now - last >= pdMS_TO_TICKS(TICK_MS)) {
last = now;
flush();
}
}
}
void sim_net_start(void)
{
if (s_mu) {
return;
}
s_mu = xSemaphoreCreateMutex();
for (int i = 0; i < MAX_UNIVERSES; i++) {
s_uni[i].uni = -1;
}
for (int i = 0; i < SIM_NET_MAX_DDP_PORTS; i++) {
s_ddp[i].fd = -1;
}
const char *env = getenv("LED_SIM_ARTNET_PORT");
if (env && env[0]) {
s_art_port = atoi(env);
}
if (s_art_port > 0 && s_art_port < 65536) {
s_art_fd = udp_bind((uint16_t)s_art_port, s_art_error, sizeof(s_art_error));
if (s_art_fd >= 0) {
ESP_LOGI(TAG, "Art-Net: listening on UDP %d", s_art_port);
} else {
ESP_LOGW(TAG, "Art-Net: %s (set LED_SIM_ARTNET_PORT to use another port)", s_art_error);
}
} else {
snprintf(s_art_error, sizeof(s_art_error), "off (LED_SIM_ARTNET_PORT=0)");
}
if (xTaskCreate(net_task, "sim_net", 8192, NULL, 4, NULL) != pdPASS) {
ESP_LOGE(TAG, "no task: Art-Net and DDP fixtures stay dark");
}
}
void sim_net_set_ddp_ports(const uint16_t *ports, int n)
{
if (!s_mu) {
return;
}
xSemaphoreTake(s_mu, portMAX_DELAY);
int k = 0;
for (int i = 0; i < n && k < SIM_NET_MAX_DDP_PORTS; i++) {
bool dup = !ports[i];
for (int j = 0; j < k; j++) {
dup |= s_want[j] == ports[i];
}
if (!dup) {
s_want[k++] = ports[i];
}
}
s_nwant = k;
s_want_changed = true; // sync_ddp only opens and closes the ports that differ
xSemaphoreGive(s_mu);
}
static void add_hex(cJSON *o, const char *key, const uint8_t *p, size_t n)
{
char *h = malloc(n * 2 + 1);
if (!h) {
return;
}
for (size_t i = 0; i < n; i++) {
snprintf(h + i * 2, 3, "%02x", p[i]);
}
h[n * 2] = 0;
cJSON_AddStringToObject(o, key, h);
free(h);
}
cJSON *sim_net_status(bool with_data)
{
cJSON *o = cJSON_CreateObject();
if (!s_mu) {
return o;
}
xSemaphoreTake(s_mu, portMAX_DELAY);
cJSON *a = cJSON_AddObjectToObject(o, "artnet");
cJSON_AddNumberToObject(a, "port", s_art_port);
cJSON_AddBoolToObject(a, "listening", s_art_fd >= 0);
if (s_art_error[0]) {
cJSON_AddStringToObject(a, "error", s_art_error);
}
cJSON_AddNumberToObject(a, "packets", s_art_packets);
cJSON_AddNumberToObject(a, "polls", s_art_polls);
cJSON_AddStringToObject(a, "last_from", s_art_from);
cJSON *us = cJSON_AddObjectToObject(a, "universes");
for (int i = 0; i < MAX_UNIVERSES; i++) {
if (s_uni[i].uni < 0) {
continue;
}
char k[12];
snprintf(k, sizeof(k), "%d", s_uni[i].uni);
cJSON *u = cJSON_AddObjectToObject(us, k);
cJSON_AddNumberToObject(u, "packets", s_uni[i].packets);
if (with_data) {
add_hex(u, "data", s_uni[i].data, 512);
}
}
cJSON *d = cJSON_AddObjectToObject(o, "ddp");
for (int i = 0; i < SIM_NET_MAX_DDP_PORTS; i++) {
if (!s_ddp[i].port) {
continue;
}
char k[12];
snprintf(k, sizeof(k), "%u", s_ddp[i].port);
cJSON *p = cJSON_AddObjectToObject(d, k);
cJSON_AddBoolToObject(p, "listening", s_ddp[i].fd >= 0);
if (s_ddp[i].error[0]) {
cJSON_AddStringToObject(p, "error", s_ddp[i].error);
}
cJSON_AddNumberToObject(p, "packets", s_ddp[i].packets);
cJSON_AddNumberToObject(p, "pixels", (double)(s_ddp[i].len / 3));
cJSON_AddStringToObject(p, "last_from", s_ddp[i].last_from);
if (with_data) {
add_hex(p, "data", s_ddp[i].rgb, s_ddp[i].len);
}
}
xSemaphoreGive(s_mu);
return o;
}
+32
View File
@@ -0,0 +1,32 @@
/*
* The simulated rig's network fixtures: Art-Net (UDP 6454) and DDP (UDP 4048, or the ports the room's DDP
* fixtures name) received here and forwarded to the rig page over /sim/ws, at most 40 frames a second:
*
* here -> page binary 0x01 + u16 universe (LE) + 512 bytes an Art-Net universe changed
* here -> page binary 0x02 + u16 port (LE) + u32 0 + RGB bytes a DDP port's pixels changed (from offset 0)
*
* The ESP-NOW frames to the page carry 0x00 in front (sim_rig.c). ArtPoll is answered so QLC+ lists the node.
* LED_SIM_ARTNET_PORT moves the Art-Net port (0: off), for when QLC+ on the same machine holds 6454.
*/
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "cJSON.h"
#define SIM_NET_MAX_DDP_PORTS 8
#define SIM_NET_DDP_PIXELS 4096
// Start the receiver task (once)
void sim_net_start(void);
// The DDP ports the active room uses (duplicates and 0 are ignored); sockets follow on the next tick
void sim_net_set_ddp_ports(const uint16_t *ports, int n);
// {artnet: {port, error, packets, polls, last_from, universes: {"0": {packets, data?: hex}}},
// ddp: {"4048": {packets, pixels, error, last_from, data?: hex}}}; data only when with_data
cJSON *sim_net_status(bool with_data);
// sim_rig.c: send one binary frame to the page; false when no page is open
bool sim_rig_page_send(const uint8_t *frame, size_t len);
+321 -57
View File
@@ -6,7 +6,8 @@
* without threads, so the page needs no cross-origin isolation: any address works * without threads, so the page needs no cross-origin isolation: any address works
* WS /sim/ws the page's radio. One page at a time: a new one takes over. * WS /sim/ws the page's radio. One page at a time: a new one takes over.
* page -> here binary src_mac(6) + ESP-NOW packet a driver transmitted (bridge_browser_rx) * page -> here binary src_mac(6) + ESP-NOW packet a driver transmitted (bridge_browser_rx)
* here -> page binary dst_mac(6) + ESP-NOW packet the controller transmitted (sim_rig_tx) * here -> page binary 0x00 + dst_mac(6) + ESP-NOW packet the controller transmitted (sim_rig_tx)
* here -> page binary 0x01 / 0x02 + ... an Art-Net universe or DDP port's pixels (sim_net.h)
* page -> here text {"t":"flash","mac":"..","data":"<NVS JSON>"} a driver committed its flash * page -> here text {"t":"flash","mac":"..","data":"<NVS JSON>"} a driver committed its flash
* here -> page text {"t":"takeover"} another page opened the rig * here -> page text {"t":"takeover"} another page opened the rig
* GET /sim/api/config the active room, its strips, the room list and the bridge * GET /sim/api/config the active room, its strips, the room list and the bridge
@@ -16,11 +17,17 @@
* GET|PUT|DELETE /sim/api/rooms/<name> * GET|PUT|DELETE /sim/api/rooms/<name>
* POST /sim/api/room {name}: switch the rig to that room * POST /sim/api/room {name}: switch the rig to that room
* POST /sim/api/next-mac {taken: [mac, ...]}: a MAC no room or the page uses * POST /sim/api/next-mac {taken: [mac, ...]}: a MAC no room or the page uses
* GET /sim/api/dmx[?data=1] what the Art-Net and DDP receiver has had (sim_net.h); data=1 adds the bytes
* *
* Rooms follow the stage maps of the qlcplus simulator: one JSON file per room in <db>/sim/rooms/, a size in * Rooms follow the stage maps of the qlcplus simulator: one JSON file per room in <db>/sim/rooms/, a size in
* metres, strip types ("definitions") and "fixtures" keyed by id, each one LED bar: x, y (metres) is pixel 0, * metres, strip types ("definitions") and "fixtures" keyed by id, each one LED bar: x, y (metres) is pixel 0,
* "direction" the way it runs (degrees clockwise from +y), "mac" the driver. Each bar's flash is * "direction" the way it runs (degrees clockwise from +y), "mac" the driver. Each bar's flash is
* <db>/sim/flash/<mac>.json, so a bar keeps its presets in every room it appears in. * <db>/sim/flash/<mac>.json, so a bar keeps its presets in every room it appears in.
*
* A fixture's "type" is "espnow" (the default: a bar with a driver), "ddp" (a strip fed by DDP: port, offset
* in pixels, color_order) or "artnet" (universe, DMX address 1-512, and kind "pixels" with color_order, or
* "can"/"mover" with dmx_def naming one of the room's "dmx_definitions": {manufacturer, model, mode, channels},
* plus zero and pan_reverse for movers). Art-Net fixtures may not share DMX channels.
*/ */
#include "auth.h" #include "auth.h"
#include "sim_rig.h" #include "sim_rig.h"
@@ -39,12 +46,15 @@
#include "esp_log.h" #include "esp_log.h"
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/semphr.h" #include "freertos/semphr.h"
#include "sim_net.h"
#include "store.h" #include "store.h"
static const char *TAG = "sim_rig"; static const char *TAG = "sim_rig";
#define MAX_FIXTURES 64 #define MAX_FIXTURES 64
#define MAX_LEDS 512 // FX_LEDS_MAX in led-driver/main/effects.h #define MAX_LEDS 512 // FX_LEDS_MAX in led-driver/main/effects.h
#define MAX_NET_LEDS SIM_NET_DDP_PIXELS // DDP and Art-Net strips: no driver, only the buffer
#define MAX_DMX_DEFS 32
#define FLASH_MAX (512 * 1024) #define FLASH_MAX (512 * 1024)
#define FRAME_MAX (FLASH_MAX + 1024) #define FRAME_MAX (FLASH_MAX + 1024)
#define DEFAULT_PITCH_M (1.0 / 60) // 60 LEDs per metre #define DEFAULT_PITCH_M (1.0 / 60) // 60 LEDs per metre
@@ -299,6 +309,249 @@ static double num_in(const cJSON *o, const char *key, double def, double lo, dou
return v->valuedouble; return v->valuedouble;
} }
static const char *const COLOR_ORDERS[] = { "rgb", "rbg", "grb", "gbr", "brg", "bgr" };
static bool color_order_ok(const char *s)
{
for (size_t i = 0; i < sizeof(COLOR_ORDERS) / sizeof(COLOR_ORDERS[0]); i++) {
if (s && !strcmp(s, COLOR_ORDERS[i])) {
return true;
}
}
return false;
}
// A DMX definition or channel name: 1-max printable characters
static bool text_ok(const char *s, size_t max)
{
size_t n = s ? strlen(s) : 0;
if (n == 0 || n > max) {
return false;
}
for (size_t i = 0; i < n; i++) {
if ((unsigned char)s[i] < 0x20 || s[i] == 0x7f) {
return false;
}
}
return true;
}
static const char *str_or(const cJSON *o, const char *key, const char *def)
{
const cJSON *v = cJSON_GetObjectItem(o, key);
return cJSON_IsString(v) ? v->valuestring : def;
}
// dmx_definitions: {name: {manufacturer, model, mode, channels: [name, ...]}}, the qlcplus stage map's definitions
static void validate_dmx_defs(const cJSON *in, cJSON *out, char *err, size_t errn)
{
if (!cJSON_IsObject(in)) {
snprintf(err, errn, "dmx_definitions must be an object keyed by name");
return;
}
if (cJSON_GetArraySize(in) > MAX_DMX_DEFS) {
snprintf(err, errn, "at most %d DMX definitions in a room", MAX_DMX_DEFS);
return;
}
const cJSON *d;
cJSON_ArrayForEach(d, in)
{
if (!text_ok(d->string, 60) || !cJSON_IsObject(d)) {
snprintf(err, errn, "DMX definition names are 1-60 characters, each an object");
return;
}
const cJSON *ch = cJSON_GetObjectItem(d, "channels"), *c;
int n = cJSON_GetArraySize(ch);
if (!cJSON_IsArray(ch) || n < 1 || n > 512) {
snprintf(err, errn, "DMX definition %s: channels is a list of 1-512 names", d->string);
return;
}
cJSON *o = cJSON_AddObjectToObject(out, d->string);
const char *fields[] = { "manufacturer", "model", "mode" };
for (int i = 0; i < 3; i++) {
const char *v = str_or(d, fields[i], "");
cJSON_AddStringToObject(o, fields[i], text_ok(v, 60) ? v : "");
}
cJSON *chans = cJSON_AddArrayToObject(o, "channels");
cJSON_ArrayForEach(c, ch)
{
if (!cJSON_IsString(c) || !text_ok(c->valuestring, 40)) {
snprintf(err, errn, "DMX definition %s: channel names are 1-40 characters", d->string);
return;
}
cJSON_AddItemToArray(chans, cJSON_CreateString(c->valuestring));
}
}
}
// One fixture into fixtures (canonical form); err set when it is not valid
static void validate_fixture(const cJSON *f, const cJSON *defs, const cJSON *dmx_defs, cJSON *fixtures, char *err,
size_t errn)
{
const char *fid = f->string;
if (!id_ok(fid) || !cJSON_IsObject(f)) {
snprintf(err, errn, "fixture ids are 1-40 letters, digits or -_.#, each an object");
return;
}
const char *type = str_or(f, "type", "espnow");
const char *kind = str_or(f, "kind", "pixels");
bool espnow = !strcmp(type, "espnow"), ddp = !strcmp(type, "ddp"), artnet = !strcmp(type, "artnet");
if (!espnow && !ddp && !artnet) {
snprintf(err, errn, "fixture %s: type is espnow, ddp or artnet", fid);
return;
}
bool pixels = !artnet || !strcmp(kind, "pixels");
if (artnet && !pixels && strcmp(kind, "can") && strcmp(kind, "mover")) {
snprintf(err, errn, "fixture %s: kind is pixels, can or mover", fid);
return;
}
const cJSON *def = cJSON_GetObjectItem(f, "def");
if (pixels && (!cJSON_IsString(def) || !cJSON_GetObjectItem(defs, def->valuestring))) {
snprintf(err, errn, "fixture %s: unknown strip type", fid);
return;
}
char m[18] = "";
if (espnow) {
const cJSON *mac = cJSON_GetObjectItem(f, "mac");
if (!cJSON_IsString(mac) || !mac_ok(mac->valuestring)) {
snprintf(err, errn, "strip %s: mac must be like 02:51:4d:00:00:01", fid);
return;
}
snprintf(m, sizeof(m), "%s", mac->valuestring);
for (char *c = m; *c; c++) {
*c = (char)tolower((unsigned char)*c);
}
const cJSON *other;
cJSON_ArrayForEach(other, fixtures)
{
const cJSON *om = cJSON_GetObjectItem(other, "mac");
if (cJSON_IsString(om) && !strcmp(om->valuestring, m)) {
snprintf(err, errn, "strip %s: mac %s is used twice in this room", fid, m);
return;
}
}
}
const char *dmx_def = str_or(f, "dmx_def", "");
if (artnet && !pixels && !cJSON_GetObjectItem(dmx_defs, dmx_def)) {
snprintf(err, errn, "fixture %s: dmx_def must name one of the room's DMX definitions", fid);
return;
}
char what[80];
cJSON *o = cJSON_AddObjectToObject(fixtures, fid);
const char *label = str_or(f, "label", "");
char lab[48];
snprintf(lab, sizeof(lab), "%s", label[0] ? label : fid);
cJSON_AddStringToObject(o, "label", lab);
cJSON_AddStringToObject(o, "type", type);
if (pixels) {
cJSON_AddStringToObject(o, "def", def->valuestring);
}
if (espnow) {
cJSON_AddStringToObject(o, "mac", m);
}
snprintf(what, sizeof(what), "%s x", fid);
cJSON_AddNumberToObject(o, "x", round_to(num_in(f, "x", 0, -1000, 1000, what, err, errn), 0.001));
snprintf(what, sizeof(what), "%s y", fid);
cJSON_AddNumberToObject(o, "y", round_to(num_in(f, "y", 0, -1000, 1000, what, err, errn), 0.001));
snprintf(what, sizeof(what), "%s direction", fid);
cJSON_AddNumberToObject(o, "direction",
round_to(wrap_deg(num_in(f, "direction", 90, -3600, 3600, what, err, errn)), 0.1));
const cJSON *leds = cJSON_GetObjectItem(f, "leds");
if (pixels && leds && !cJSON_IsNull(leds)) {
snprintf(what, sizeof(what), "%s leds", fid);
cJSON_AddNumberToObject(o, "leds", (int)num_in(f, "leds", 1, 1, espnow ? MAX_LEDS : MAX_NET_LEDS, what, err, errn));
}
if (!espnow && pixels) {
const char *order = str_or(f, "color_order", "rgb");
if (!color_order_ok(order)) {
snprintf(err, errn, "fixture %s: color_order is one of rgb, rbg, grb, gbr, brg, bgr", fid);
return;
}
cJSON_AddStringToObject(o, "color_order", order);
}
if (ddp) {
snprintf(what, sizeof(what), "%s port", fid);
cJSON_AddNumberToObject(o, "port", (int)num_in(f, "port", 4048, 1, 65535, what, err, errn));
snprintf(what, sizeof(what), "%s offset", fid);
int off = (int)num_in(f, "offset", 0, 0, SIM_NET_DDP_PIXELS - 1, what, err, errn);
cJSON_AddNumberToObject(o, "offset", off);
}
if (artnet) {
cJSON_AddStringToObject(o, "kind", kind);
snprintf(what, sizeof(what), "%s universe", fid);
cJSON_AddNumberToObject(o, "universe", (int)num_in(f, "universe", 0, 0, 32767, what, err, errn));
snprintf(what, sizeof(what), "%s address", fid);
cJSON_AddNumberToObject(o, "address", (int)num_in(f, "address", 1, 1, 512, what, err, errn));
if (!pixels) {
cJSON_AddStringToObject(o, "dmx_def", dmx_def);
snprintf(what, sizeof(what), "%s zero", fid);
cJSON_AddNumberToObject(o, "zero", round_to(wrap_deg(num_in(f, "zero", 0, -3600, 3600, what, err, errn)), 0.1));
cJSON_AddBoolToObject(o, "pan_reverse", cJSON_IsTrue(cJSON_GetObjectItem(f, "pan_reverse")));
}
}
}
static int fixture_leds(const cJSON *room, const cJSON *f);
// The DMX slots an Art-Net fixture uses: up to 32 runs of [start, end) in a universe. Pixels fill the first
// universe from the address, then 170 a universe from channel 1, the way an Art-Net output sends them.
static int dmx_runs(const cJSON *room, const cJSON *f, int uni[32], int start[32], int end[32])
{
int u = cJSON_GetObjectItem(f, "universe")->valueint, a0 = cJSON_GetObjectItem(f, "address")->valueint - 1;
if (strcmp(str_or(f, "kind", "pixels"), "pixels")) {
const cJSON *d = cJSON_GetObjectItem(cJSON_GetObjectItem(room, "dmx_definitions"), str_or(f, "dmx_def", ""));
uni[0] = u;
start[0] = a0;
end[0] = a0 + cJSON_GetArraySize(cJSON_GetObjectItem(d, "channels"));
return 1;
}
int left = fixture_leds(room, f), n = 0;
int first = (512 - a0) / 3;
while (left > 0 && n < 32) {
int take = n == 0 ? first : 170;
take = take < left ? take : left;
uni[n] = u + n;
start[n] = n == 0 ? a0 : 0;
end[n] = start[n] + take * 3;
left -= take;
n++;
}
return n;
}
// Art-Net fixtures must fit in their universes and not share slots
static void dmx_overlaps(const cJSON *room, char *err, size_t errn)
{
const cJSON *fixtures = cJSON_GetObjectItem(room, "fixtures"), *a, *b;
cJSON_ArrayForEach(a, fixtures)
{
if (strcmp(str_or(a, "type", ""), "artnet")) {
continue;
}
int ua[32], sa[32], ea[32], na = dmx_runs(room, a, ua, sa, ea);
if (ea[0] > 512) {
snprintf(err, errn, "fixture %s: its %d channels from %d run past channel 512", a->string, ea[0] - sa[0],
sa[0] + 1);
return;
}
for (b = a->next; b; b = b->next) {
if (strcmp(str_or(b, "type", ""), "artnet")) {
continue;
}
int ub[32], sb[32], eb[32], nb = dmx_runs(room, b, ub, sb, eb);
for (int i = 0; i < na; i++) {
for (int k = 0; k < nb; k++) {
if (ua[i] == ub[k] && sa[i] < eb[k] && sb[k] < ea[i]) {
snprintf(err, errn, "fixtures %s and %s share DMX channels in universe %d", a->string,
b->string, ua[i]);
return;
}
}
}
}
}
}
// The room in canonical form (a new object), or NULL with the reason in err // The room in canonical form (a new object), or NULL with the reason in err
static cJSON *validate_room(const cJSON *raw, const char *name, char *err, size_t errn) static cJSON *validate_room(const cJSON *raw, const char *name, char *err, size_t errn)
{ {
@@ -343,69 +596,28 @@ static cJSON *validate_room(const cJSON *raw, const char *name, char *err, size_
cJSON_AddNumberToObject(o, "leds", (int)leds); cJSON_AddNumberToObject(o, "leds", (int)leds);
cJSON_AddNumberToObject(o, "pitch_m", round_to(pitch, 0.00001)); cJSON_AddNumberToObject(o, "pitch_m", round_to(pitch, 0.00001));
} }
const cJSON *dd_in = cJSON_GetObjectItem(raw, "dmx_definitions");
cJSON *dmx_defs = cJSON_AddObjectToObject(room, "dmx_definitions");
if (!err[0] && dd_in && !cJSON_IsNull(dd_in)) {
validate_dmx_defs(dd_in, dmx_defs, err, errn);
}
const cJSON *fx_in = cJSON_GetObjectItem(raw, "fixtures"), *f; const cJSON *fx_in = cJSON_GetObjectItem(raw, "fixtures"), *f;
cJSON *fixtures = cJSON_AddObjectToObject(room, "fixtures"); cJSON *fixtures = cJSON_AddObjectToObject(room, "fixtures");
if (!err[0] && fx_in && !cJSON_IsObject(fx_in)) { if (!err[0] && fx_in && !cJSON_IsObject(fx_in)) {
snprintf(err, errn, "fixtures must be an object keyed by id"); snprintf(err, errn, "fixtures must be an object keyed by id");
} }
if (!err[0] && cJSON_GetArraySize(fx_in) > MAX_FIXTURES) { if (!err[0] && cJSON_GetArraySize(fx_in) > MAX_FIXTURES) {
snprintf(err, errn, "at most %d strips in a room", MAX_FIXTURES); snprintf(err, errn, "at most %d fixtures in a room", MAX_FIXTURES);
} }
cJSON_ArrayForEach(f, fx_in) cJSON_ArrayForEach(f, fx_in)
{ {
if (err[0]) { if (err[0]) {
break; break;
} }
const char *fid = f->string; validate_fixture(f, defs, dmx_defs, fixtures, err, errn);
if (!id_ok(fid) || !cJSON_IsObject(f)) {
snprintf(err, errn, "strip ids are 1-40 letters, digits or -_.#, each an object");
break;
}
const cJSON *def = cJSON_GetObjectItem(f, "def"), *mac = cJSON_GetObjectItem(f, "mac");
const cJSON *label = cJSON_GetObjectItem(f, "label");
if (!cJSON_IsString(def) || !cJSON_GetObjectItem(defs, def->valuestring)) {
snprintf(err, errn, "strip %s: unknown strip type", fid);
break;
}
if (!cJSON_IsString(mac) || !mac_ok(mac->valuestring)) {
snprintf(err, errn, "strip %s: mac must be like 02:51:4d:00:00:01", fid);
break;
}
char m[18];
snprintf(m, sizeof(m), "%s", mac->valuestring);
for (char *c = m; *c; c++) {
*c = (char)tolower((unsigned char)*c);
}
const cJSON *other;
cJSON_ArrayForEach(other, fixtures)
{
const cJSON *om = cJSON_GetObjectItem(other, "mac");
if (cJSON_IsString(om) && !strcmp(om->valuestring, m)) {
snprintf(err, errn, "strip %s: mac %s is used twice in this room", fid, m);
}
}
if (err[0]) {
break;
}
char what[80];
cJSON *o = cJSON_AddObjectToObject(fixtures, fid);
char lab[48];
snprintf(lab, sizeof(lab), "%s", cJSON_IsString(label) && label->valuestring[0] ? label->valuestring : fid);
cJSON_AddStringToObject(o, "label", lab);
cJSON_AddStringToObject(o, "def", def->valuestring);
cJSON_AddStringToObject(o, "mac", m);
snprintf(what, sizeof(what), "%s x", fid);
cJSON_AddNumberToObject(o, "x", round_to(num_in(f, "x", 0, -1000, 1000, what, err, errn), 0.001));
snprintf(what, sizeof(what), "%s y", fid);
cJSON_AddNumberToObject(o, "y", round_to(num_in(f, "y", 0, -1000, 1000, what, err, errn), 0.001));
snprintf(what, sizeof(what), "%s direction", fid);
cJSON_AddNumberToObject(o, "direction",
round_to(wrap_deg(num_in(f, "direction", 90, -3600, 3600, what, err, errn)), 0.1));
const cJSON *leds = cJSON_GetObjectItem(f, "leds");
if (leds && !cJSON_IsNull(leds)) {
snprintf(what, sizeof(what), "%s leds", fid);
cJSON_AddNumberToObject(o, "leds", (int)num_in(f, "leds", 1, 1, MAX_LEDS, what, err, errn));
} }
if (!err[0]) {
dmx_overlaps(room, err, errn);
} }
if (err[0]) { if (err[0]) {
cJSON_Delete(room); cJSON_Delete(room);
@@ -567,7 +779,11 @@ static const cJSON *fixture_by_mac(const cJSON *room, const char *mac12)
const cJSON *f; const cJSON *f;
cJSON_ArrayForEach(f, cJSON_GetObjectItem(room, "fixtures")) cJSON_ArrayForEach(f, cJSON_GetObjectItem(room, "fixtures"))
{ {
const char *m = cJSON_GetObjectItem(f, "mac")->valuestring; const cJSON *mj = cJSON_GetObjectItem(f, "mac");
if (!cJSON_IsString(mj)) {
continue; // a DDP or Art-Net fixture
}
const char *m = mj->valuestring;
char h[13]; char h[13];
int k = 0; int k = 0;
for (const char *c = m; *c && k < 12; c++) { for (const char *c = m; *c && k < 12; c++) {
@@ -614,8 +830,8 @@ static bool send_frame(int fd, httpd_ws_type_t type, const uint8_t *data, size_t
return httpd_ws_send_frame_async(s_hd, fd, &f) == ESP_OK; return httpd_ws_send_frame_async(s_hd, fd, &f) == ESP_OK;
} }
// Called by bridge.c for the "browser" bridge: dst_mac(6) + packet // One binary frame to the page, its first byte the kind (0 ESP-NOW, 1 Art-Net, 2 DDP)
bool sim_rig_tx(const uint8_t *frame, size_t len) bool sim_rig_page_send(const uint8_t *frame, size_t len)
{ {
if (!s_tx_mu) { if (!s_tx_mu) {
return false; return false;
@@ -629,6 +845,44 @@ bool sim_rig_tx(const uint8_t *frame, size_t len)
return ok; return ok;
} }
// Called by bridge.c for the "browser" bridge: dst_mac(6) + packet, sent to the page behind a 0 byte
bool sim_rig_tx(const uint8_t *frame, size_t len)
{
uint8_t buf[1 + 6 + 256];
if (len + 1 > sizeof(buf)) {
return false;
}
buf[0] = 0;
memcpy(buf + 1, frame, len);
return sim_rig_page_send(buf, len + 1);
}
// The receiver listens on the DDP ports the room's DDP fixtures use
static void room_ports(const cJSON *room)
{
uint16_t ports[SIM_NET_MAX_DDP_PORTS];
int n = 0;
const cJSON *f;
cJSON_ArrayForEach(f, cJSON_GetObjectItem(room, "fixtures"))
{
const cJSON *p = cJSON_GetObjectItem(f, "port");
if (!strcmp(str_or(f, "type", ""), "ddp") && cJSON_IsNumber(p) && n < SIM_NET_MAX_DDP_PORTS) {
ports[n++] = (uint16_t)p->valueint;
}
}
sim_net_set_ddp_ports(ports, n);
}
static void active_room_ports(void)
{
char err[160];
cJSON *room = load_room(s_room, err, sizeof(err));
if (room) {
room_ports(room);
}
cJSON_Delete(room);
}
static esp_err_t ws_open(httpd_req_t *req) static esp_err_t ws_open(httpd_req_t *req)
{ {
if (auth_ws_admit(req, "sim", AUTH_VIEW) != ESP_OK) { if (auth_ws_admit(req, "sim", AUTH_VIEW) != ESP_OK) {
@@ -794,9 +1048,9 @@ static void next_mac(const cJSON *taken, char out[18])
const cJSON *f, *fixtures = room ? cJSON_GetObjectItem(room, "fixtures") : NULL; const cJSON *f, *fixtures = room ? cJSON_GetObjectItem(room, "fixtures") : NULL;
cJSON_ArrayForEach(f, fixtures) cJSON_ArrayForEach(f, fixtures)
{ {
const char *m = cJSON_GetObjectItem(f, "mac")->valuestring; const cJSON *m = cJSON_GetObjectItem(f, "mac");
if (all && len + 20 < cap) { if (all && cJSON_IsString(m) && len + 20 < cap) {
len += (size_t)snprintf(all + len, cap - len, "%s,", m); len += (size_t)snprintf(all + len, cap - len, "%s,", m->valuestring);
} }
} }
cJSON_Delete(room); cJSON_Delete(room);
@@ -870,6 +1124,10 @@ static esp_err_t api_handler(httpd_req_t *req)
cJSON_AddStringToObject(o, "mac", mac); cJSON_AddStringToObject(o, "mac", mac);
ret = api_json(req, "200 OK", o, true); ret = api_json(req, "200 OK", o, true);
} }
} else if (!strcmp(a, "dmx") && !b[0] && m == HTTP_GET) {
char q[32] = "";
bool data = httpd_req_get_url_query_str(req, q, sizeof(q)) == ESP_OK && strstr(q, "data=1");
ret = api_json(req, "200 OK", sim_net_status(data), true);
} else if (!strcmp(a, "rooms") && !b[0] && m == HTTP_GET) { } else if (!strcmp(a, "rooms") && !b[0] && m == HTTP_GET) {
ret = rooms_info(req); ret = rooms_info(req);
} else if (!strcmp(a, "rooms") && !b[0] && m == HTTP_POST) { } else if (!strcmp(a, "rooms") && !b[0] && m == HTTP_POST) {
@@ -939,6 +1197,9 @@ static esp_err_t api_handler(httpd_req_t *req)
ret = api_error(req, "500 Internal Server Error", "could not write the room"); ret = api_error(req, "500 Internal Server Error", "could not write the room");
cJSON_Delete(room); cJSON_Delete(room);
} else { } else {
if (!strcmp(b, s_room)) {
room_ports(room);
}
cJSON *o = cJSON_CreateObject(); cJSON *o = cJSON_CreateObject();
cJSON_AddItemToObject(o, "room", room); cJSON_AddItemToObject(o, "room", room);
ret = api_json(req, "200 OK", o, true); ret = api_json(req, "200 OK", o, true);
@@ -967,6 +1228,7 @@ static esp_err_t api_handler(httpd_req_t *req)
} else { } else {
snprintf(s_room, sizeof(s_room), "%s", nm->valuestring); snprintf(s_room, sizeof(s_room), "%s", nm->valuestring);
save_active(); save_active();
active_room_ports();
ESP_LOGI(TAG, "room: %s", s_room); ESP_LOGI(TAG, "room: %s", s_room);
ret = api_json(req, "200 OK", config_json(), true); ret = api_json(req, "200 OK", config_json(), true);
} }
@@ -989,6 +1251,8 @@ esp_err_t sim_rig_register(httpd_handle_t server)
return ESP_ERR_NO_MEM; return ESP_ERR_NO_MEM;
} }
load_active(); load_active();
sim_net_start();
active_room_ports();
const httpd_uri_t ws = { .uri = "/sim/ws", .method = HTTP_GET, .handler = ws_handler, .is_websocket = true, const httpd_uri_t ws = { .uri = "/sim/ws", .method = HTTP_GET, .handler = ws_handler, .is_websocket = true,
.handle_ws_control_frames = false, .ws_post_handshake_cb = ws_open }; .handle_ws_control_frames = false, .ws_post_handshake_cb = ws_open };
esp_err_t err = httpd_register_uri_handler(server, &ws); esp_err_t err = httpd_register_uri_handler(server, &ws);
+225
View File
@@ -0,0 +1,225 @@
"""The simulated rig's network fixtures (sim-controller/components/sim/sim_net.c and sim_rig.c): rooms with DDP and
Art-Net fixtures, and the Art-Net / DDP receiver behind GET /sim/api/dmx.
make sim-web # the controller with the rig at /sim/
python3 -m pytest test/api/test_sim_net.py --host localhost:8080
Skipped unless the controller serves /sim/api/dmx. The receiver must be on this machine (packets go to the
controller's host on UDP 6454 and 4048; LED_SIM_ARTNET_PORT moves the Art-Net one).
"""
import os
import socket
import time
from urllib.parse import urlparse
import pytest
from helpers import unique
ARTNET_PORT = int(os.environ.get("LED_SIM_ARTNET_PORT", "6454"))
DDP_PORT = 4048
@pytest.fixture(scope="module")
def sim(c):
r = c.get("/sim/api/dmx")
if r.status_code != 200:
pytest.skip("no simulated rig with network fixtures here")
return r.json()
@pytest.fixture(scope="module")
def udp_host(base_url):
return urlparse(base_url).hostname
@pytest.fixture
def room(c, sim):
"""A new room, deleted afterwards; yields its name."""
name = unique("net")[:40].replace(" ", "-")
r = c.post("/sim/api/rooms", json={"name": name, "width": 6, "depth": 4})
assert r.status_code == 200, r.text
yield name
current = c.get("/sim/api/rooms").json()["current"]
if current == name:
c.post("/sim/api/room", json={"name": "default"})
c.delete(f"/sim/api/rooms/{name}")
BCC145 = {"manufacturer": "beamZ", "model": "BCC145", "mode": "8 Channel",
"channels": ["Dimmer", "Strobe", "Red", "Green", "Blue", "White", "Macro", "Speed"]}
def base_room(fixtures, dmx_definitions=None):
return {"width": 6, "depth": 4, "definitions": {"bar-119": {"leds": 119}},
"dmx_definitions": dmx_definitions or {"beamZ BCC145": BCC145}, "fixtures": fixtures}
def put(c, name, body):
return c.put(f"/sim/api/rooms/{name}", json=body)
def artdmx(universe, data):
data = bytes(data) + b"\0" * (len(data) & 1)
n = len(data)
return (b"Art-Net\0" + bytes([0x00, 0x50, 0, 14, 1, 0, universe & 0xFF, (universe >> 8) & 0x7F, n >> 8, n & 0xFF])
+ data)
def ddp(offset, data, push=True):
n = len(data)
return bytes([0x40 | (1 if push else 0), 1, 0x0B, 1]) + offset.to_bytes(4, "big") + n.to_bytes(2, "big") + bytes(data)
def send(host, port, pkt):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.sendto(pkt, (host, port))
def status(c, data=False):
return c.get("/sim/api/dmx" + ("?data=1" if data else "")).json()
def wait_for(fn, timeout=3.0):
end = time.time() + timeout
while time.time() < end:
v = fn()
if v:
return v
time.sleep(0.05)
return fn()
# --- room schema ---------------------------------------------------------------------------------------------
def test_old_rooms_default_to_espnow(c, room):
r = put(c, room, base_room({"a": {"def": "bar-119", "mac": "02:51:4d:00:10:01", "x": 0, "y": 1}}))
assert r.status_code == 200, r.text
f = r.json()["room"]["fixtures"]["a"]
assert f["type"] == "espnow" and f["mac"] == "02:51:4d:00:10:01"
def test_ddp_and_artnet_fixtures_round_trip(c, room):
body = base_room({
"strip": {"type": "ddp", "def": "bar-119", "leds": 60, "port": 4049, "offset": 10, "color_order": "grb"},
"px": {"type": "artnet", "kind": "pixels", "def": "bar-119", "leds": 200, "universe": 1, "address": 1},
"can1": {"type": "artnet", "kind": "can", "dmx_def": "beamZ BCC145", "universe": 0, "address": 9},
"mover": {"type": "artnet", "kind": "mover", "dmx_def": "beamZ BCC145", "universe": 0, "address": 17,
"zero": 45, "pan_reverse": True},
})
r = put(c, room, body)
assert r.status_code == 200, r.text
fx = c.get(f"/sim/api/rooms/{room}").json()["fixtures"]
assert fx["strip"]["port"] == 4049 and fx["strip"]["offset"] == 10
assert fx["strip"]["color_order"] == "grb" and "mac" not in fx["strip"]
assert fx["px"]["kind"] == "pixels" and fx["px"]["color_order"] == "rgb"
assert fx["can1"]["dmx_def"] == "beamZ BCC145" and "def" not in fx["can1"]
assert fx["mover"]["zero"] == 45 and fx["mover"]["pan_reverse"] is True
assert c.get(f"/sim/api/rooms/{room}").json()["dmx_definitions"]["beamZ BCC145"]["channels"][2] == "Red"
@pytest.mark.parametrize("fixture, words", [
({"type": "dmx"}, "type is"),
({"type": "artnet", "kind": "laser", "universe": 0, "address": 1}, "kind is"),
({"type": "artnet", "kind": "can", "dmx_def": "nope", "universe": 0, "address": 1}, "dmx_def"),
({"type": "artnet", "kind": "can", "dmx_def": "beamZ BCC145", "universe": 0, "address": 600}, "address"),
({"type": "artnet", "kind": "can", "dmx_def": "beamZ BCC145", "universe": 0, "address": 510}, "past channel 512"),
({"type": "ddp", "def": "bar-119", "port": 70000}, "port"),
({"type": "ddp", "def": "bar-119", "color_order": "rgbw"}, "color_order"),
({"type": "ddp"}, "strip type"),
])
def test_bad_fixtures_are_refused(c, room, fixture, words):
r = put(c, room, base_room({"f": fixture}))
assert r.status_code == 400 and words in r.json()["error"], r.text
def test_dmx_fixtures_may_not_share_channels(c, room):
body = base_room({
"a": {"type": "artnet", "kind": "can", "dmx_def": "beamZ BCC145", "universe": 0, "address": 1},
"b": {"type": "artnet", "kind": "can", "dmx_def": "beamZ BCC145", "universe": 0, "address": 8},
})
r = put(c, room, body)
assert r.status_code == 400 and "share DMX channels" in r.json()["error"]
body["fixtures"]["b"]["address"] = 9
assert put(c, room, body).status_code == 200
body["fixtures"]["b"]["universe"] = 1
body["fixtures"]["b"]["address"] = 1
assert put(c, room, body).status_code == 200
def test_pixels_run_on_into_the_next_universe(c, room):
# 200 pixels from universe 0: 170 there, 30 in universe 1, which a can at 1 then overlaps
body = base_room({
"px": {"type": "artnet", "kind": "pixels", "def": "bar-119", "leds": 200, "universe": 0, "address": 1},
"can": {"type": "artnet", "kind": "can", "dmx_def": "beamZ BCC145", "universe": 1, "address": 1},
})
assert put(c, room, body).status_code == 400
body["fixtures"]["can"]["address"] = 91 # past 30 pixels (90 channels)
assert put(c, room, body).status_code == 200
def test_bad_dmx_definitions_are_refused(c, room):
r = put(c, room, base_room({}, {"empty": {"channels": []}}))
assert r.status_code == 400 and "channels" in r.json()["error"]
# --- the receiver --------------------------------------------------------------------------------------------
def test_artnet_universe_is_received(c, sim, udp_host):
if not sim["artnet"]["listening"]:
pytest.skip("Art-Net port not open: " + sim["artnet"].get("error", ""))
before = sim["artnet"]["packets"]
frame = bytes([255, 0, 200, 10, 20]) + bytes(507)
send(udp_host, ARTNET_PORT, artdmx(7, frame))
got = wait_for(lambda: status(c, True)["artnet"]["universes"].get("7"))
assert got and got["data"].startswith("ff00c80a14")
assert status(c)["artnet"]["packets"] > before
def test_artpoll_gets_a_reply(sim, udp_host):
if not sim["artnet"]["listening"]:
pytest.skip("Art-Net port not open")
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.settimeout(2)
s.sendto(b"Art-Net\0" + bytes([0x00, 0x20, 0, 14, 0, 0]), (udp_host, ARTNET_PORT))
reply, _ = s.recvfrom(1024)
assert reply.startswith(b"Art-Net\0") and reply[8:10] == bytes([0x00, 0x21])
assert b"led-sim" in reply
def test_ddp_port_follows_the_active_room(c, room, udp_host):
body = base_room({"s": {"type": "ddp", "def": "bar-119", "leds": 10, "port": 4051}})
assert put(c, room, body).status_code == 200
assert c.post("/sim/api/room", json={"name": room}).status_code == 200
assert wait_for(lambda: status(c)["ddp"].get("4051", {}).get("listening"))
send(udp_host, 4051, ddp(3, [1, 2, 3, 4, 5, 6]))
got = wait_for(lambda: status(c, True)["ddp"]["4051"]["packets"] and status(c, True)["ddp"]["4051"])
assert got["data"] == "000000" + "010203040506" and got["pixels"] == 3
c.post("/sim/api/room", json={"name": "default"})
assert wait_for(lambda: "4051" not in status(c)["ddp"])
def test_controller_artnet_output_reaches_the_sim(c, sim):
"""A controller output aimed at the sim: its test frames land in the universe. The test request holds the
HTTP server until red, green, blue, white and black have gone out, so only the end state can be read here."""
if not sim["artnet"]["listening"]:
pytest.skip("Art-Net port not open")
r = c.post("/outputs", json={"name": unique("sim-out"), "protocol": "artnet", "host": "127.0.0.1",
"port": ARTNET_PORT, "universe": 300, "pixel_count": 4, "enabled": True})
if r.status_code not in (200, 201):
pytest.skip(f"outputs not available: {r.status_code}")
oid = r.json().get("id")
before = status(c)["artnet"]["universes"].get("300", {}).get("packets", 0)
try:
r = c.post(f"/outputs/{oid}/test", json={"step_s": 0.2}, timeout=20)
assert r.status_code == 200, r.text
sent = r.json()["status"]["packets"]
u = wait_for(lambda: (s := status(c, True)["artnet"]["universes"].get("300")) and
s["packets"] - before >= sent and s)
assert u and u["packets"] - before >= sent >= 5, (u, sent)
assert bytes.fromhex(u["data"])[:12] == bytes(12) # ends on black
finally:
c.delete(f"/outputs/{oid}")
+114
View File
@@ -0,0 +1,114 @@
// The simulated rig's DMX decoder (led-simulator/web/dmx.js), checked against the qlcplus simulator's rules
// (technicalkiwi/qlcplus simulator/decode.py): node --test test/browser/dmx_decode.test.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { test } from 'node:test';
createRequire(import.meta.url)('../../led-simulator/web/dmx.js');
const D = globalThis.RigDmx;
const CAN = D.PRESET_DEFINITIONS['beamZ BCC145'].channels;
const MOVER = D.PRESET_DEFINITIONS['Small Eye 7 Mover'].channels;
function universe(at, values) {
const f = new Uint8Array(512);
f.set(values, at - 1);
return new Map([[0, f]]);
}
const can = (values, address = 1) =>
D.viewFixture({ kind: 'can', universe: 0, address, channel_names: CAN }, universe(address, values));
const mover = (values, extra = {}) =>
D.viewFixture({ kind: 'mover', universe: 0, address: 1, channel_names: MOVER, ...extra }, universe(1, values));
test('a can at full dimmer and red shows red', () => {
const v = can([255, 0, 255, 0, 0, 0, 0, 0]);
assert.deepEqual([v.r, v.g, v.b], [255, 0, 0]);
assert.equal(v.function, 'mix');
assert.equal(v.strobe_hz, 0);
assert.equal(v.patched, true);
});
test('the can reads from its own address', () => {
const v = can([128, 0, 0, 0, 255, 0, 0, 0], 95);
assert.deepEqual([v.r, v.g, v.b], [0, 0, 128]);
});
test('white adds to every colour and the dimmer scales the mix', () => {
const v = can([128, 0, 100, 0, 0, 100, 0, 0]);
// mix_rgbw: min(255, 100 + 100) * 128/255 = 100.39 -> 100; 100 * 128/255 = 50.2 -> 50
assert.deepEqual([v.r, v.g, v.b], [100, 50, 50]);
});
test('can strobe above 7 flashes, at the qlcplus rate', () => {
assert.equal(can([255, 7, 255]).strobe_hz, 0);
const v = can([255, 131, 255]);
// 1 + (131 - 7) / 248 * 18 = 10
assert.equal(v.strobe_hz, 10);
assert.equal(v.strobe_mode, 'strobe');
});
test('can macro bands pick the function', () => {
assert.equal(can([255, 0, 0, 0, 0, 0, 60]).function, 'fixed');
assert.equal(can([255, 0, 0, 0, 0, 0, 120]).function, 'jump');
assert.equal(can([255, 0, 0, 0, 0, 0, 255]).sound, 2);
// fixed: (60 - 51) * 10 // 50 = 1 -> orange
const v = can([255, 0, 0, 0, 0, 0, 60]);
assert.deepEqual([v.r, v.g, v.b], [255, 96, 0]);
});
test('a mover at pan and tilt centre points along its zero, straight down', () => {
const v = mover([128, 0, 128, 0]);
assert.equal(v.pan_deg, 0);
assert.equal(v.tilt_deg, 0);
assert.equal(v.beam_m, 0);
});
test('mover pan spans 540 degrees and pan_reverse mirrors it', () => {
// (0xC000 - 0x8000) / 65536 * 540 = 135
assert.equal(mover([192, 0, 128, 0]).pan_deg, 135);
assert.equal(mover([192, 0, 128, 0], { pan_reverse: true }).pan_deg, -135);
});
test('mover tilt leans the beam out on the plan', () => {
const v = mover([128, 0, 0, 0]);
// tilt (0 - 32768) / 65536 * 270 = -135; lean = min(90, 135) = 90 -> full reach
assert.equal(v.tilt_deg, -135);
assert.equal(v.beam_m, D.BEAM_MAX_M);
});
test('mover pixels, dimmer and strobe', () => {
const ch = new Array(43).fill(0);
ch[MOVER.indexOf('Center Brightness')] = 255;
ch[MOVER.indexOf('Green 1')] = 200;
ch[MOVER.indexOf('Center Strobe')] = 220;
const v = mover(ch);
assert.equal(v.pixels.length, 7);
assert.deepEqual(v.pixels[0], [0, 200, 0]);
assert.deepEqual([v.r, v.g, v.b], [0, 200, 0]);
assert.equal(v.strobe_mode, 'random');
assert.equal(v.strobe_hz, 12);
});
test('mover colour macro fills all seven pixels', () => {
const ch = new Array(43).fill(0);
ch[MOVER.indexOf('Center Brightness')] = 255;
ch[MOVER.indexOf('Colour Macro')] = 10; // first band: red
const v = mover(ch);
assert.equal(v.function, 'macro');
assert.ok(v.pixels.every((p) => p[0] === 255 && p[1] === 0 && p[2] === 0));
});
test('an unpatched fixture is dark', () => {
const v = D.viewFixture({ kind: 'can', universe: 0, address: 0, channel_names: CAN }, new Map());
assert.equal(v.patched, false);
});
test('Art-Net pixels run on into the next universe, 170 a universe', () => {
const u0 = new Uint8Array(512).fill(1);
const u1 = new Uint8Array(512).fill(2);
const px = D.artnetPixels(new Map([[0, u0], [1, u1]]), 0, 1, 200);
assert.equal(px.length, 600);
assert.equal(px[509], 1);
assert.equal(px[510], 2);
assert.deepEqual(D.dmxRuns({ kind: 'pixels', universe: 0, address: 1 }, {}, 200), [[0, 0, 510], [1, 0, 90]]);
});
+1 -1
View File
@@ -12,7 +12,7 @@ mkdir -p "$OUT"
python3 - "$SRC" "$OUT/sim.pack" <<'PY' python3 - "$SRC" "$OUT/sim.pack" <<'PY'
import gzip, os, struct, sys import gzip, os, struct, sys
src, out_path = sys.argv[1], sys.argv[2] src, out_path = sys.argv[1], sys.argv[2]
files = ["index.html", "app.js", "layout.js", "styles.css", "driver-worker.js", files = ["index.html", "app.js", "layout.js", "dmx.js", "dmx-draw.js", "styles.css", "driver-worker.js",
"gallery.html", "gallery.js", "gallery.css", "gallery.html", "gallery.js", "gallery.css",
"wasm/led_driver.mjs", "wasm/led_driver.wasm", "wasm/led_fx.mjs", "wasm/led_fx.wasm"] "wasm/led_driver.mjs", "wasm/led_driver.wasm", "wasm/led_fx.mjs", "wasm/led_fx.wasm"]
out = bytearray(b"WWW1") out = bytearray(b"WWW1")