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

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

971 lines
32 KiB
C

// DMX bridge: see bridge_dmx.h. Linux host build only (it starts processes and opens tty devices).
//
// Threads: the bridge's worker reads the record, starts and watches the fixture processes, reads what they send,
// and every 25 ms builds the universes and sends them to the network outputs. Each USB-DMX output has a thread of
// its own, since a frame at 250 kbaud takes most of the 25 ms to go out. bridge_dmx_send runs in the caller's
// thread and writes to the fixtures' pipes under the bridge's lock.
#ifndef _GNU_SOURCE
#define _GNU_SOURCE // pipe2
#endif
#include "bridge_dmx.h"
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <spawn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include "cJSON.h"
#include "dmx_wire.h"
#include "esp_log.h"
#include "esp_mac.h"
#include "store.h"
extern char **environ;
static const char *TAG = "bridge_dmx";
#define TICK_US (1000000 / DMX_REFRESH_HZ)
#define MSG_MAX (3 + 0xFFFF)
#define RESTART_MIN_MS 1000
#define RESTART_MAX_MS 10000
#define SERIAL_RETRY_MS 2000
enum { OUT_ARTNET, OUT_SACN, OUT_SERIAL, OUT_SIM };
enum { MODE_ENTTEC_PRO, MODE_OPEN_DMX };
// Serial port I/O lives in bridge_dmx_serial.c (it needs the kernel's termios2, which clashes with <termios.h>)
int dmx_serial_open(const char *path, bool open_dmx, char *err, size_t elen);
bool dmx_serial_write(int fd, bool open_dmx, const uint8_t data[DMX_CHANNELS]);
// The rig page's network fixtures (sim-controller/components/sim/sim_net.c): a universe straight to the page
void sim_net_put_universe(int uni, const uint8_t data[512]);
typedef struct bridge_dmx bridge_dmx_t;
typedef struct {
char id[16], name[64];
uint8_t mac[6];
char hex[13];
int universe; // index into the bridge's universes
int address; // 1-based start channel
int nslots, pixels;
dmx_slot_t slots[DMX_CHANNELS];
bool dimmer; // has a dimmer channel: its level comes from the process ('B')
// the process
pid_t pid; // 0: not running
int in_fd, out_fd; // its stdin (we write), its stdout (we read)
uint8_t *rbuf;
size_t rlen;
uint8_t px[3 * DMX_PIXELS_MAX];
int npx;
uint8_t bright; // the output level from the process, for the dimmer channel (255 until it sends one)
int64_t restart_at_us;
int backoff_ms;
uint32_t starts;
} fixture_t;
typedef struct serial_out serial_out_t;
typedef struct {
int type;
char host[64];
int port, universe; // universe: the number on the wire
bool enabled;
struct sockaddr_in to;
bool resolved;
uint8_t seq;
serial_out_t *serial; // OUT_SERIAL: its thread
} output_t;
typedef struct {
char id[16], name[64];
int number;
output_t *outs;
int nouts;
uint8_t data[DMX_CHANNELS];
} universe_t;
struct serial_out {
bridge_dmx_t *b;
char path[96];
bool open_dmx;
pthread_t th;
pthread_mutex_t mu; // data
uint8_t data[DMX_CHANNELS];
volatile bool stop;
};
struct bridge_dmx {
char id[16];
bridge_dmx_rx_t rx;
pthread_t worker;
volatile bool stop;
volatile bool reload;
int wake[2];
pthread_mutex_t mu; // fixtures' pids and fds (send), the config arrays (status), the counters
char name[64];
universe_t *unis;
int nunis;
fixture_t **fx;
int nfx;
int sock;
uint8_t cid[16];
uint8_t own_mac[6];
uint32_t frames, packets, errors;
char last_error[128];
bool missing; // the record does not exist
bridge_dmx_t *next; // the registry of open bridges
};
static pthread_mutex_t s_reg_mu = PTHREAD_MUTEX_INITIALIZER;
static bridge_dmx_t *s_open;
static int64_t mono_us(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (int64_t)ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
}
static void set_error(bridge_dmx_t *b, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
static void set_error(bridge_dmx_t *b, const char *fmt, ...)
{
char text[128];
va_list ap;
va_start(ap, fmt);
vsnprintf(text, sizeof(text), fmt, ap);
va_end(ap);
pthread_mutex_lock(&b->mu);
b->errors++;
if (strcmp(b->last_error, text) != 0) {
snprintf(b->last_error, sizeof(b->last_error), "%s", text);
ESP_LOGW(TAG, "%s: %s", b->id, text);
}
pthread_mutex_unlock(&b->mu);
}
static bool parse_mac(const char *hex, uint8_t mac[6])
{
if (!hex || strlen(hex) != 12) {
return false;
}
for (int i = 0; i < 6; i++) {
char pair[3] = { hex[2 * i], hex[2 * i + 1], 0 };
char *end;
mac[i] = (uint8_t)strtol(pair, &end, 16);
if (*end) {
return false;
}
}
return true;
}
/* ------------------------------------------------------------- fixtures */
// The led-fixture program: LED_FIXTURE_BIN, else next to this program, else on the PATH
static void fixture_bin(char *out, size_t n)
{
const char *env = getenv("LED_FIXTURE_BIN");
if (env && env[0]) {
snprintf(out, n, "%s", env);
return;
}
char self[400];
ssize_t len = readlink("/proc/self/exe", self, sizeof(self) - 1);
if (len > 0) {
self[len] = 0;
char *slash = strrchr(self, '/');
if (slash) {
*slash = 0;
snprintf(out, n, "%s/led-fixture", self);
if (access(out, X_OK) == 0) {
return;
}
}
}
snprintf(out, n, "led-fixture");
}
// The fixture's flash: kept between starts, with the strip settings the bridge owns set each time
static bool write_flash(bridge_dmx_t *b, const fixture_t *f, char *path, size_t n)
{
char dir[256];
snprintf(dir, sizeof(dir), "%s/dmx", store_dir());
mkdir(dir, 0755);
snprintf(path, n, "%s/%s.json", dir, f->hex);
cJSON *root = NULL;
FILE *in = fopen(path, "rb");
if (in) {
char buf[16384];
size_t got = fread(buf, 1, sizeof(buf) - 1, in);
buf[got] = 0;
fclose(in);
root = cJSON_Parse(buf);
}
if (!cJSON_IsObject(root)) {
cJSON_Delete(root);
root = cJSON_CreateObject();
}
cJSON *ns = cJSON_GetObjectItem(root, "led");
if (!cJSON_IsObject(ns)) {
cJSON_DeleteItemFromObject(root, "led");
ns = cJSON_AddObjectToObject(root, "led");
}
struct {
const char *key, *type;
cJSON *val;
} SET[] = {
{ "num_leds", "i32", cJSON_CreateNumber(f->pixels) },
{ "rgb_order", "str", cJSON_CreateString("rgb") },
{ "hostname", "str", cJSON_CreateString(f->name) },
};
for (size_t i = 0; i < sizeof(SET) / sizeof(SET[0]); i++) {
cJSON *pair = cJSON_CreateArray();
cJSON_AddItemToArray(pair, cJSON_CreateString(SET[i].type));
cJSON_AddItemToArray(pair, SET[i].val);
cJSON_DeleteItemFromObject(ns, SET[i].key);
cJSON_AddItemToObject(ns, SET[i].key, pair);
}
char *json = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
char tmp[300];
snprintf(tmp, sizeof(tmp), "%s.tmp", path);
FILE *out = fopen(tmp, "wb");
bool ok = out && json && fputs(json, out) >= 0;
ok = out && fclose(out) == 0 && ok;
ok = ok && rename(tmp, path) == 0;
free(json);
if (!ok) {
set_error(b, "cannot write %s", path);
}
return ok;
}
static void fixture_spawn(bridge_dmx_t *b, fixture_t *f)
{
char flash[300], bin[512];
if (!write_flash(b, f, flash, sizeof(flash))) {
f->restart_at_us = mono_us() + (int64_t)RESTART_MAX_MS * 1000;
return;
}
fixture_bin(bin, sizeof(bin));
int in[2], out[2];
if (pipe2(in, O_CLOEXEC) != 0) {
set_error(b, "pipe: errno %d", errno);
return;
}
if (pipe2(out, O_CLOEXEC) != 0) {
close(in[0]);
close(in[1]);
set_error(b, "pipe: errno %d", errno);
return;
}
posix_spawn_file_actions_t fa;
posix_spawn_file_actions_init(&fa);
posix_spawn_file_actions_adddup2(&fa, in[0], 0);
posix_spawn_file_actions_adddup2(&fa, out[1], 1);
#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 34))
// Only stdin/stdout/stderr go to the fixture: without this it keeps whatever the controller has open without
// close-on-exec (a bridge's serial port, UDP sockets), holding a USB board open after the controller lets go
posix_spawn_file_actions_addclosefrom_np(&fa, 3);
#endif
char *argv[] = { bin, f->hex, flash, f->dimmer ? (char *)"dimmer" : NULL, NULL };
pid_t pid = 0;
int err = posix_spawnp(&pid, bin, &fa, NULL, argv, environ);
posix_spawn_file_actions_destroy(&fa);
close(in[0]);
close(out[1]);
if (err != 0) {
close(in[1]);
close(out[0]);
set_error(b, "cannot start %s for fixture %s: %s", bin, f->name, strerror(err));
f->restart_at_us = mono_us() + (int64_t)RESTART_MAX_MS * 1000;
return;
}
fcntl(in[1], F_SETFL, O_NONBLOCK); // a stalled fixture loses frames, as on air; the controller never waits
fcntl(out[0], F_SETFL, O_NONBLOCK);
pthread_mutex_lock(&b->mu);
f->pid = pid;
f->in_fd = in[1];
f->out_fd = out[0];
f->rlen = 0;
f->starts++;
pthread_mutex_unlock(&b->mu);
ESP_LOGI(TAG, "%s: fixture %s (%s) started, pid %d", b->id, f->name, f->hex, (int)pid);
}
// Stop the process (if any). With restart, it starts again after the back-off.
static void fixture_stop(bridge_dmx_t *b, fixture_t *f, bool restart)
{
pthread_mutex_lock(&b->mu);
pid_t pid = f->pid;
if (f->in_fd >= 0) {
close(f->in_fd); // the process exits on EOF
}
if (f->out_fd >= 0) {
close(f->out_fd);
}
f->in_fd = f->out_fd = -1;
f->pid = 0;
f->npx = 0;
pthread_mutex_unlock(&b->mu);
if (pid > 0) {
int status;
for (int i = 0; i < 50 && waitpid(pid, &status, WNOHANG) == 0; i++) {
usleep(10000);
}
if (waitpid(pid, &status, WNOHANG) == 0) {
kill(pid, SIGKILL);
waitpid(pid, &status, 0);
}
}
if (restart) {
f->backoff_ms = f->backoff_ms ? f->backoff_ms * 2 : RESTART_MIN_MS;
f->backoff_ms = f->backoff_ms > RESTART_MAX_MS ? RESTART_MAX_MS : f->backoff_ms;
f->restart_at_us = mono_us() + (int64_t)f->backoff_ms * 1000;
}
}
// Close the stdin of each of these fixtures at once, so they all exit together before each is waited for
static void close_inputs(bridge_dmx_t *b, fixture_t **fx, int n)
{
pthread_mutex_lock(&b->mu);
for (int i = 0; i < n; i++) {
if (fx[i] && fx[i]->in_fd >= 0) {
close(fx[i]->in_fd);
fx[i]->in_fd = -1;
}
}
pthread_mutex_unlock(&b->mu);
}
static void fixture_free(bridge_dmx_t *b, fixture_t *f)
{
if (f) {
fixture_stop(b, f, false);
free(f->rbuf);
free(f);
}
}
// Whole messages from the fixture's stdout. False when the process has gone.
static bool fixture_read(bridge_dmx_t *b, fixture_t *f)
{
for (;;) {
ssize_t got = read(f->out_fd, f->rbuf + f->rlen, MSG_MAX - f->rlen);
if (got == 0) {
return false;
}
if (got < 0) {
return errno == EAGAIN || errno == EINTR;
}
f->rlen += (size_t)got;
size_t off = 0;
while (f->rlen - off >= 3) {
const uint8_t *m = f->rbuf + off;
size_t len = m[1] | ((size_t)m[2] << 8);
if (f->rlen - off < 3 + len) {
break;
}
if (m[0] == 'T' && len > 6 && b->rx) {
b->rx(f->mac, m + 3 + 6, (int)len - 6); // dest MAC dropped: every frame is heard by the controller
} else if (m[0] == 'F') {
size_t n = len > sizeof(f->px) ? sizeof(f->px) : len;
memcpy(f->px, m + 3, n);
f->npx = (int)(n / 3);
f->backoff_ms = 0; // it runs: the next restart starts quickly again
} else if (m[0] == 'B' && len == 1) {
f->bright = m[3];
}
off += 3 + len;
}
memmove(f->rbuf, f->rbuf + off, f->rlen - off);
f->rlen -= off;
}
}
/* -------------------------------------------------------------- outputs */
static void *serial_task(void *arg)
{
serial_out_t *s = arg;
int fd = -1;
int64_t next = mono_us();
uint8_t frame[DMX_CHANNELS];
while (!s->stop) {
if (fd < 0) {
char err[96];
fd = dmx_serial_open(s->path, s->open_dmx, err, sizeof(err));
if (fd < 0) {
set_error(s->b, "%s", err);
for (int i = 0; i < SERIAL_RETRY_MS / 50 && !s->stop; i++) {
usleep(50000);
}
continue;
}
ESP_LOGI(TAG, "%s: DMX out on %s (%s)", s->b->id, s->path, s->open_dmx ? "Open DMX" : "Enttec DMX USB Pro");
}
pthread_mutex_lock(&s->mu);
memcpy(frame, s->data, sizeof(frame));
pthread_mutex_unlock(&s->mu);
if (!dmx_serial_write(fd, s->open_dmx, frame)) {
set_error(s->b, "%s: write failed (errno %d)", s->path, errno);
close(fd);
fd = -1;
continue;
}
pthread_mutex_lock(&s->b->mu);
s->b->packets++;
pthread_mutex_unlock(&s->b->mu);
next += TICK_US;
int64_t now = mono_us();
if (next < now - 4 * TICK_US) {
next = now; // fell behind (a slow port): no burst
}
if (next > now) {
usleep((useconds_t)(next - now));
}
}
if (fd >= 0) {
close(fd);
}
return NULL;
}
static void outputs_resolve(bridge_dmx_t *b, output_t *o)
{
memset(&o->to, 0, sizeof(o->to));
o->to.sin_family = AF_INET;
o->to.sin_port = htons(o->port);
o->resolved = true;
if (!o->host[0]) {
o->to.sin_addr.s_addr = htonl(o->type == OUT_SACN ? dmx_sacn_group(o->universe) : INADDR_BROADCAST);
return;
}
if (inet_aton(o->host, &o->to.sin_addr)) {
return;
}
struct addrinfo hints = { .ai_family = AF_INET, .ai_socktype = SOCK_DGRAM }, *res = NULL;
if (getaddrinfo(o->host, NULL, &hints, &res) != 0 || !res) {
o->resolved = false;
set_error(b, "cannot resolve %s", o->host);
return;
}
o->to.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
freeaddrinfo(res);
}
// Each universe's 512 channels from its fixtures' pixels, then out to its outputs
static void send_universes(bridge_dmx_t *b)
{
for (int u = 0; u < b->nunis; u++) {
memset(b->unis[u].data, 0, DMX_CHANNELS);
}
for (int i = 0; i < b->nfx; i++) {
fixture_t *f = b->fx[i];
uint8_t *d = b->unis[f->universe].data + f->address - 1;
bool has_white[DMX_PIXELS_MAX] = { false };
for (int k = 0; k < f->nslots; k++) {
if (f->slots[k].role == DMX_ROLE_WHITE) {
has_white[f->slots[k].pixel] = true;
}
}
for (int k = 0; k < f->nslots && f->address - 1 + k < DMX_CHANNELS; k++) {
const dmx_slot_t *s = &f->slots[k];
int p = s->pixel;
int r = 0, g = 0, bl = 0;
if (p < f->npx) {
r = f->px[3 * p];
g = f->px[3 * p + 1];
bl = f->px[3 * p + 2];
}
int w = r < g ? (r < bl ? r : bl) : (g < bl ? g : bl);
int take = has_white[p] ? w : 0; // RGBW: white carries what red, green and blue share
switch (s->role) {
case DMX_ROLE_RED: d[k] = (uint8_t)(r - take); break;
case DMX_ROLE_GREEN: d[k] = (uint8_t)(g - take); break;
case DMX_ROLE_BLUE: d[k] = (uint8_t)(bl - take); break;
case DMX_ROLE_WHITE: d[k] = (uint8_t)w; break;
case DMX_ROLE_DIMMER: d[k] = f->pid ? f->bright : 0; break; // a fixture whose driver is down stays dark
case DMX_ROLE_STROBE: d[k] = 0; break;
default: d[k] = s->value; break;
}
}
}
static uint8_t pkt[DMX_PACKET_MAX];
uint32_t sent = 0;
for (int u = 0; u < b->nunis; u++) {
universe_t *un = &b->unis[u];
for (int o = 0; o < un->nouts; o++) {
output_t *out = &un->outs[o];
if (!out->enabled) {
continue;
}
if (out->type == OUT_SERIAL) {
pthread_mutex_lock(&out->serial->mu);
memcpy(out->serial->data, un->data, DMX_CHANNELS);
pthread_mutex_unlock(&out->serial->mu);
continue;
}
if (out->type == OUT_SIM) { // inside this process, like the browser bridge's radio
sim_net_put_universe(out->universe, un->data);
sent++;
continue;
}
if (!out->resolved || b->sock < 0) {
continue;
}
size_t len;
if (out->type == OUT_ARTNET) {
out->seq = out->seq % 255 + 1;
len = dmx_artnet_packet(pkt, out->seq, out->universe, un->data, DMX_CHANNELS);
} else {
out->seq++;
char source[64];
snprintf(source, sizeof(source), "led-controller %.48s", b->name);
len = dmx_sacn_packet(pkt, b->cid, source, out->seq, out->universe, un->data, DMX_CHANNELS);
}
if (sendto(b->sock, pkt, len, 0, (struct sockaddr *)&out->to, sizeof(out->to)) < 0) {
set_error(b, "send to %s universe %d: errno %d", out->host[0] ? out->host : "broadcast", out->universe,
errno);
} else {
sent++;
}
}
}
pthread_mutex_lock(&b->mu);
b->frames++;
b->packets += sent;
pthread_mutex_unlock(&b->mu);
}
/* --------------------------------------------------------------- config */
static int num_or(const cJSON *v, int dflt)
{
return cJSON_IsNumber(v) ? v->valueint : dflt;
}
static void str_of(const cJSON *obj, const char *key, char *out, size_t n)
{
const cJSON *v = cJSON_GetObjectItem(obj, key);
snprintf(out, n, "%s", cJSON_IsString(v) ? v->valuestring : "");
}
static void free_config(universe_t *unis, int nunis)
{
for (int u = 0; u < nunis; u++) {
for (int o = 0; o < unis[u].nouts; o++) {
serial_out_t *s = unis[u].outs[o].serial;
if (s) {
s->stop = true;
pthread_join(s->th, NULL);
pthread_mutex_destroy(&s->mu);
free(s);
}
}
free(unis[u].outs);
}
free(unis);
}
// Read the record into new universes and fixtures (the fixtures not started). Takes the store lock.
static bool load_config(bridge_dmx_t *b, char *name, universe_t **unis_out, int *nunis_out, fixture_t ***fx_out,
int *nfx_out)
{
*unis_out = NULL;
*nunis_out = 0;
*fx_out = NULL;
*nfx_out = 0;
store_lock();
const cJSON *rec = cJSON_GetObjectItem(store_coll("dmx_bridge"), b->id);
if (!rec) {
store_unlock();
return false;
}
str_of(rec, "name", name, 64);
const cJSON *ulist = cJSON_GetObjectItem(rec, "universes");
int nu = cJSON_GetArraySize(ulist);
universe_t *unis = calloc(nu ? nu : 1, sizeof(*unis));
int nfx_total = 0;
const cJSON *u;
cJSON_ArrayForEach(u, ulist)
{
nfx_total += cJSON_GetArraySize(cJSON_GetObjectItem(u, "fixtures"));
}
fixture_t **fx = calloc(nfx_total ? nfx_total : 1, sizeof(*fx));
int ui = 0, nfx = 0;
const cJSON *defs = store_coll("dmx_definition");
cJSON_ArrayForEach(u, ulist)
{
universe_t *un = &unis[ui];
str_of(u, "id", un->id, sizeof(un->id));
str_of(u, "name", un->name, sizeof(un->name));
un->number = num_or(cJSON_GetObjectItem(u, "number"), 0);
const cJSON *olist = cJSON_GetObjectItem(u, "outputs");
un->outs = calloc(cJSON_GetArraySize(olist) + 1, sizeof(output_t));
const cJSON *o;
cJSON_ArrayForEach(o, olist)
{
output_t *out = &un->outs[un->nouts++];
char type[16];
str_of(o, "type", type, sizeof(type));
out->type = !strcmp(type, "sacn") ? OUT_SACN
: !strcmp(type, "dmx_serial") ? OUT_SERIAL
: !strcmp(type, "sim") ? OUT_SIM
: OUT_ARTNET;
str_of(o, "host", out->host, sizeof(out->host));
out->port = num_or(cJSON_GetObjectItem(o, "port"), out->type == OUT_SACN ? SACN_PORT : ARTNET_PORT);
out->universe = num_or(cJSON_GetObjectItem(o, "universe"), un->number);
out->enabled = !cJSON_IsFalse(cJSON_GetObjectItem(o, "enabled"));
if (out->type == OUT_SERIAL && out->enabled) {
serial_out_t *s = calloc(1, sizeof(*s));
s->b = b;
str_of(o, "serial_port", s->path, sizeof(s->path));
char mode[16];
str_of(o, "dmx_mode", mode, sizeof(mode));
s->open_dmx = !strcmp(mode, "open_dmx");
pthread_mutex_init(&s->mu, NULL);
out->serial = s;
}
}
const cJSON *flist = cJSON_GetObjectItem(u, "fixtures");
const cJSON *fr;
cJSON_ArrayForEach(fr, flist)
{
fixture_t *f = calloc(1, sizeof(*f));
str_of(fr, "id", f->id, sizeof(f->id));
str_of(fr, "name", f->name, sizeof(f->name));
str_of(fr, "mac", f->hex, sizeof(f->hex));
if (!parse_mac(f->hex, f->mac)) {
free(f);
continue;
}
f->universe = ui;
f->address = num_or(cJSON_GetObjectItem(fr, "address"), 1);
f->address = f->address < 1 ? 1 : f->address > DMX_CHANNELS ? DMX_CHANNELS : f->address;
char def_id[32];
str_of(fr, "definition", def_id, sizeof(def_id));
bool white;
f->nslots = dmx_def_map(cJSON_GetObjectItem(defs, def_id), f->slots, DMX_CHANNELS, &f->pixels, &white);
for (int k = 0; k < f->nslots; k++) {
f->dimmer = f->dimmer || f->slots[k].role == DMX_ROLE_DIMMER;
}
f->bright = 255;
f->in_fd = f->out_fd = -1;
fx[nfx++] = f;
}
ui++;
}
store_unlock();
*unis_out = unis;
*nunis_out = ui;
*fx_out = fx;
*nfx_out = nfx;
return true;
}
// Apply the record: keep the processes of fixtures whose MAC, name and pixel count are unchanged
static void apply_config(bridge_dmx_t *b)
{
char name[64] = "";
universe_t *unis;
int nunis, nfx;
fixture_t **fx;
bool found = load_config(b, name, &unis, &nunis, &fx, &nfx);
for (int i = 0; i < nfx; i++) {
for (int k = 0; k < b->nfx; k++) {
fixture_t *old = b->fx[k];
if (old && old->pid && !memcmp(old->mac, fx[i]->mac, 6) && !strcmp(old->name, fx[i]->name) &&
old->pixels == fx[i]->pixels) {
pthread_mutex_lock(&b->mu);
fx[i]->pid = old->pid;
fx[i]->in_fd = old->in_fd;
fx[i]->out_fd = old->out_fd;
fx[i]->starts = old->starts;
memcpy(fx[i]->px, old->px, sizeof(old->px));
fx[i]->npx = old->npx;
fx[i]->bright = old->bright;
old->pid = 0;
old->in_fd = old->out_fd = -1;
pthread_mutex_unlock(&b->mu);
fx[i]->rbuf = old->rbuf; // a partial message carries over
fx[i]->rlen = old->rlen;
old->rbuf = NULL;
break;
}
}
if (!fx[i]->rbuf) {
fx[i]->rbuf = malloc(MSG_MAX);
}
}
// Swap in the new config under the lock (send and status read it), then stop what is left of the old
pthread_mutex_lock(&b->mu);
universe_t *old_unis = b->unis;
int old_nunis = b->nunis;
fixture_t **old_fx = b->fx;
int old_nfx = b->nfx;
b->unis = unis;
b->nunis = nunis;
b->fx = fx;
b->nfx = nfx;
b->missing = !found;
snprintf(b->name, sizeof(b->name), "%s", name);
pthread_mutex_unlock(&b->mu);
close_inputs(b, old_fx, old_nfx);
for (int k = 0; k < old_nfx; k++) {
fixture_free(b, old_fx[k]);
}
free(old_fx);
free_config(old_unis, old_nunis);
for (int u = 0; u < nunis; u++) {
for (int o = 0; o < unis[u].nouts; o++) {
output_t *out = &unis[u].outs[o];
if (out->serial) {
pthread_create(&out->serial->th, NULL, serial_task, out->serial);
} else if (out->type != OUT_SIM) {
outputs_resolve(b, out);
}
}
}
if (!found) {
set_error(b, "no DMX bridge record %s", b->id);
}
ESP_LOGI(TAG, "%s \"%s\": %d universes, %d fixtures", b->id, b->name, nunis, nfx);
}
/* --------------------------------------------------------------- worker */
static void *worker(void *arg)
{
bridge_dmx_t *b = arg;
apply_config(b);
int64_t next_tick = mono_us();
struct pollfd *pfd = NULL;
int pfd_cap = 0;
while (!b->stop) {
if (b->reload) {
b->reload = false;
apply_config(b);
}
int64_t now = mono_us();
for (int i = 0; i < b->nfx; i++) {
fixture_t *f = b->fx[i];
if (!f->pid && now >= f->restart_at_us) {
fixture_spawn(b, f);
}
}
if (pfd_cap < b->nfx + 1) {
pfd_cap = b->nfx + 1;
pfd = realloc(pfd, pfd_cap * sizeof(*pfd));
}
pfd[0] = (struct pollfd){ b->wake[0], POLLIN, 0 };
for (int i = 0; i < b->nfx; i++) {
pfd[i + 1] = (struct pollfd){ b->fx[i]->out_fd, POLLIN, 0 }; // -1 is skipped by poll
}
now = mono_us();
int wait_ms = next_tick > now ? (int)((next_tick - now + 999) / 1000) : 0;
int r = poll(pfd, b->nfx + 1, wait_ms);
if (r > 0) {
if (pfd[0].revents) {
char drain[16];
while (read(b->wake[0], drain, sizeof(drain)) > 0) {
}
}
for (int i = 0; i < b->nfx; i++) {
fixture_t *f = b->fx[i];
if (f->out_fd >= 0 && (pfd[i + 1].revents & (POLLIN | POLLHUP | POLLERR))) {
if (!fixture_read(b, f)) {
set_error(b, "fixture %s (%s) stopped; starting it again", f->name, f->hex);
fixture_stop(b, f, true);
}
}
}
}
now = mono_us();
if (now >= next_tick) {
send_universes(b);
next_tick += TICK_US;
if (now - next_tick > 4 * TICK_US) {
next_tick = now + TICK_US; // stalled: no burst of frames to catch up
}
}
}
free(pfd);
close_inputs(b, b->fx, b->nfx);
for (int k = 0; k < b->nfx; k++) {
fixture_free(b, b->fx[k]);
}
free(b->fx);
b->fx = NULL;
b->nfx = 0;
free_config(b->unis, b->nunis);
ESP_LOGI(TAG, "%s: stopped", b->id);
if (b->sock >= 0) {
close(b->sock);
}
if (b->wake[0] >= 0) {
close(b->wake[0]);
close(b->wake[1]);
}
pthread_mutex_destroy(&b->mu);
free(b);
return NULL;
}
/* ------------------------------------------------------------------ API */
bridge_dmx_t *bridge_dmx_open(const char *id, bridge_dmx_rx_t rx)
{
signal(SIGPIPE, SIG_IGN); // a fixture that exits must not take the controller with it
bridge_dmx_t *b = calloc(1, sizeof(*b));
if (!b) {
return NULL;
}
snprintf(b->id, sizeof(b->id), "%s", id);
b->rx = rx;
b->sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
if (b->sock >= 0) {
int on = 1;
setsockopt(b->sock, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on));
}
esp_read_mac(b->own_mac, ESP_MAC_WIFI_STA);
memcpy(b->cid, b->own_mac, 6);
memcpy(b->cid + 6, "dmx-bridge", 10);
for (size_t i = 0; i < strlen(id) && i < 6; i++) {
b->cid[10 + i] = (uint8_t)id[i];
}
pthread_mutex_init(&b->mu, NULL);
if (pipe2(b->wake, O_CLOEXEC | O_NONBLOCK) != 0) {
b->wake[0] = b->wake[1] = -1;
}
if (pthread_create(&b->worker, NULL, worker, b) != 0) {
close(b->sock);
free(b);
return NULL;
}
pthread_mutex_lock(&s_reg_mu);
b->next = s_open;
s_open = b;
pthread_mutex_unlock(&s_reg_mu);
return b;
}
// The worker stops the fixtures and frees the bridge: close may be called with the store locked, and the worker
// takes that lock to read the record, so close does not wait for it
void bridge_dmx_close(bridge_dmx_t *b)
{
if (!b) {
return;
}
pthread_mutex_lock(&s_reg_mu);
for (bridge_dmx_t **p = &s_open; *p; p = &(*p)->next) {
if (*p == b) {
*p = b->next;
break;
}
}
pthread_mutex_unlock(&s_reg_mu);
b->stop = true;
if (b->wake[1] >= 0) {
(void)!write(b->wake[1], "x", 1);
}
pthread_detach(b->worker);
}
void bridge_dmx_send(bridge_dmx_t *b, const uint8_t dst[6], const void *data, size_t len)
{
static const uint8_t BCAST[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
if (!b || len > 250) {
return;
}
uint8_t msg[3 + 6 + 250];
msg[0] = 'R';
msg[1] = (uint8_t)(6 + len);
msg[2] = (uint8_t)((6 + len) >> 8);
memcpy(msg + 3, b->own_mac, 6);
memcpy(msg + 9, data, len);
bool bcast = !memcmp(dst, BCAST, 6);
pthread_mutex_lock(&b->mu);
for (int i = 0; i < b->nfx; i++) {
fixture_t *f = b->fx[i];
if (f->in_fd >= 0 && (bcast || !memcmp(dst, f->mac, 6))) {
(void)!write(f->in_fd, msg, 9 + len); // under PIPE_BUF: all of it or nothing
}
}
pthread_mutex_unlock(&b->mu);
}
void bridge_dmx_status(bridge_dmx_t *b, char *out, size_t n)
{
pthread_mutex_lock(&b->mu);
int running = 0;
for (int i = 0; i < b->nfx; i++) {
running += b->fx[i]->pid > 0;
}
cJSON *o = cJSON_CreateObject();
cJSON_AddBoolToObject(o, "linked", !b->missing && b->nfx > 0 && running == b->nfx);
cJSON_AddStringToObject(o, "name", b->name);
cJSON_AddNumberToObject(o, "universes", b->nunis);
cJSON_AddNumberToObject(o, "fixtures", b->nfx);
cJSON_AddNumberToObject(o, "running", running);
cJSON_AddNumberToObject(o, "hz", DMX_REFRESH_HZ);
cJSON_AddNumberToObject(o, "frames", b->frames);
cJSON_AddNumberToObject(o, "packets", b->packets);
cJSON_AddNumberToObject(o, "errors", b->errors);
cJSON_AddItemToObject(o, "last_error", b->last_error[0] ? cJSON_CreateString(b->last_error) : cJSON_CreateNull());
pthread_mutex_unlock(&b->mu);
if (!cJSON_PrintPreallocated(o, out, (int)n, false)) {
snprintf(out, n, "{}");
}
cJSON_Delete(o);
}
void bridge_dmx_reload(const char *id)
{
pthread_mutex_lock(&s_reg_mu);
for (bridge_dmx_t *b = s_open; b; b = b->next) {
if (!strcmp(b->id, id)) {
b->reload = true;
if (b->wake[1] >= 0) {
(void)!write(b->wake[1], "r", 1);
}
}
}
pthread_mutex_unlock(&s_reg_mu);
}
bool bridge_dmx_owns_mac(const uint8_t mac[6], char *addr, size_t n)
{
bool hit = false;
pthread_mutex_lock(&s_reg_mu);
for (bridge_dmx_t *b = s_open; b && !hit; b = b->next) {
pthread_mutex_lock(&b->mu);
for (int i = 0; i < b->nfx && !hit; i++) {
if (!memcmp(b->fx[i]->mac, mac, 6)) {
hit = true;
if (addr) {
snprintf(addr, n, BRIDGE_DMX_PREFIX "%s", b->id);
}
}
}
pthread_mutex_unlock(&b->mu);
}
pthread_mutex_unlock(&s_reg_mu);
return hit;
}