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
+2859 -118

No files matched your search

+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" "."
REQUIRES esp_http_server esp_timer esp_event cjson main freertos)
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);
+322 -58
View File
@@ -6,7 +6,8 @@
* 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.
* 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
* 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
@@ -16,11 +17,17 @@
* GET|PUT|DELETE /sim/api/rooms/<name>
* 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
* 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
* 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
* <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 "sim_rig.h"
@@ -39,12 +46,15 @@
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "sim_net.h"
#include "store.h"
static const char *TAG = "sim_rig";
#define MAX_FIXTURES 64
#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 FRAME_MAX (FLASH_MAX + 1024)
#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;
}
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
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, "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;
cJSON *fixtures = cJSON_AddObjectToObject(room, "fixtures");
if (!err[0] && fx_in && !cJSON_IsObject(fx_in)) {
snprintf(err, errn, "fixtures must be an object keyed by id");
}
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)
{
if (err[0]) {
break;
}
const char *fid = f->string;
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));
}
validate_fixture(f, defs, dmx_defs, fixtures, err, errn);
}
if (!err[0]) {
dmx_overlaps(room, err, errn);
}
if (err[0]) {
cJSON_Delete(room);
@@ -567,7 +779,11 @@ static const cJSON *fixture_by_mac(const cJSON *room, const char *mac12)
const cJSON *f;
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];
int k = 0;
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;
}
// Called by bridge.c for the "browser" bridge: dst_mac(6) + packet
bool sim_rig_tx(const uint8_t *frame, size_t len)
// One binary frame to the page, its first byte the kind (0 ESP-NOW, 1 Art-Net, 2 DDP)
bool sim_rig_page_send(const uint8_t *frame, size_t len)
{
if (!s_tx_mu) {
return false;
@@ -629,6 +845,44 @@ bool sim_rig_tx(const uint8_t *frame, size_t len)
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)
{
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;
cJSON_ArrayForEach(f, fixtures)
{
const char *m = cJSON_GetObjectItem(f, "mac")->valuestring;
if (all && len + 20 < cap) {
len += (size_t)snprintf(all + len, cap - len, "%s,", m);
const cJSON *m = cJSON_GetObjectItem(f, "mac");
if (all && cJSON_IsString(m) && len + 20 < cap) {
len += (size_t)snprintf(all + len, cap - len, "%s,", m->valuestring);
}
}
cJSON_Delete(room);
@@ -870,6 +1124,10 @@ static esp_err_t api_handler(httpd_req_t *req)
cJSON_AddStringToObject(o, "mac", mac);
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) {
ret = rooms_info(req);
} 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");
cJSON_Delete(room);
} else {
if (!strcmp(b, s_room)) {
room_ports(room);
}
cJSON *o = cJSON_CreateObject();
cJSON_AddItemToObject(o, "room", room);
ret = api_json(req, "200 OK", o, true);
@@ -967,6 +1228,7 @@ static esp_err_t api_handler(httpd_req_t *req)
} else {
snprintf(s_room, sizeof(s_room), "%s", nm->valuestring);
save_active();
active_room_ports();
ESP_LOGI(TAG, "room: %s", s_room);
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;
}
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,
.handle_ws_control_frames = false, .ws_post_handshake_cb = ws_open };
esp_err_t err = httpd_register_uri_handler(server, &ws);