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>
This commit is contained in:
1 parent
35207a868a
commit
edf35e9c71
280 files changed
+24043
-1756
No files matched your search
+2
-2
@@ -2,13 +2,13 @@ if(IDF_TARGET STREQUAL "linux")
|
||||
# Host build for led-simulator (sim-controller/): no Ethernet, Wi-Fi, mic or OTA. The sim
|
||||
# component has app_main and stands in for main.c, mic.c and ota.c.
|
||||
idf_component_register(SRCS "beat.c" "beat_dsp.c" "espnow_tx.c" "bridge.c" "store.c" "api.c" "web.c" "envelope.c" "engine.c" "rel.c" "bench.c" "audio.c"
|
||||
"res_profile.c" "res_misc.c" "res_device.c" "res_group.c" "seqplay.c" "res_bundle.c" "audio_api.c" "patterns.c" "outputs.c" "ws.c" "ws_client.c" "wifi_drv.c" "bridge_serial.c" "auth.c"
|
||||
"res_profile.c" "res_misc.c" "res_device.c" "res_group.c" "seqplay.c" "res_bundle.c" "audio_api.c" "patterns.c" "outputs.c" "dmx_wire.c" "ws.c" "ws_client.c" "wifi_drv.c" "bridge_serial.c" "bridge_dmx.c" "bridge_dmx_serial.c" "res_dmx.c" "auth.c"
|
||||
INCLUDE_DIRS "." "../sim-controller/components/sim/include" "../bridge/main"
|
||||
REQUIRES esp_http_server esp_timer esp_event cjson
|
||||
PRIV_REQUIRES mbedtls lwip esp_app_format)
|
||||
else()
|
||||
idf_component_register(SRCS "main.c" "mic.c" "beat.c" "beat_dsp.c" "espnow_tx.c" "bridge.c" "store.c" "api.c" "web.c" "envelope.c" "engine.c" "rel.c" "bench.c" "audio.c" "ota.c"
|
||||
"res_profile.c" "res_misc.c" "res_device.c" "res_group.c" "seqplay.c" "res_bundle.c" "audio_api.c" "patterns.c" "outputs.c" "ws.c" "ws_client.c" "wifi_drv.c" "auth.c"
|
||||
"res_profile.c" "res_misc.c" "res_device.c" "res_group.c" "seqplay.c" "res_bundle.c" "audio_api.c" "patterns.c" "outputs.c" "dmx_wire.c" "ws.c" "ws_client.c" "wifi_drv.c" "res_dmx.c" "auth.c"
|
||||
INCLUDE_DIRS "." "../bridge/main"
|
||||
REQUIRES esp_eth esp_netif esp_event esp_driver_spi esp_driver_gpio nvs_flash app_update esp_app_format
|
||||
esp_http_server esp_timer esp_driver_i2s esp_wifi esp_rom cjson esp_driver_gpio
|
||||
|
||||
@@ -124,7 +124,7 @@ menu "ESP-NOW config"
|
||||
config ESPNOW_CHANNEL
|
||||
int "Wi-Fi channel shared with the LED drivers"
|
||||
range 1 13
|
||||
default 6
|
||||
default 11
|
||||
|
||||
config BEAT_TX_COPIES
|
||||
int "Copies sent of every beat frame"
|
||||
|
||||
+103
-7
@@ -31,7 +31,7 @@ static const struct {
|
||||
{ "devices", "device" }, { "zones", "zone" }, { "presets", "preset" },
|
||||
{ "profiles", "profile" }, { "palettes", "palette" }, { "patterns", "pattern" },
|
||||
{ "sequences", "sequence" }, { "scenes", "scene" }, { "groups", "group" },
|
||||
{ "outputs", "output" },
|
||||
{ "outputs", "output" }, { "dmx-definitions", "dmx_definition" }, { "dmx-bridges", "dmx_bridge" },
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------- helpers */
|
||||
@@ -228,6 +228,7 @@ static bool route(const char *res, httpd_req_t *req, int n, api_seg_t seg, esp_e
|
||||
{ "profiles", profiles_route }, { "zones", zones_route }, { "presets", presets_route },
|
||||
{ "palettes", palettes_route }, { "sequences", sequences_route }, { "devices", devices_route },
|
||||
{ "patterns", patterns_route }, { "outputs", outputs_route }, { "groups", groups_route },
|
||||
{ "dmx-definitions", dmx_definitions_route }, { "dmx-bridges", dmx_bridges_route },
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(ROUTERS) / sizeof(ROUTERS[0]); i++) {
|
||||
if (!strcmp(ROUTERS[i].res, res)) {
|
||||
@@ -439,9 +440,26 @@ static esp_err_t put_settings(httpd_req_t *req)
|
||||
}
|
||||
|
||||
// The bridges the controller sends its ESP-NOW frames to (USB boards, network boards, the simulator).
|
||||
// GET /settings/bridge: {supported, bridges: [{addr, kind, status}], ports}.
|
||||
// PUT /settings/bridge: {bridges: [addr, ...]} sets the whole list; {addr, channel} sets a board's channel.
|
||||
// GET /settings/bridge: {supported, bridges: [{addr, name, kind, status}], ports}.
|
||||
// PUT /settings/bridge: {bridges: [addr, ...]} sets the whole list; {addr, channel} sets a board's channel;
|
||||
// {addr, name} names a bridge (an empty name clears it).
|
||||
// Both apply at once on the host; a device reads the list at the next restart.
|
||||
// Bridge names are kept in settings "bridge_names", by address. A USB board is kept by its MAC ("usb:<mac>") once it
|
||||
// has answered, so its name survives a change of port.
|
||||
static void bridge_name_key(const cJSON *bridge, char *key, size_t n)
|
||||
{
|
||||
const cJSON *addr = cJSON_GetObjectItem(bridge, "addr");
|
||||
const cJSON *mac = cJSON_GetObjectItem(cJSON_GetObjectItem(bridge, "status"), "mac");
|
||||
snprintf(key, n, "%s", cJSON_IsString(addr) ? addr->valuestring : "");
|
||||
if (cJSON_IsString(mac) && strcmp(mac->valuestring, "00:00:00:00:00:00") != 0 &&
|
||||
(!strncmp(key, "/dev/", 5) || !strncmp(key, "serial:", 7) || !strncmp(key, "usb:", 4))) {
|
||||
unsigned m[6];
|
||||
if (sscanf(mac->valuestring, "%x:%x:%x:%x:%x:%x", &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) == 6) {
|
||||
snprintf(key, n, "usb:%02x%02x%02x%02x%02x%02x", m[0], m[1], m[2], m[3], m[4], m[5]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static esp_err_t bridge_get(httpd_req_t *req)
|
||||
{
|
||||
char links[1536], ports[512];
|
||||
@@ -453,11 +471,31 @@ static esp_err_t bridge_get(httpd_req_t *req)
|
||||
#else
|
||||
cJSON_AddBoolToObject(out, "supported", false);
|
||||
#endif
|
||||
cJSON_AddItemToObject(out, "bridges", cJSON_Parse(links));
|
||||
cJSON *bridges = cJSON_Parse(links);
|
||||
const cJSON *names = cJSON_GetObjectItem(store_settings(), "bridge_names");
|
||||
const cJSON *b;
|
||||
cJSON_ArrayForEach(b, bridges)
|
||||
{
|
||||
char key[BRIDGE_ADDR_MAX];
|
||||
bridge_name_key(b, key, sizeof(key));
|
||||
const cJSON *name = cJSON_GetObjectItem(names, key);
|
||||
cJSON_AddStringToObject((cJSON *)b, "name", cJSON_IsString(name) ? name->valuestring : "");
|
||||
}
|
||||
cJSON_AddItemToObject(out, "bridges", bridges);
|
||||
cJSON_AddItemToObject(out, "ports", cJSON_Parse(ports));
|
||||
return api_json(req, "200 OK", out, true);
|
||||
}
|
||||
|
||||
static void bridge_store(void);
|
||||
|
||||
// bridge.c calls this when a USB board's address became its MAC
|
||||
static void bridge_store_locked(void)
|
||||
{
|
||||
store_lock();
|
||||
bridge_store();
|
||||
store_unlock();
|
||||
}
|
||||
|
||||
// Save the list the running bridges actually have (a bridge that failed to open is not kept)
|
||||
static void bridge_store(void)
|
||||
{
|
||||
@@ -475,6 +513,24 @@ static void bridge_store(void)
|
||||
store_save("settings");
|
||||
}
|
||||
|
||||
void api_bridges_remove(const char *addr)
|
||||
{
|
||||
char addrs[BRIDGE_MAX_LINKS][BRIDGE_ADDR_MAX];
|
||||
size_t n = bridge_list(addrs, BRIDGE_MAX_LINKS), k = 0;
|
||||
bool had = false;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
if (strcmp(addrs[i], addr) != 0) {
|
||||
memmove(addrs[k++], addrs[i], BRIDGE_ADDR_MAX);
|
||||
} else {
|
||||
had = true;
|
||||
}
|
||||
}
|
||||
if (had) {
|
||||
espnow_tx_change_bridges(addrs, k);
|
||||
bridge_store();
|
||||
}
|
||||
}
|
||||
|
||||
static esp_err_t bridge_put(httpd_req_t *req)
|
||||
{
|
||||
#if !CONFIG_IDF_TARGET_LINUX
|
||||
@@ -488,8 +544,9 @@ static esp_err_t bridge_put(httpd_req_t *req)
|
||||
const cJSON *addr = cJSON_GetObjectItem(body, "addr");
|
||||
const cJSON *ch = cJSON_GetObjectItem(body, "channel");
|
||||
const char *bad = NULL;
|
||||
if (!list && !(addr && ch)) {
|
||||
bad = "send bridges (a list), or addr and channel";
|
||||
const cJSON *name = cJSON_GetObjectItem(body, "name");
|
||||
if (!list && !(addr && (ch || name))) {
|
||||
bad = "send bridges (a list), or addr with a channel or a name";
|
||||
} else if (list && !cJSON_IsArray(list)) {
|
||||
bad = "bridges must be a list of addresses";
|
||||
} else if (list && cJSON_GetArraySize(list) > BRIDGE_MAX_LINKS) {
|
||||
@@ -498,12 +555,17 @@ static esp_err_t bridge_put(httpd_req_t *req)
|
||||
bad = "addr must be a board port (/dev/...) or host:port";
|
||||
} else if (ch && !(cJSON_IsNumber(ch) && ch->valueint >= 1 && ch->valueint <= 13)) {
|
||||
bad = "channel must be 1 to 13";
|
||||
} else if (name && !(cJSON_IsString(name) && strlen(name->valuestring) <= 40)) {
|
||||
bad = "name must be text of up to 40 characters";
|
||||
}
|
||||
const cJSON *item = NULL;
|
||||
if (!bad && list) {
|
||||
cJSON_ArrayForEach(item, list) {
|
||||
if (!cJSON_IsString(item) || strlen(item->valuestring) >= BRIDGE_ADDR_MAX) {
|
||||
bad = "each bridge must be a board port (/dev/...), host:port or serial:/dev/...";
|
||||
bad = "each bridge must be a board port (/dev/...), host:port, serial:/dev/... or dmx:<id>";
|
||||
} else if (!strncmp(item->valuestring, "dmx:", 4) &&
|
||||
!cJSON_GetObjectItem(store_coll("dmx_bridge"), item->valuestring + 4)) {
|
||||
bad = "no DMX bridge has that id (create it at /dmx-bridges first)";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -514,10 +576,16 @@ static esp_err_t bridge_put(httpd_req_t *req)
|
||||
if (list) {
|
||||
char addrs[BRIDGE_MAX_LINKS][BRIDGE_ADDR_MAX];
|
||||
size_t n = 0;
|
||||
bool has_browser = false;
|
||||
cJSON_ArrayForEach(item, list) {
|
||||
snprintf(addrs[n], BRIDGE_ADDR_MAX, "%s", item->valuestring);
|
||||
has_browser = has_browser || !strcmp(item->valuestring, BRIDGE_BROWSER);
|
||||
n++;
|
||||
}
|
||||
// The rig page's own bridge cannot be removed: keep it when it runs and the list leaves it out
|
||||
if (!has_browser && bridge_has_browser() && n < BRIDGE_MAX_LINKS) {
|
||||
snprintf(addrs[n++], BRIDGE_ADDR_MAX, "%s", BRIDGE_BROWSER);
|
||||
}
|
||||
esp_err_t err = espnow_tx_change_bridges(addrs, n);
|
||||
bridge_store();
|
||||
if (err != ESP_OK) {
|
||||
@@ -525,6 +593,31 @@ static esp_err_t bridge_put(httpd_req_t *req)
|
||||
return api_error(req, "400 Bad Request", "one of the bridges could not be opened (the others are running)");
|
||||
}
|
||||
}
|
||||
if (addr && name) {
|
||||
char links[1536];
|
||||
bridge_status_json(links, sizeof(links));
|
||||
cJSON *all = cJSON_Parse(links);
|
||||
char key[BRIDGE_ADDR_MAX];
|
||||
snprintf(key, sizeof(key), "%s", addr->valuestring);
|
||||
const cJSON *b;
|
||||
cJSON_ArrayForEach(b, all)
|
||||
{
|
||||
const cJSON *a = cJSON_GetObjectItem(b, "addr");
|
||||
if (cJSON_IsString(a) && !strcmp(a->valuestring, addr->valuestring)) {
|
||||
bridge_name_key(b, key, sizeof(key));
|
||||
}
|
||||
}
|
||||
cJSON_Delete(all);
|
||||
cJSON *names = cJSON_GetObjectItem(store_settings(), "bridge_names");
|
||||
if (!cJSON_IsObject(names)) {
|
||||
names = cJSON_AddObjectToObject(store_settings(), "bridge_names");
|
||||
}
|
||||
cJSON_DeleteItemFromObject(names, key);
|
||||
if (name->valuestring[0]) {
|
||||
cJSON_AddStringToObject(names, key, name->valuestring);
|
||||
}
|
||||
store_save("settings");
|
||||
}
|
||||
if (addr && ch) {
|
||||
// A board just switched in answers its INFO a moment later: wait up to 3 s for it before giving up
|
||||
esp_err_t err = ESP_OK;
|
||||
@@ -681,6 +774,7 @@ LOCKED(test_handler)
|
||||
|
||||
esp_err_t api_register(httpd_handle_t server)
|
||||
{
|
||||
bridge_set_renamed_cb(bridge_store_locked);
|
||||
ESP_ERROR_CHECK(auth_init());
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(auth_register(server));
|
||||
store_lock();
|
||||
@@ -689,10 +783,12 @@ esp_err_t api_register(httpd_handle_t server)
|
||||
api_migrate_sequences();
|
||||
api_migrate_zones();
|
||||
api_migrate_groups();
|
||||
dmx_seed_definitions();
|
||||
store_unlock();
|
||||
static const char *const ROUTES[] = {
|
||||
"/devices*", "/zones*", "/presets*", "/profiles*", "/palettes*",
|
||||
"/patterns*", "/sequences*", "/scenes*", "/groups*", "/outputs*",
|
||||
"/dmx-definitions*", "/dmx-bridges*",
|
||||
};
|
||||
static const httpd_method_t METHODS[] = { HTTP_GET, HTTP_POST, HTTP_PUT, HTTP_DELETE };
|
||||
for (size_t r = 0; r < sizeof(ROUTES) / sizeof(ROUTES[0]); r++) {
|
||||
|
||||
@@ -78,3 +78,9 @@ bool groups_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret);
|
||||
bool devices_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret);
|
||||
bool patterns_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret);
|
||||
bool outputs_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret);
|
||||
bool dmx_definitions_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret);
|
||||
bool dmx_bridges_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret);
|
||||
// The rig sim's two DMX definitions, when there are none (at boot)
|
||||
void dmx_seed_definitions(void);
|
||||
// Take addr off the running bridges and the saved list (a DMX bridge that was deleted). Store locked.
|
||||
void api_bridges_remove(const char *addr);
|
||||
@@ -600,6 +600,8 @@ auth_need_t auth_classify(const char *uri, int method)
|
||||
area = "patterns";
|
||||
} else if (!strcmp(s0, "sim")) {
|
||||
area = "sim";
|
||||
} else if (!strcmp(s0, "dmx-bridges") || !strcmp(s0, "dmx-definitions")) {
|
||||
area = "settings"; // DMX bridges are set up with the other bridges
|
||||
} else if (!strcmp(s0, "settings") || !strcmp(s0, "ota") || !strcmp(s0, "reboot") || !strcmp(s0, "test")) {
|
||||
area = "settings";
|
||||
} else if (!strcmp(s0, "api") && n > 1 && !strcmp(s1, "audio")) {
|
||||
|
||||
+85
-6
@@ -13,9 +13,11 @@
|
||||
#include "sdkconfig.h"
|
||||
#include "bridge_proto.h"
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
#include "bridge_dmx.h"
|
||||
#include "bridge_serial.h"
|
||||
#else
|
||||
typedef struct bridge_serial bridge_serial_t; // serial boards are linux-only; the device never opens one
|
||||
typedef struct bridge_dmx bridge_dmx_t; // so are DMX bridges
|
||||
#endif
|
||||
|
||||
static const char *TAG = "bridge";
|
||||
@@ -25,6 +27,8 @@ typedef struct {
|
||||
bool used;
|
||||
bool serial; // a USB board (bridge_serial), else UDP
|
||||
bool browser; // the rig page of the host build (sim_rig.c), over its WebSocket
|
||||
bool dmx; // a DMX bridge "dmx:<id>" (bridge_dmx.c): its fixtures are drivers of their own
|
||||
bridge_dmx_t *dmx_b;
|
||||
char addr[BRIDGE_ADDR_MAX]; // as the settings store it
|
||||
bridge_serial_t *board; // serial: the board (linux)
|
||||
int sock; // UDP data socket (port), -1 when closed
|
||||
@@ -41,6 +45,7 @@ static link_t s_links[BRIDGE_MAX_LINKS];
|
||||
static SemaphoreHandle_t s_lock;
|
||||
static bridge_rx_cb_t s_cb;
|
||||
static bridge_audio_cb_t s_audio_cb;
|
||||
static void (*s_renamed_cb)(void);
|
||||
static int s_mic_slot = -1; // the UDP board recording (-1: none)
|
||||
|
||||
// Frames heard by more than one bridge arrive once: a frame seen again within DEDUPE_MS is dropped
|
||||
@@ -60,7 +65,7 @@ static int s_n_browser_macs;
|
||||
|
||||
static bool is_serial_addr(const char *addr)
|
||||
{
|
||||
return strncmp(addr, "/dev/", 5) == 0 || strncmp(addr, "serial:", 7) == 0;
|
||||
return strncmp(addr, "/dev/", 5) == 0 || strncmp(addr, "serial:", 7) == 0 || strncmp(addr, "usb:", 4) == 0;
|
||||
}
|
||||
|
||||
static bool is_browser_addr(const char *addr)
|
||||
@@ -68,6 +73,11 @@ static bool is_browser_addr(const char *addr)
|
||||
return strcmp(addr, BRIDGE_BROWSER) == 0;
|
||||
}
|
||||
|
||||
static bool is_dmx_addr(const char *addr)
|
||||
{
|
||||
return strncmp(addr, "dmx:", 4) == 0;
|
||||
}
|
||||
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
// The rig page's link (sim-controller/components/sim/sim_rig.c): dst_mac(6) + packet to the page, if it is open
|
||||
bool sim_rig_tx(const uint8_t *frame, size_t len);
|
||||
@@ -187,6 +197,21 @@ static void keepalive_task(void *arg)
|
||||
}
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
int64_t now = now_ms();
|
||||
bool renamed = false;
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
// A USB board that has answered is known by its MAC from then on: its port can change (it is plugged into
|
||||
// another one, or the numbering shifts) and it is found again
|
||||
for (int i = 0; i < BRIDGE_MAX_LINKS; i++) {
|
||||
link_t *l = &s_links[i];
|
||||
uint8_t mac[6];
|
||||
if (l->used && l->serial && strncmp(l->addr, "usb:", 4) != 0 && bridge_serial_mac(l->board, mac)) {
|
||||
bridge_serial_follow_mac(l->board);
|
||||
snprintf(l->addr, sizeof(l->addr), "usb:%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4],
|
||||
mac[5]);
|
||||
renamed = true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
for (int i = 0; i < BRIDGE_MAX_LINKS; i++) {
|
||||
link_t *l = &s_links[i];
|
||||
if (!l->used || l->serial || l->ctl < 0) {
|
||||
@@ -205,6 +230,9 @@ static void keepalive_task(void *arg)
|
||||
}
|
||||
}
|
||||
xSemaphoreGive(s_lock);
|
||||
if (renamed && s_renamed_cb) {
|
||||
s_renamed_cb(); // outside the lock: it saves the list, which takes the store lock first
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,7 +300,25 @@ static esp_err_t activate(const char *addr)
|
||||
}
|
||||
link_t *l = &s_links[slot];
|
||||
l->browser = false;
|
||||
if (is_browser_addr(addr)) {
|
||||
l->dmx = false;
|
||||
if (is_dmx_addr(addr)) {
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
if (!addr[4]) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
l->dmx_b = bridge_dmx_open(addr + 4, deliver);
|
||||
if (!l->dmx_b) {
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
l->dmx = true;
|
||||
l->serial = false;
|
||||
l->sock = -1;
|
||||
l->ctl = -1;
|
||||
ESP_LOGW(TAG, "ESP-NOW frames go to the fixtures of DMX bridge %s", addr + 4);
|
||||
#else
|
||||
return ESP_ERR_NOT_SUPPORTED;
|
||||
#endif
|
||||
} else if (is_browser_addr(addr)) {
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
l->browser = true;
|
||||
l->serial = false;
|
||||
@@ -284,7 +330,7 @@ static esp_err_t activate(const char *addr)
|
||||
#endif
|
||||
} else if (is_serial_addr(addr)) {
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
const char *dev = strncmp(addr, "serial:", 7) == 0 ? addr + 7 : addr;
|
||||
const char *dev = strncmp(addr, "serial:", 7) == 0 ? addr + 7 : addr; // "usb:<mac>" goes as it is
|
||||
l->board = bridge_serial_open(dev, deliver);
|
||||
if (!l->board) {
|
||||
return ESP_FAIL;
|
||||
@@ -336,6 +382,11 @@ static void deactivate(int i)
|
||||
if (l->serial) {
|
||||
bridge_serial_close(l->board);
|
||||
}
|
||||
if (l->dmx) {
|
||||
bridge_dmx_close(l->dmx_b);
|
||||
l->dmx_b = NULL;
|
||||
l->dmx = false;
|
||||
}
|
||||
#endif
|
||||
if (!l->serial && l->sock >= 0) {
|
||||
close(l->sock);
|
||||
@@ -397,6 +448,11 @@ esp_err_t bridge_set_all(const char addrs[][BRIDGE_ADDR_MAX], size_t n, bridge_r
|
||||
return first;
|
||||
}
|
||||
|
||||
void bridge_set_renamed_cb(void (*cb)(void))
|
||||
{
|
||||
s_renamed_cb = cb;
|
||||
}
|
||||
|
||||
bool bridge_active(void)
|
||||
{
|
||||
for (int i = 0; i < BRIDGE_MAX_LINKS; i++) {
|
||||
@@ -438,7 +494,12 @@ esp_err_t bridge_send(const uint8_t *dst_mac, const void *data, size_t len)
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
if (l->browser) {
|
||||
if (l->dmx) {
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
bridge_dmx_send(l->dmx_b, dst_mac, data, len);
|
||||
l->tx++;
|
||||
#endif
|
||||
} else if (l->browser) {
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
if (sim_rig_tx(buf, 6 + len)) { // no page open: the frame is lost, as on air
|
||||
l->tx++;
|
||||
@@ -472,7 +533,13 @@ size_t bridge_status_json(char *out, size_t n)
|
||||
continue;
|
||||
}
|
||||
char body[400];
|
||||
if (l->browser) {
|
||||
if (l->dmx) {
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
bridge_dmx_status(l->dmx_b, body, sizeof(body));
|
||||
#else
|
||||
snprintf(body, sizeof(body), "{}");
|
||||
#endif
|
||||
} else if (l->browser) {
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
snprintf(body, sizeof(body), "{\"page\":%s,\"tx\":%lu,\"rx\":%lu}",
|
||||
sim_rig_page_open() ? "true" : "false", (unsigned long)l->tx, (unsigned long)l->rx);
|
||||
@@ -498,7 +565,7 @@ size_t bridge_status_json(char *out, size_t n)
|
||||
(unsigned long)l->tx, (unsigned long)l->rx, (unsigned long)l->audio);
|
||||
}
|
||||
int w = snprintf(out + used, n - used, "%s{\"addr\":\"%s\",\"kind\":\"%s\",\"status\":%s}",
|
||||
first ? "" : ",", l->addr, l->browser ? "browser" : (l->serial ? "serial" : "udp"), body);
|
||||
first ? "" : ",", l->addr, l->dmx ? "dmx" : l->browser ? "browser" : (l->serial ? "serial" : "udp"), body);
|
||||
if (w < 0 || (size_t)w >= n - used) {
|
||||
break;
|
||||
}
|
||||
@@ -671,3 +738,15 @@ esp_err_t bridge_mic(bool on)
|
||||
#endif
|
||||
return err;
|
||||
}
|
||||
|
||||
bool bridge_mac_is_dmx(const uint8_t mac[6], char *addr, size_t n)
|
||||
{
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
return bridge_dmx_owns_mac(mac, addr, n);
|
||||
#else
|
||||
(void)mac;
|
||||
(void)addr;
|
||||
(void)n;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
@@ -6,6 +6,10 @@
|
||||
// "host:port" UDP, e.g. led-simulator (bridge_sim.py), or a network bridge board.
|
||||
// Down: dst_mac(6) + packet. Up: src_mac(6) + packet.
|
||||
// "/dev/ttyACM1" serial, the USB ESP-NOW bridge board in bridge/ (linux target only), or "serial:/dev/...".
|
||||
// "usb:aabbccddeeff" a USB board by its MAC, wherever its port is (linux). A board added by port becomes this
|
||||
// once it answers; the list is saved again then (bridge_set_renamed_cb).
|
||||
// "dmx:<id>" a DMX bridge (bridge_dmx.h, linux only): the "dmx_bridge" record id's fixtures, each a
|
||||
// led-driver of its own, sent as Art-Net, sACN or USB-DMX at 40 Hz.
|
||||
// "browser" the rig page the host build serves at /sim/ (linux target only): the simulated drivers
|
||||
// run in the browser and get the frames over the page's WebSocket (sim_rig.c).
|
||||
// While one runs, nothing goes out over the air.
|
||||
@@ -29,11 +33,15 @@ typedef void (*bridge_audio_cb_t)(const int16_t *pcm, size_t n);
|
||||
// opened, and frames received from any of them go to cb. Returns the first error, if any; the bridges that
|
||||
// could open stay up.
|
||||
esp_err_t bridge_set_all(const char addrs[][BRIDGE_ADDR_MAX], size_t n, bridge_rx_cb_t cb);
|
||||
// Called when a bridge's address changed by itself (a USB board became "usb:<mac>"): save the list
|
||||
void bridge_set_renamed_cb(void (*cb)(void));
|
||||
bool bridge_active(void);
|
||||
// A frame the rig page's drivers sent: src_mac(6) + packet (linux; sim_rig.c). Dropped unless "browser" runs.
|
||||
void bridge_browser_rx(const uint8_t *frame, int len);
|
||||
// The driver with this MAC was heard on the browser bridge since start: a simulated driver of the rig page
|
||||
bool bridge_mac_is_browser(const uint8_t mac[6]);
|
||||
// The driver with this MAC is a fixture of a running DMX bridge; that bridge's address ("dmx:<id>") in addr
|
||||
bool bridge_mac_is_dmx(const uint8_t mac[6], char *addr, size_t n);
|
||||
// The "browser" bridge is running
|
||||
bool bridge_has_browser(void);
|
||||
// Send to every running bridge
|
||||
|
||||
@@ -0,0 +1,970 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
|
||||
// DMX bridge (linux host build): the bridge address "dmx:<id>" names a "dmx_bridge" record. Each of its fixtures
|
||||
// is a led-driver of its own, a led-fixture process (fixture-driver/) with the fixture's MAC: frames the
|
||||
// controller sends to that MAC (or broadcasts) go to the process, and what the process sends comes back as frames
|
||||
// from that MAC, so the fixture registers, joins groups and plays presets like any driver. 40 times a second the
|
||||
// bridge turns every fixture's pixels into its DMX channels (from the fixture's definition), and sends each
|
||||
// universe's 512 channels to the universe's outputs: Art-Net, sACN, or a USB-DMX adapter (Enttec DMX USB Pro or
|
||||
// Open DMX).
|
||||
//
|
||||
// The record:
|
||||
// {name, universes: [{id, name, number,
|
||||
// outputs: [{type: artnet|sacn|dmx_serial, host, port, universe, serial_port, dmx_mode, enabled}],
|
||||
// fixtures: [{id, name, mac, definition, address}]}]}
|
||||
// and a definition ("dmx_definition"): {name, channels: [names], defaults: {name: value}}.
|
||||
// Channel names pick what each slot gets: Red/Green/Blue/White[ n] the fixture's pixel n (numbered groups in
|
||||
// order; White takes the part of the colour common to red, green and blue), Dimmer (or Intensity, Master Dimmer,
|
||||
// Center Brightness) 255, Strobe (or Shutter, Center Strobe) 0, open. Any other slot holds its default.
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define BRIDGE_DMX_PREFIX "dmx:"
|
||||
#define DMX_REFRESH_HZ 40
|
||||
|
||||
typedef struct bridge_dmx bridge_dmx_t;
|
||||
typedef void (*bridge_dmx_rx_t)(const uint8_t *src_mac, const uint8_t *data, int len);
|
||||
|
||||
// Start the bridge of record id: its fixtures and outputs come up in the bridge's own thread, so this does not
|
||||
// take the store lock. NULL when out of memory.
|
||||
bridge_dmx_t *bridge_dmx_open(const char *id, bridge_dmx_rx_t rx);
|
||||
// Stop the fixtures and outputs, and free the bridge
|
||||
void bridge_dmx_close(bridge_dmx_t *b);
|
||||
// A frame for dst (broadcast: every fixture). Lost when the fixture is not running, as on air.
|
||||
void bridge_dmx_send(bridge_dmx_t *b, const uint8_t dst[6], const void *data, size_t len);
|
||||
// {"linked", "name", "universes", "fixtures", "running", "hz", "frames", "packets", "errors", "last_error"}
|
||||
void bridge_dmx_status(bridge_dmx_t *b, char *out, size_t n);
|
||||
// The record changed (or was deleted): the running bridge of that id reads it again. Fixtures whose MAC, name and
|
||||
// pixel count are the same keep running.
|
||||
void bridge_dmx_reload(const char *id);
|
||||
// Is mac a fixture of a running DMX bridge? Its address ("dmx:<id>") in addr when it is.
|
||||
bool bridge_dmx_owns_mac(const uint8_t mac[6], char *addr, size_t n);
|
||||
@@ -0,0 +1,97 @@
|
||||
// USB-DMX adapters for the DMX bridge (bridge_dmx.c), linux only:
|
||||
// Enttec DMX USB Pro: the widget's "Output Only Send DMX" message (label 6) with start code 0 and 512 channels.
|
||||
// Open DMX (an FTDI cable with no processor): the DMX line itself, 250000 baud 8N2, a break and mark-after-break,
|
||||
// then start code 0 and 512 channels.
|
||||
// The kernel's termios2 sets 250000 baud exactly; its header clashes with glibc's <termios.h>, so this file has
|
||||
// only the kernel's.
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <asm/ioctls.h>
|
||||
#include <asm/termbits.h>
|
||||
#include "dmx_wire.h"
|
||||
|
||||
int ioctl(int fd, unsigned long request, ...);
|
||||
|
||||
int dmx_serial_open(const char *path, bool open_dmx, char *err, size_t elen)
|
||||
{
|
||||
int fd = open(path, O_RDWR | O_NOCTTY | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
snprintf(err, elen, "cannot open %s: %s", path, strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
struct termios2 t;
|
||||
if (ioctl(fd, TCGETS2, &t) != 0) {
|
||||
snprintf(err, elen, "%s is not a serial port: %s", path, strerror(errno));
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
// Raw: no echo, no line discipline, no flow control
|
||||
t.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXOFF | IXANY);
|
||||
t.c_oflag &= ~OPOST;
|
||||
t.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
|
||||
t.c_cflag &= ~(CSIZE | PARENB | CBAUD | CRTSCTS);
|
||||
t.c_cflag |= CS8 | CLOCAL | CREAD | BOTHER;
|
||||
if (open_dmx) {
|
||||
t.c_cflag |= CSTOPB; // 8N2
|
||||
} else {
|
||||
t.c_cflag &= ~CSTOPB;
|
||||
}
|
||||
unsigned baud = open_dmx ? 250000 : 57600; // the Pro is USB: its rate does not matter
|
||||
t.c_ispeed = t.c_ospeed = baud;
|
||||
t.c_cc[VMIN] = 0;
|
||||
t.c_cc[VTIME] = 0;
|
||||
if (ioctl(fd, TCSETS2, &t) != 0) {
|
||||
snprintf(err, elen, "cannot set up %s: %s", path, strerror(errno));
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
return fd;
|
||||
}
|
||||
|
||||
static bool write_all(int fd, const uint8_t *p, size_t n)
|
||||
{
|
||||
while (n) {
|
||||
ssize_t w = write(fd, p, n);
|
||||
if (w < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
p += w;
|
||||
n -= (size_t)w;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool dmx_serial_write(int fd, bool open_dmx, const uint8_t data[DMX_CHANNELS])
|
||||
{
|
||||
uint8_t frame[5 + 1 + DMX_CHANNELS + 1];
|
||||
if (!open_dmx) {
|
||||
size_t len = 1 + DMX_CHANNELS;
|
||||
frame[0] = 0x7E;
|
||||
frame[1] = 6;
|
||||
frame[2] = (uint8_t)len;
|
||||
frame[3] = (uint8_t)(len >> 8);
|
||||
frame[4] = 0; // start code
|
||||
memcpy(frame + 5, data, DMX_CHANNELS);
|
||||
frame[5 + DMX_CHANNELS] = 0xE7;
|
||||
return write_all(fd, frame, 6 + DMX_CHANNELS);
|
||||
}
|
||||
ioctl(fd, TCSBRK, 1); // wait for the last frame to leave before the break
|
||||
if (ioctl(fd, TIOCSBRK) != 0) {
|
||||
return false;
|
||||
}
|
||||
usleep(110); // break: at least 88 us
|
||||
ioctl(fd, TIOCCBRK);
|
||||
usleep(16); // mark after break: at least 8 us
|
||||
frame[0] = 0;
|
||||
memcpy(frame + 1, data, DMX_CHANNELS);
|
||||
return write_all(fd, frame, 1 + DMX_CHANNELS);
|
||||
}
|
||||
+155
-5
@@ -29,7 +29,9 @@ typedef struct {
|
||||
} tx_frame_t;
|
||||
|
||||
struct bridge_serial {
|
||||
char dev[80];
|
||||
char dev[80]; // the port; empty while a board known by MAC has not been found yet
|
||||
bool by_mac; // follow the board by its MAC: when its port goes away, find it on another
|
||||
uint8_t want_mac[6];
|
||||
bool used; // a slot holds a board (closed boards keep their slot and tasks)
|
||||
bool active; // the link task keeps the port open while this is set
|
||||
bridge_rx_cb_t cb;
|
||||
@@ -59,7 +61,7 @@ static uint32_t get_u32(const uint8_t *p)
|
||||
|
||||
static bool open_port(bridge_serial_t *b)
|
||||
{
|
||||
int fd = open(b->dev, O_RDWR | O_NOCTTY);
|
||||
int fd = open(b->dev, O_RDWR | O_NOCTTY | O_CLOEXEC); // processes the controller starts must not keep the board open
|
||||
if (fd < 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -176,6 +178,92 @@ static void handle_frame(bridge_serial_t *b, const uint8_t *msg, size_t len)
|
||||
}
|
||||
}
|
||||
|
||||
// Is a board on this port in use by a board slot other than skip?
|
||||
static bool port_taken(const char *path, const bridge_serial_t *skip)
|
||||
{
|
||||
for (int i = 0; i < MAX_BOARDS; i++) {
|
||||
const bridge_serial_t *o = &s_boards[i];
|
||||
if (o != skip && o->used && o->fd >= 0 && strcmp(o->dev, path) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Open path for a moment and ask the board for its INFO. True with its MAC if one answers.
|
||||
static bool probe_mac(const char *path, uint8_t mac[6])
|
||||
{
|
||||
int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
return false;
|
||||
}
|
||||
struct termios t;
|
||||
if (tcgetattr(fd, &t) == 0) {
|
||||
cfmakeraw(&t);
|
||||
cfsetispeed(&t, B921600);
|
||||
cfsetospeed(&t, B921600);
|
||||
t.c_cflag |= CLOCAL | CREAD;
|
||||
tcsetattr(fd, TCSANOW, &t);
|
||||
}
|
||||
tcflush(fd, TCIOFLUSH);
|
||||
uint8_t hello[BRIDGE_ENC_MAX];
|
||||
size_t hn = bridge_encode(hello, sizeof(hello), BRIDGE_MSG_HELLO, NULL, 0);
|
||||
bridge_decoder_t dec;
|
||||
memset(&dec, 0, sizeof(dec));
|
||||
bool found = false;
|
||||
for (int tick = 0; tick < 75 && !found; tick++) { // 1.5 s, HELLO every 0.5 s
|
||||
if (tick % 25 == 0 && hn) {
|
||||
ssize_t w = write(fd, hello, hn);
|
||||
(void)w;
|
||||
}
|
||||
uint8_t buf[128];
|
||||
ssize_t n = read(fd, buf, sizeof(buf));
|
||||
for (ssize_t i = 0; i < n && !found; i++) {
|
||||
if (bridge_decode_feed(&dec, buf[i]) && dec.frame_len >= 8 && dec.buf[0] == BRIDGE_MSG_INFO &&
|
||||
dec.buf[1] == BRIDGE_PROTO_VERSION) {
|
||||
memcpy(mac, dec.buf + 2, 6);
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
vTaskDelay(pdMS_TO_TICKS(20));
|
||||
}
|
||||
}
|
||||
close(fd);
|
||||
return found;
|
||||
}
|
||||
|
||||
// A board followed by MAC lost its port: look for it on the other serial ports. Sets b->dev when found.
|
||||
static bool find_board(bridge_serial_t *b)
|
||||
{
|
||||
static const char *const pats[] = { "/dev/ttyACM*", "/dev/ttyUSB*", "/dev/led-bridge" };
|
||||
glob_t g;
|
||||
memset(&g, 0, sizeof(g));
|
||||
for (size_t i = 0; i < sizeof(pats) / sizeof(pats[0]); i++) {
|
||||
glob(pats[i], i ? GLOB_APPEND : 0, NULL, &g);
|
||||
}
|
||||
bool found = false;
|
||||
for (size_t i = 0; i < g.gl_pathc && !found; i++) {
|
||||
const char *path = g.gl_pathv[i];
|
||||
uint8_t mac[6];
|
||||
if (strlen(path) >= sizeof(b->dev) || port_taken(path, b)) {
|
||||
continue;
|
||||
}
|
||||
if (probe_mac(path, mac) && memcmp(mac, b->want_mac, 6) == 0) {
|
||||
if (strcmp(b->dev, path) != 0) {
|
||||
ESP_LOGW(TAG, "bridge board %02x:%02x:%02x:%02x:%02x:%02x is now on %s", mac[0], mac[1], mac[2], mac[3],
|
||||
mac[4], mac[5], path);
|
||||
}
|
||||
xSemaphoreTake(b->lock, portMAX_DELAY);
|
||||
snprintf(b->dev, sizeof(b->dev), "%s", path);
|
||||
xSemaphoreGive(b->lock);
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
globfree(&g);
|
||||
return found;
|
||||
}
|
||||
|
||||
static void link_task(void *arg)
|
||||
{
|
||||
bridge_serial_t *b = arg;
|
||||
@@ -185,6 +273,15 @@ static void link_task(void *arg)
|
||||
memset(&dec, 0, sizeof(dec));
|
||||
for (;;) {
|
||||
if (b->fd < 0) {
|
||||
if (b->by_mac && b->active && !find_board(b)) {
|
||||
if (!b->warned) {
|
||||
ESP_LOGW(TAG, "waiting for the bridge board %02x:%02x:%02x:%02x:%02x:%02x", b->want_mac[0],
|
||||
b->want_mac[1], b->want_mac[2], b->want_mac[3], b->want_mac[4], b->want_mac[5]);
|
||||
b->warned = true;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||
continue;
|
||||
}
|
||||
xSemaphoreTake(b->lock, portMAX_DELAY);
|
||||
bool ok = b->active && open_port(b);
|
||||
if (ok) {
|
||||
@@ -233,14 +330,45 @@ static void link_task(void *arg)
|
||||
}
|
||||
}
|
||||
|
||||
// "usb:aabbccddeeff" (colons allowed): a board known by its MAC
|
||||
static bool parse_usb_mac(const char *s, uint8_t mac[6])
|
||||
{
|
||||
if (strncmp(s, "usb:", 4) != 0) {
|
||||
return false;
|
||||
}
|
||||
int n = 0;
|
||||
for (const char *c = s + 4; *c && n < 12; c++) {
|
||||
if (*c == ':') {
|
||||
continue;
|
||||
}
|
||||
int v = (*c >= '0' && *c <= '9') ? *c - '0' : (*c >= 'a' && *c <= 'f') ? *c - 'a' + 10
|
||||
: (*c >= 'A' && *c <= 'F') ? *c - 'A' + 10 : -1;
|
||||
if (v < 0) {
|
||||
return false;
|
||||
}
|
||||
mac[n / 2] = (uint8_t)((n % 2 ? mac[n / 2] << 4 : 0) | v);
|
||||
n++;
|
||||
}
|
||||
return n == 12;
|
||||
}
|
||||
|
||||
bridge_serial_t *bridge_serial_open(const char *dev, bridge_rx_cb_t cb)
|
||||
{
|
||||
if (!dev || !dev[0] || strlen(dev) >= sizeof(((bridge_serial_t *)0)->dev)) {
|
||||
return NULL;
|
||||
}
|
||||
uint8_t want[6];
|
||||
bool by_mac = parse_usb_mac(dev, want);
|
||||
if (strncmp(dev, "usb:", 4) == 0 && !by_mac) {
|
||||
return NULL;
|
||||
}
|
||||
bridge_serial_t *b = NULL;
|
||||
for (int i = 0; i < MAX_BOARDS; i++) {
|
||||
if (s_boards[i].used && strcmp(s_boards[i].dev, dev) == 0) {
|
||||
if (!s_boards[i].used) {
|
||||
continue;
|
||||
}
|
||||
if (by_mac ? (s_boards[i].by_mac && memcmp(s_boards[i].want_mac, want, 6) == 0)
|
||||
: strcmp(s_boards[i].dev, dev) == 0) {
|
||||
b = &s_boards[i];
|
||||
break;
|
||||
}
|
||||
@@ -255,7 +383,12 @@ bridge_serial_t *bridge_serial_open(const char *dev, bridge_rx_cb_t cb)
|
||||
return NULL;
|
||||
}
|
||||
memset(b, 0, sizeof(*b));
|
||||
snprintf(b->dev, sizeof(b->dev), "%s", dev);
|
||||
if (by_mac) {
|
||||
b->by_mac = true;
|
||||
memcpy(b->want_mac, want, 6);
|
||||
} else {
|
||||
snprintf(b->dev, sizeof(b->dev), "%s", dev);
|
||||
}
|
||||
b->fd = -1;
|
||||
b->lock = xSemaphoreCreateMutex();
|
||||
b->txq = xQueueCreate(TX_QUEUE_LEN, sizeof(tx_frame_t));
|
||||
@@ -270,7 +403,7 @@ bridge_serial_t *bridge_serial_open(const char *dev, bridge_rx_cb_t cb)
|
||||
b->cb = cb;
|
||||
b->active = true;
|
||||
xSemaphoreGive(b->lock);
|
||||
ESP_LOGW(TAG, "ESP-NOW frames go to the bridge board on %s, not the radio", dev);
|
||||
ESP_LOGW(TAG, "ESP-NOW frames go to the bridge board %s, not the radio", dev);
|
||||
return b;
|
||||
}
|
||||
|
||||
@@ -290,6 +423,23 @@ void bridge_serial_close(bridge_serial_t *b)
|
||||
xSemaphoreGive(b->lock);
|
||||
}
|
||||
|
||||
bool bridge_serial_mac(bridge_serial_t *b, uint8_t mac[6])
|
||||
{
|
||||
if (!b || !b->have_info) {
|
||||
return false;
|
||||
}
|
||||
memcpy(mac, b->mac, 6);
|
||||
return true;
|
||||
}
|
||||
|
||||
void bridge_serial_follow_mac(bridge_serial_t *b)
|
||||
{
|
||||
if (b && b->have_info) {
|
||||
memcpy(b->want_mac, b->mac, 6);
|
||||
b->by_mac = true;
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t bridge_serial_send(bridge_serial_t *b, const uint8_t *dst_mac, const void *data, size_t len)
|
||||
{
|
||||
if (!b || !b->active) {
|
||||
|
||||
@@ -11,10 +11,17 @@
|
||||
|
||||
typedef struct bridge_serial bridge_serial_t;
|
||||
|
||||
// Open a board on dev (e.g. /dev/ttyACM1), or reopen it if it was closed. The port may come and go: its
|
||||
// Open a board on dev (e.g. /dev/ttyACM1), or "usb:aabbccddeeff" for the board with that MAC wherever its port is,
|
||||
// or reopen it if it was closed. The port may come and go: its
|
||||
// link task keeps reopening it, so a missing board is not an error. Frames from it go to cb.
|
||||
bridge_serial_t *bridge_serial_open(const char *dev, bridge_rx_cb_t cb);
|
||||
|
||||
// The board's MAC, once it has answered (false before)
|
||||
bool bridge_serial_mac(bridge_serial_t *b, uint8_t mac[6]);
|
||||
|
||||
// From now on follow this board by its MAC: when its port goes away, look for it on the other ports
|
||||
void bridge_serial_follow_mac(bridge_serial_t *b);
|
||||
|
||||
// Stop using the board: its port closes and stays closed until bridge_serial_open(dev) again.
|
||||
void bridge_serial_close(bridge_serial_t *b);
|
||||
|
||||
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
#include "dmx_wire.h"
|
||||
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
|
||||
static void put16(uint8_t *p, unsigned v)
|
||||
{
|
||||
p[0] = v >> 8;
|
||||
p[1] = v;
|
||||
}
|
||||
|
||||
size_t dmx_artnet_packet(uint8_t *pkt, uint8_t seq, int uni, const uint8_t *data, size_t n)
|
||||
{
|
||||
n = n > DMX_CHANNELS ? DMX_CHANNELS : n;
|
||||
size_t dl = n + (n & 1);
|
||||
dl = dl < 2 ? 2 : dl;
|
||||
memcpy(pkt, "Art-Net\0", 8);
|
||||
uint8_t h[10] = { 0x00, 0x50, 0, 14, seq, 0, uni & 0xFF, (uni >> 8) & 0x7F, dl >> 8, dl & 0xFF };
|
||||
memcpy(pkt + 8, h, 10);
|
||||
memset(pkt + 18, 0, dl);
|
||||
memcpy(pkt + 18, data, n);
|
||||
return 18 + dl;
|
||||
}
|
||||
|
||||
size_t dmx_sacn_packet(uint8_t *pkt, const uint8_t cid[16], const char *source, uint8_t seq, int uni,
|
||||
const uint8_t *data, size_t n)
|
||||
{
|
||||
n = n > DMX_CHANNELS ? DMX_CHANNELS : n;
|
||||
size_t total = 126 + n;
|
||||
memset(pkt, 0, 126);
|
||||
put16(pkt, 0x0010);
|
||||
memcpy(pkt + 4, "ASC-E1.17\0\0\0", 12);
|
||||
put16(pkt + 16, 0x7000 | (total - 16));
|
||||
pkt[21] = 0x04;
|
||||
memcpy(pkt + 22, cid, 16);
|
||||
put16(pkt + 38, 0x7000 | (total - 38));
|
||||
pkt[43] = 0x02;
|
||||
snprintf((char *)pkt + 44, 64, "%s", source);
|
||||
pkt[108] = 100;
|
||||
pkt[111] = seq;
|
||||
put16(pkt + 113, uni);
|
||||
put16(pkt + 115, 0x7000 | (total - 115));
|
||||
pkt[117] = 0x02;
|
||||
pkt[118] = 0xA1;
|
||||
put16(pkt + 121, 0x0001);
|
||||
put16(pkt + 123, n + 1);
|
||||
memcpy(pkt + 126, data, n);
|
||||
return total;
|
||||
}
|
||||
|
||||
uint32_t dmx_sacn_group(int uni)
|
||||
{
|
||||
return 0xEFFF0000u | (uni & 0xFFFF);
|
||||
}
|
||||
|
||||
// "Red 3" -> DMX_ROLE_RED, 3; "Red" -> DMX_ROLE_RED, 0 (no number); other names -> FIXED
|
||||
static int colour_role(const char *name, int *num)
|
||||
{
|
||||
static const struct {
|
||||
const char *word;
|
||||
int role;
|
||||
} WORDS[] = { { "red", DMX_ROLE_RED }, { "green", DMX_ROLE_GREEN }, { "blue", DMX_ROLE_BLUE }, { "white", DMX_ROLE_WHITE } };
|
||||
*num = 0;
|
||||
for (size_t i = 0; i < sizeof(WORDS) / sizeof(WORDS[0]); i++) {
|
||||
size_t w = strlen(WORDS[i].word);
|
||||
if (strncasecmp(name, WORDS[i].word, w) != 0) {
|
||||
continue;
|
||||
}
|
||||
const char *rest = name + w;
|
||||
if (!*rest) {
|
||||
return WORDS[i].role;
|
||||
}
|
||||
if (*rest != ' ' || !isdigit((unsigned char)rest[1])) {
|
||||
continue;
|
||||
}
|
||||
char *end;
|
||||
long n = strtol(rest + 1, &end, 10);
|
||||
if (*end || n < 1 || n > 9999) {
|
||||
continue;
|
||||
}
|
||||
*num = (int)n;
|
||||
return WORDS[i].role;
|
||||
}
|
||||
return DMX_ROLE_FIXED;
|
||||
}
|
||||
|
||||
static bool is_any(const char *name, const char *const *list, size_t n)
|
||||
{
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
if (!strcasecmp(name, list[i])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int dmx_def_map(const cJSON *def, dmx_slot_t *slots, int max, int *pixels, bool *white)
|
||||
{
|
||||
static const char *const DIMMERS[] = { "Dimmer", "Intensity", "Master Dimmer", "Center Brightness" };
|
||||
static const char *const STROBES[] = { "Strobe", "Shutter", "Center Strobe" };
|
||||
const cJSON *chans = cJSON_GetObjectItem(def, "channels");
|
||||
const cJSON *defaults = cJSON_GetObjectItem(def, "defaults");
|
||||
*pixels = 1;
|
||||
*white = false;
|
||||
if (!cJSON_IsArray(chans)) {
|
||||
return 0;
|
||||
}
|
||||
// The numbers of the pixel groups, in order: "Red 1".."Red 7" are pixels 0..6; plain "Red" is number 0
|
||||
int nums[DMX_PIXELS_MAX], nnums = 0;
|
||||
int count = 0;
|
||||
const cJSON *c;
|
||||
cJSON_ArrayForEach(c, chans)
|
||||
{
|
||||
if (count >= max) {
|
||||
break;
|
||||
}
|
||||
const char *name = cJSON_IsString(c) ? c->valuestring : "";
|
||||
while (isspace((unsigned char)*name)) {
|
||||
name++;
|
||||
}
|
||||
char trimmed[48];
|
||||
snprintf(trimmed, sizeof(trimmed), "%s", name);
|
||||
for (int k = (int)strlen(trimmed) - 1; k >= 0 && isspace((unsigned char)trimmed[k]); k--) {
|
||||
trimmed[k] = 0;
|
||||
}
|
||||
dmx_slot_t *s = &slots[count++];
|
||||
memset(s, 0, sizeof(*s));
|
||||
int num;
|
||||
int role = colour_role(trimmed, &num);
|
||||
if (role != DMX_ROLE_FIXED) {
|
||||
int at = -1;
|
||||
for (int k = 0; k < nnums; k++) {
|
||||
at = nums[k] == num ? k : at;
|
||||
}
|
||||
if (at < 0 && nnums < DMX_PIXELS_MAX) {
|
||||
nums[nnums++] = num;
|
||||
}
|
||||
s->role = (uint8_t)role;
|
||||
s->pixel = (uint8_t)num; // the group's number for now; its index once all are known
|
||||
*white = *white || role == DMX_ROLE_WHITE;
|
||||
} else if (is_any(trimmed, DIMMERS, sizeof(DIMMERS) / sizeof(DIMMERS[0]))) {
|
||||
s->role = DMX_ROLE_DIMMER;
|
||||
} else if (is_any(trimmed, STROBES, sizeof(STROBES) / sizeof(STROBES[0]))) {
|
||||
s->role = DMX_ROLE_STROBE;
|
||||
} else {
|
||||
const cJSON *d = cJSON_GetObjectItem(defaults, trimmed);
|
||||
int v = cJSON_IsNumber(d) ? d->valueint : 0;
|
||||
s->value = (uint8_t)(v < 0 ? 0 : v > 255 ? 255 : v);
|
||||
}
|
||||
}
|
||||
// Sort the group numbers, then turn each slot's number into its pixel index
|
||||
for (int i = 1; i < nnums; i++) {
|
||||
for (int k = i; k > 0 && nums[k - 1] > nums[k]; k--) {
|
||||
int t = nums[k];
|
||||
nums[k] = nums[k - 1];
|
||||
nums[k - 1] = t;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < count; i++) {
|
||||
if (slots[i].role < DMX_ROLE_RED || slots[i].role > DMX_ROLE_WHITE) {
|
||||
continue;
|
||||
}
|
||||
int idx = 0;
|
||||
for (int k = 0; k < nnums; k++) {
|
||||
idx = nums[k] == slots[i].pixel ? k : idx;
|
||||
}
|
||||
slots[i].pixel = (uint8_t)idx;
|
||||
}
|
||||
*pixels = nnums ? nnums : 1;
|
||||
return count;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
// Art-Net and sACN (E1.31) packets: one universe of DMX data each. Shared by the pixel outputs' test
|
||||
// (outputs.c) and the DMX bridge (bridge_dmx.c).
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "cJSON.h"
|
||||
|
||||
#define DMX_CHANNELS 512
|
||||
#define ARTNET_PORT 6454
|
||||
#define SACN_PORT 5568
|
||||
#define DMX_PACKET_MAX (126 + DMX_CHANNELS) // the larger of the two
|
||||
|
||||
// ArtDmx for universe uni (15-bit port-address) with sequence seq: n bytes of data (at most 512, padded to an
|
||||
// even length of at least 2). Returns the packet's length.
|
||||
size_t dmx_artnet_packet(uint8_t *pkt, uint8_t seq, int uni, const uint8_t *data, size_t n);
|
||||
|
||||
// sACN data packet for universe uni (1-63999) from the source cid / name, priority 100, start code 0: n bytes of
|
||||
// data (at most 512). Returns the packet's length.
|
||||
size_t dmx_sacn_packet(uint8_t *pkt, const uint8_t cid[16], const char *source, uint8_t seq, int uni,
|
||||
const uint8_t *data, size_t n);
|
||||
|
||||
// The multicast group of an sACN universe: 239.255.<hi>.<lo>, host order
|
||||
uint32_t dmx_sacn_group(int uni);
|
||||
|
||||
// What a fixture's slot gets, from its channel name in the definition (see bridge_dmx.h)
|
||||
enum { DMX_ROLE_FIXED, DMX_ROLE_RED, DMX_ROLE_GREEN, DMX_ROLE_BLUE, DMX_ROLE_WHITE, DMX_ROLE_DIMMER, DMX_ROLE_STROBE };
|
||||
#define DMX_PIXELS_MAX 64
|
||||
|
||||
typedef struct {
|
||||
uint8_t role;
|
||||
uint8_t pixel; // RED..WHITE: the pixel group, 0 first
|
||||
uint8_t value; // FIXED: the default
|
||||
} dmx_slot_t;
|
||||
|
||||
// Map a "dmx_definition" record ({channels: [names], defaults: {name: value}}) into slots (up to max).
|
||||
// Returns the channel count (0 when the record has none), with the pixel groups (at least 1) in *pixels and
|
||||
// whether any pixel has a white slot in *white.
|
||||
int dmx_def_map(const cJSON *def, dmx_slot_t *slots, int max, int *pixels, bool *white);
|
||||
+338
-40
@@ -14,6 +14,8 @@
|
||||
#include "rel.h"
|
||||
#include "wifi_drv.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/queue.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include "freertos/task.h"
|
||||
#include "store.h"
|
||||
|
||||
@@ -308,6 +310,33 @@ static bool wifi_in_group(const cJSON *dev, const char *id, const char *gid)
|
||||
return false;
|
||||
}
|
||||
|
||||
// The Wi-Fi driver whose record holds this MAC (12 hex digits), or NULL
|
||||
static const cJSON *wifi_by_mac(const char *hex12)
|
||||
{
|
||||
const cJSON *d;
|
||||
cJSON_ArrayForEach(d, store_coll("device"))
|
||||
{
|
||||
const cJSON *m = cJSON_GetObjectItem(d, "mac");
|
||||
if (d->string && is_wifi(d) && cJSON_IsString(m) && !strcasecmp(m->valuestring, hex12)) {
|
||||
return d;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Whether the Wi-Fi device is in one of the zone's groups
|
||||
static bool wifi_in_zone(const cJSON *dev, const char *zone_id)
|
||||
{
|
||||
char t[ZONE_TARGETS_MAX][GROUP_ID_MAX];
|
||||
int n = engine_zone_targets(zone_id, t, ZONE_TARGETS_MAX);
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (wifi_in_group(dev, dev->string, t[i])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Wi-Fi drivers in the zone's groups get its preset (payload), or off when payload is NULL
|
||||
static void wifi_zone(const char *zone_id, const cJSON *payload)
|
||||
{
|
||||
@@ -495,8 +524,10 @@ typedef struct {
|
||||
char zone[16];
|
||||
char preset[24];
|
||||
uint16_t ver;
|
||||
uint32_t seq; // order of zone_cur_set calls, to tell which zone spoke last
|
||||
} zone_cur_t;
|
||||
static zone_cur_t s_cur[16];
|
||||
static uint32_t s_cur_seq;
|
||||
|
||||
static void zone_cur_set(const char *zone_id, const char *preset_id)
|
||||
{
|
||||
@@ -514,6 +545,7 @@ static void zone_cur_set(const char *zone_id, const char *preset_id)
|
||||
snprintf(slot->zone, sizeof(slot->zone), "%s", zone_id);
|
||||
snprintf(slot->preset, sizeof(slot->preset), "%s", preset_id);
|
||||
slot->ver = rel_ver();
|
||||
slot->seq = ++s_cur_seq;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -597,6 +629,26 @@ int engine_group_macs(const char *gid, char out[][13], int max)
|
||||
snprintf(out[n++], 13, "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
||||
}
|
||||
}
|
||||
// Wi-Fi drivers are listed by hostname; the MAC in their record names them as d<mac> like an ESP-NOW driver
|
||||
cJSON_ArrayForEach(d, store_coll("device"))
|
||||
{
|
||||
const cJSON *m = cJSON_GetObjectItem(d, "mac");
|
||||
if (n >= max || !d->string || !is_wifi(d) || !cJSON_IsString(m) || strlen(m->valuestring) != 12 ||
|
||||
!wifi_in_group(d, d->string, gid)) {
|
||||
continue;
|
||||
}
|
||||
char hex[13];
|
||||
for (int i = 0; i < 13; i++) {
|
||||
hex[i] = (char)tolower((unsigned char)m->valuestring[i]);
|
||||
}
|
||||
bool dup = false;
|
||||
for (int i = 0; i < n && !dup; i++) {
|
||||
dup = !strcmp(out[i], hex);
|
||||
}
|
||||
if (!dup) {
|
||||
memcpy(out[n++], hex, 13);
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
@@ -1063,7 +1115,13 @@ static void send_groups(const uint8_t mac[6], const char *name, bool allow_empty
|
||||
if (count == 0 && !allow_empty) {
|
||||
return;
|
||||
}
|
||||
rel_send(mac, pkt, len, false, 1);
|
||||
// tx waits for room: unicasts to drivers that are off hold the link's slots until they give up, and a
|
||||
// dropped GROUPS leaves a driver out of a zone whose next play it then ignores (and commits, so no resync)
|
||||
esp_err_t err = tx(mac, pkt, len, false, 1);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(TAG, "groups for %02x%02x%02x%02x%02x%02x not sent: %s", mac[0], mac[1], mac[2], mac[3], mac[4],
|
||||
mac[5], esp_err_to_name(err));
|
||||
}
|
||||
}
|
||||
|
||||
static bool hex_mac(const char *s, uint8_t mac[6])
|
||||
@@ -1108,60 +1166,224 @@ static bool skip_unresponsive(const uint8_t mac[6])
|
||||
return false;
|
||||
}
|
||||
|
||||
// Re-send group membership to every registered ESP-NOW driver (zones or devices changed)
|
||||
void engine_groups_changed(void)
|
||||
/* Group pushes never hold the store lock while they wait for room on the link. Each send to a driver that
|
||||
does not ack holds a link slot for its whole retry run, so with a few such drivers every send waits about
|
||||
2 s for room; doing that under the lock stalled every HTTP request (the UI stopped loading) for as long
|
||||
as the push ran. So the packets are built under the lock (quick) and sent after it is released. */
|
||||
typedef struct {
|
||||
uint8_t mac[6];
|
||||
uint8_t pkt[REL_FRAG_MAX];
|
||||
size_t len;
|
||||
uint16_t seq;
|
||||
bool queued;
|
||||
} group_out_t;
|
||||
|
||||
// Every registered ESP-NOW driver's GROUPS packet (skip_dead: leave out drivers that stopped acking).
|
||||
// Takes the store lock. Returns a malloc'd array of *n entries (NULL when there are none).
|
||||
static group_out_t *groups_collect(bool skip_dead, int *n)
|
||||
{
|
||||
*n = 0;
|
||||
store_lock();
|
||||
int cap = cJSON_GetArraySize(store_coll("device"));
|
||||
group_out_t *out = cap > 0 ? malloc(cap * sizeof(*out)) : NULL;
|
||||
const cJSON *d;
|
||||
cJSON_ArrayForEach(d, store_coll("device"))
|
||||
{
|
||||
const cJSON *name = cJSON_GetObjectItem(d, "name"), *addr = cJSON_GetObjectItem(d, "address");
|
||||
const cJSON *tr = cJSON_GetObjectItem(d, "transport");
|
||||
uint8_t mac[6];
|
||||
const char *hex = cJSON_IsString(addr) ? addr->valuestring : d->string;
|
||||
if (cJSON_IsString(name) && cJSON_IsString(tr) && !strcmp(tr->valuestring, "espnow") && hex_mac(hex, mac) &&
|
||||
!skip_unresponsive(mac)) {
|
||||
send_groups(mac, name->valuestring, true);
|
||||
if (out && *n < cap && cJSON_IsString(name) && cJSON_IsString(tr) && !strcmp(tr->valuestring, "espnow") &&
|
||||
hex_mac(hex, out[*n].mac) && !(skip_dead && skip_unresponsive(out[*n].mac))) {
|
||||
int count;
|
||||
out[*n].len = build_groups(out[*n].pkt, out[*n].mac, name->valuestring, &count);
|
||||
out[*n].queued = false;
|
||||
(*n)++;
|
||||
}
|
||||
}
|
||||
store_unlock();
|
||||
if (out && *n == 0) {
|
||||
free(out);
|
||||
out = NULL;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
#define PUSH_MAX 32
|
||||
static SemaphoreHandle_t s_groups_wake;
|
||||
|
||||
static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len);
|
||||
static void resync_driver(const uint8_t mac[6]);
|
||||
|
||||
/* Announces and resync requests arrive on the ack task (rel_task), which is also the only task that frees
|
||||
room on the link (it processes the acks). Handling them there meant taking the store lock and waiting for
|
||||
room on the link from the very task that makes room: each one stalled ack handling for up to 2 s, and
|
||||
while a group push held the store lock no ack was processed at all. So the ack task only queues them,
|
||||
and the driver task below does the work. */
|
||||
enum { JOB_ANNOUNCE, JOB_RESYNC };
|
||||
typedef struct {
|
||||
uint8_t kind;
|
||||
uint8_t mac[6];
|
||||
uint8_t len;
|
||||
uint8_t data[250]; // an announce: rel's largest frame
|
||||
} driver_job_t;
|
||||
#define DRIVER_JOBS_LEN 32
|
||||
static QueueHandle_t s_driver_jobs;
|
||||
|
||||
static void queue_driver_job(uint8_t kind, const uint8_t mac[6], const uint8_t *data, int len)
|
||||
{
|
||||
if (!s_driver_jobs || len < 0 || len > (int)sizeof(((driver_job_t *)0)->data)) {
|
||||
return;
|
||||
}
|
||||
driver_job_t j = { .kind = kind, .len = (uint8_t)len };
|
||||
memcpy(j.mac, mac, 6);
|
||||
if (len > 0) {
|
||||
memcpy(j.data, data, len);
|
||||
}
|
||||
if (xQueueSend(s_driver_jobs, &j, 0) != pdTRUE) {
|
||||
// The driver announces or asks for a resync again, so a dropped one only costs time
|
||||
ESP_LOGW(TAG, "%s from %02x%02x%02x%02x%02x%02x dropped: driver task busy",
|
||||
kind == JOB_ANNOUNCE ? "announce" : "resync", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
||||
}
|
||||
}
|
||||
|
||||
static void queue_announce(const uint8_t mac[6], const uint8_t *pkt, int len)
|
||||
{
|
||||
queue_driver_job(JOB_ANNOUNCE, mac, pkt, len);
|
||||
}
|
||||
|
||||
static void queue_resync(const uint8_t mac[6])
|
||||
{
|
||||
queue_driver_job(JOB_RESYNC, mac, NULL, 0);
|
||||
}
|
||||
|
||||
/* The driver task never waits for room on the link: with drivers that do not ack holding the link's slots,
|
||||
each wait is up to 2 s, and announces queued behind them were dropped. A GROUPS that finds no room is
|
||||
kept here and sent again (rebuilt, in case membership changed) every DEFER_RETRY_MS. Only the driver
|
||||
task touches this. */
|
||||
#define DEFER_MAX 64
|
||||
#define DEFER_RETRY_MS 100
|
||||
static struct {
|
||||
uint8_t mac[6];
|
||||
bool allow_empty; // from a group push (send even with no groups); else from an announce (see build_groups)
|
||||
} s_defer[DEFER_MAX];
|
||||
static int s_defer_n;
|
||||
static int64_t s_defer_next_us;
|
||||
|
||||
static void defer_groups(const uint8_t mac[6], bool allow_empty)
|
||||
{
|
||||
for (int i = 0; i < s_defer_n; i++) {
|
||||
if (!memcmp(s_defer[i].mac, mac, 6)) {
|
||||
s_defer[i].allow_empty |= allow_empty;
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (s_defer_n == DEFER_MAX) {
|
||||
ESP_LOGW(TAG, "groups for %02x%02x%02x%02x%02x%02x not sent: link busy", mac[0], mac[1], mac[2], mac[3],
|
||||
mac[4], mac[5]);
|
||||
return;
|
||||
}
|
||||
memcpy(s_defer[s_defer_n].mac, mac, 6);
|
||||
s_defer[s_defer_n].allow_empty = allow_empty;
|
||||
s_defer_n++;
|
||||
}
|
||||
|
||||
// Send a driver its GROUPS now if the link has room, else later (see s_defer). Never waits.
|
||||
static void send_groups_or_defer(const uint8_t mac[6], const uint8_t *pkt, size_t len, bool allow_empty)
|
||||
{
|
||||
esp_err_t err = rel_send(mac, pkt, len, false, 1);
|
||||
if (err == ESP_ERR_NO_MEM) {
|
||||
defer_groups(mac, allow_empty);
|
||||
} else if (err != ESP_OK) {
|
||||
ESP_LOGW(TAG, "groups for %02x%02x%02x%02x%02x%02x not sent: %s", mac[0], mac[1], mac[2], mac[3], mac[4],
|
||||
mac[5], esp_err_to_name(err));
|
||||
}
|
||||
}
|
||||
|
||||
static void retry_deferred_groups(void)
|
||||
{
|
||||
int64_t now = esp_timer_get_time();
|
||||
if (!s_defer_n || now < s_defer_next_us) {
|
||||
return;
|
||||
}
|
||||
s_defer_next_us = now + DEFER_RETRY_MS * 1000LL;
|
||||
int n = s_defer_n;
|
||||
static struct {
|
||||
uint8_t mac[6];
|
||||
bool allow_empty;
|
||||
} todo[DEFER_MAX];
|
||||
memcpy(todo, s_defer, n * sizeof(todo[0]));
|
||||
s_defer_n = 0; // those that still find no room come back
|
||||
for (int i = 0; i < n; i++) {
|
||||
uint8_t pkt[REL_FRAG_MAX];
|
||||
int count = 0;
|
||||
size_t len = 0;
|
||||
store_lock();
|
||||
const char *name = device_name_for(todo[i].mac); // gone (deleted): nothing to send
|
||||
if (name) {
|
||||
len = build_groups(pkt, todo[i].mac, name, &count);
|
||||
}
|
||||
store_unlock();
|
||||
if (len && (count > 0 || todo[i].allow_empty)) {
|
||||
send_groups_or_defer(todo[i].mac, pkt, len, todo[i].allow_empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// One group push to every driver (see groups_collect)
|
||||
static void groups_push_pass(void)
|
||||
{
|
||||
int n;
|
||||
group_out_t *out = groups_collect(true, &n); // skip_unresponsive is only called from this task
|
||||
for (int i = 0; i < n; i++) {
|
||||
send_groups_or_defer(out[i].mac, out[i].pkt, out[i].len, true);
|
||||
}
|
||||
free(out);
|
||||
}
|
||||
|
||||
// The driver task: queued announces and resyncs, and group pushes. A push runs once per wake: edits made
|
||||
// during a pass give the semaphore again, so they get a pass of their own; edits made while it waits share one.
|
||||
#define DRIVER_TASK_POLL_MS 20
|
||||
static void driver_task(void *arg)
|
||||
{
|
||||
(void)arg;
|
||||
for (;;) {
|
||||
driver_job_t j;
|
||||
if (xQueueReceive(s_driver_jobs, &j, pdMS_TO_TICKS(DRIVER_TASK_POLL_MS)) == pdTRUE) {
|
||||
if (j.kind == JOB_ANNOUNCE) {
|
||||
on_announce(j.mac, j.data, j.len);
|
||||
} else {
|
||||
resync_driver(j.mac);
|
||||
}
|
||||
}
|
||||
if (xSemaphoreTake(s_groups_wake, 0) == pdTRUE) {
|
||||
groups_push_pass();
|
||||
}
|
||||
retry_deferred_groups();
|
||||
}
|
||||
}
|
||||
|
||||
// Re-send group membership to every registered ESP-NOW driver (zones or devices changed). Returns at once:
|
||||
// the group pusher sends it, so an HTTP handler never waits on the drivers.
|
||||
void engine_groups_changed(void)
|
||||
{
|
||||
if (s_groups_wake) {
|
||||
xSemaphoreGive(s_groups_wake);
|
||||
}
|
||||
}
|
||||
|
||||
void engine_groups_push_all(int *total, int *sent, int *failed)
|
||||
{
|
||||
struct {
|
||||
uint8_t mac[6];
|
||||
uint16_t seq;
|
||||
bool queued;
|
||||
} out[PUSH_MAX];
|
||||
int n = 0;
|
||||
store_lock();
|
||||
const cJSON *d;
|
||||
cJSON_ArrayForEach(d, store_coll("device"))
|
||||
{
|
||||
const cJSON *name = cJSON_GetObjectItem(d, "name"), *addr = cJSON_GetObjectItem(d, "address");
|
||||
const cJSON *tr = cJSON_GetObjectItem(d, "transport");
|
||||
const char *hex = cJSON_IsString(addr) ? addr->valuestring : d->string;
|
||||
if (n < PUSH_MAX && cJSON_IsString(name) && cJSON_IsString(tr) && !strcmp(tr->valuestring, "espnow") &&
|
||||
hex_mac(hex, out[n].mac)) {
|
||||
uint8_t pkt[REL_FRAG_MAX];
|
||||
int count;
|
||||
size_t len = build_groups(pkt, out[n].mac, name->valuestring, &count);
|
||||
out[n].queued = false;
|
||||
for (int i = 0; i < 400 && !out[n].queued; i++) { // wait for room, as tx() does
|
||||
esp_err_t err = rel_send_seq(out[n].mac, pkt, len, false, 1, &out[n].seq);
|
||||
out[n].queued = err == ESP_OK;
|
||||
if (err != ESP_ERR_NO_MEM) {
|
||||
break;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(5));
|
||||
int n;
|
||||
group_out_t *out = groups_collect(false, &n);
|
||||
for (int k = 0; k < n; k++) {
|
||||
for (int i = 0; i < 400 && !out[k].queued; i++) { // wait for room, as tx() does
|
||||
esp_err_t err = rel_send_seq(out[k].mac, out[k].pkt, out[k].len, false, 1, &out[k].seq);
|
||||
out[k].queued = err == ESP_OK;
|
||||
if (err != ESP_ERR_NO_MEM) {
|
||||
break;
|
||||
}
|
||||
n++;
|
||||
vTaskDelay(pdMS_TO_TICKS(5));
|
||||
}
|
||||
}
|
||||
store_unlock();
|
||||
// All are in flight at once; then collect each outcome (rel gives up after about 2 s)
|
||||
*total = n;
|
||||
*sent = *failed = 0;
|
||||
@@ -1173,6 +1395,7 @@ void engine_groups_push_all(int *total, int *sent, int *failed)
|
||||
(*failed)++;
|
||||
}
|
||||
}
|
||||
free(out);
|
||||
}
|
||||
|
||||
// A driver said hello at boot: register it, then tell it which zones it belongs to
|
||||
@@ -1320,6 +1543,9 @@ static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len)
|
||||
// A driver heard on the browser bridge is one of the rig page's simulated drivers: "sim": true (a real
|
||||
// board has no "sim" key)
|
||||
const bool sim = bridge_mac_is_browser(mac);
|
||||
// A fixture of a DMX bridge: "dmx_fixture": true and the bridge's address, kept once set
|
||||
char dmx_addr[BRIDGE_ADDR_MAX];
|
||||
const bool dmx = bridge_mac_is_dmx(mac, dmx_addr, sizeof(dmx_addr));
|
||||
if (!rec) {
|
||||
rec = cJSON_AddObjectToObject(devs, hex);
|
||||
cJSON_AddStringToObject(rec, "id", hex);
|
||||
@@ -1331,6 +1557,10 @@ static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len)
|
||||
if (sim) {
|
||||
cJSON_AddTrueToObject(rec, "sim");
|
||||
}
|
||||
if (dmx) {
|
||||
cJSON_AddTrueToObject(rec, "dmx_fixture");
|
||||
cJSON_AddStringToObject(rec, "bridge", dmx_addr);
|
||||
}
|
||||
store_save("device");
|
||||
ESP_LOGI(TAG, "new %sdriver %s (%s)", sim ? "simulated " : "", name, hex);
|
||||
} else {
|
||||
@@ -1342,6 +1572,13 @@ static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len)
|
||||
if (api_apply_driver_cfg(rec, cfg, cfg_len)) {
|
||||
changed = true;
|
||||
}
|
||||
const cJSON *was = cJSON_GetObjectItem(rec, "bridge");
|
||||
if (dmx && (!cJSON_IsTrue(cJSON_GetObjectItem(rec, "dmx_fixture")) || !cJSON_IsString(was) ||
|
||||
strcmp(was->valuestring, dmx_addr) != 0)) {
|
||||
api_set(rec, "dmx_fixture", cJSON_CreateTrue());
|
||||
api_set(rec, "bridge", cJSON_CreateString(dmx_addr));
|
||||
changed = true;
|
||||
}
|
||||
if (sim != cJSON_IsTrue(cJSON_GetObjectItem(rec, "sim"))) {
|
||||
cJSON_DeleteItemFromObject(rec, "sim");
|
||||
if (sim) {
|
||||
@@ -1356,8 +1593,14 @@ static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len)
|
||||
if (pkt[0] == '{') {
|
||||
free(cfg);
|
||||
}
|
||||
send_groups(mac, name, false);
|
||||
// Built under the lock, sent after it (see groups_collect): HTTP handlers wait on that lock
|
||||
uint8_t gpkt[REL_FRAG_MAX];
|
||||
int count;
|
||||
size_t glen = build_groups(gpkt, mac, name, &count);
|
||||
store_unlock();
|
||||
if (count > 0) { // a driver in no zone keeps the groups it has (see build_groups)
|
||||
send_groups_or_defer(mac, gpkt, glen, false);
|
||||
}
|
||||
}
|
||||
|
||||
/* A driver reported a stale state version: replay what its zone is playing, then commit the version */
|
||||
@@ -1402,8 +1645,16 @@ static void resync_driver(const uint8_t mac[6])
|
||||
esp_err_t engine_init(void)
|
||||
{
|
||||
wifi_drv_init();
|
||||
rel_set_resync_cb(resync_driver);
|
||||
rel_set_announce_cb(on_announce);
|
||||
s_groups_wake = xSemaphoreCreateBinary();
|
||||
s_driver_jobs = xQueueCreate(DRIVER_JOBS_LEN, sizeof(driver_job_t));
|
||||
// 8 KB: it runs what rel_task used to (announce parsing, resync's frames) as well as the group pushes
|
||||
if (!s_groups_wake || !s_driver_jobs || xTaskCreate(driver_task, "drivers", 8192, NULL, 3, NULL) != pdPASS) {
|
||||
ESP_LOGE(TAG, "driver task not started");
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
// The ack task only queues these (see driver_job_t)
|
||||
rel_set_resync_cb(queue_resync);
|
||||
rel_set_announce_cb(queue_announce);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
@@ -1413,5 +1664,52 @@ bool engine_mac_in_zone(const char *hex12, const char *zone_id)
|
||||
if (!hex_mac(hex12, mac)) {
|
||||
return false;
|
||||
}
|
||||
return driver_in_zone(mac, device_name_for(mac), zone_id);
|
||||
const cJSON *w = wifi_by_mac(hex12);
|
||||
return w ? wifi_in_zone(w, zone_id) : driver_in_zone(mac, device_name_for(mac), zone_id);
|
||||
}
|
||||
|
||||
bool engine_driver_current(const char *hex12, char *preset, size_t len, uint32_t *seq)
|
||||
{
|
||||
uint8_t mac[6];
|
||||
if (!hex_mac(hex12, mac)) {
|
||||
return false;
|
||||
}
|
||||
const char *name = device_name_for(mac);
|
||||
const cJSON *w = wifi_by_mac(hex12);
|
||||
const zone_cur_t *best = NULL;
|
||||
for (int i = 0; i < 16; i++) {
|
||||
if (s_cur[i].zone[0] && (!best || s_cur[i].seq > best->seq) &&
|
||||
(w ? wifi_in_zone(w, s_cur[i].zone) : driver_in_zone(mac, name, s_cur[i].zone))) {
|
||||
best = &s_cur[i];
|
||||
}
|
||||
}
|
||||
if (!best) {
|
||||
return false;
|
||||
}
|
||||
snprintf(preset, len, "%s", best->preset);
|
||||
*seq = best->seq;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool engine_mac_is_sim(const char *hex12)
|
||||
{
|
||||
const cJSON *rec = cJSON_GetObjectItem(store_coll("device"), hex12);
|
||||
return cJSON_IsTrue(cJSON_GetObjectItem(rec ? rec : wifi_by_mac(hex12), "sim"));
|
||||
}
|
||||
|
||||
bool engine_mac_is_wifi(const char *hex12)
|
||||
{
|
||||
return wifi_by_mac(hex12) != NULL;
|
||||
}
|
||||
|
||||
bool engine_group_has_sim(const char *gid)
|
||||
{
|
||||
char macs[64][13];
|
||||
int n = engine_group_macs(gid, macs, 64);
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (engine_mac_is_sim(macs[i])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
+15
-2
@@ -20,7 +20,7 @@ int engine_zone_targets(const char *zone_id, char out[][GROUP_ID_MAX], int max);
|
||||
cJSON *engine_preset_payload(const char *preset_id);
|
||||
|
||||
// Drivers in group gid (a group id, "z<zone>" or a driver's own "d<mac>"), as 12-hex MACs from the
|
||||
// device list. Call with the store locked.
|
||||
// device list: ESP-NOW drivers, and Wi-Fi drivers whose record has a "mac". Call with the store locked.
|
||||
int engine_group_macs(const char *gid, char out[][13], int max);
|
||||
// Wi-Fi drivers (listed by hostname) in the zone's groups. Call with the store locked.
|
||||
int engine_zone_wifi_ids(const char *zone_id, char out[][GROUP_ID_MAX], int max);
|
||||
@@ -28,6 +28,18 @@ int engine_zone_wifi_ids(const char *zone_id, char out[][GROUP_ID_MAX], int max)
|
||||
const char *engine_zone_current(const char *zone_id);
|
||||
// Is the driver with this MAC (12 hex digits) in one of the zone's groups? Call with the store locked.
|
||||
bool engine_mac_in_zone(const char *hex12, const char *zone_id);
|
||||
// What the driver with this MAC last got from a zone: the newest play/stop/note among the zones holding it
|
||||
// ("off" included), with an order number that grows with every such call. False when none of its zones has played.
|
||||
// Call with the store locked.
|
||||
bool engine_driver_current(const char *hex12, char *preset, size_t len, uint32_t *seq);
|
||||
// Is the driver with this MAC (12 hex digits) one of the rig page's simulated drivers ("sim": true in its
|
||||
// device record)? Call with the store locked.
|
||||
bool engine_mac_is_sim(const char *hex12);
|
||||
// Is the driver with this MAC a Wi-Fi driver (its record, listed by hostname, has this "mac")? Call with the
|
||||
// store locked.
|
||||
bool engine_mac_is_wifi(const char *hex12);
|
||||
// Does group gid (as engine_group_macs takes it) hold a simulated driver? Call with the store locked.
|
||||
bool engine_group_has_sim(const char *gid);
|
||||
// Record preset_id as what zone_id plays, when the UI has sent it to the drivers itself
|
||||
void engine_zone_note(const char *zone_id, const char *preset_id);
|
||||
|
||||
@@ -45,7 +57,8 @@ esp_err_t engine_send_presets(const cJSON *ids, bool save, const char *def, cons
|
||||
// board into the Wi-Fi device. Call without the store lock held.
|
||||
void engine_wifi_mac(const char *host, const char *mac);
|
||||
|
||||
// Zones or devices changed: re-send group membership to every registered ESP-NOW driver
|
||||
// Zones or devices changed: re-send group membership to every registered ESP-NOW driver. Returns at once
|
||||
// (a background task sends it, without the store lock), so it may be called with or without the lock held.
|
||||
void engine_groups_changed(void);
|
||||
// POST /devices/groups: send every ESP-NOW driver its groups, including silent ones, and wait for the
|
||||
// acks. Call without the store lock held.
|
||||
|
||||
+9
-40
@@ -8,6 +8,7 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "api_util.h"
|
||||
#include "dmx_wire.h"
|
||||
#include "esp_mac.h"
|
||||
#include "esp_timer.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
@@ -181,7 +182,7 @@ static bool resolve(out_t *o, int universe_for_sacn)
|
||||
o->to.sin_port = htons(o->port);
|
||||
if (!o->host[0]) {
|
||||
if (!strcmp(o->proto, "sacn")) { // multicast group of the universe
|
||||
o->to.sin_addr.s_addr = htonl(0xEFFF0000 | (universe_for_sacn & 0xFFFF));
|
||||
o->to.sin_addr.s_addr = htonl(dmx_sacn_group(universe_for_sacn));
|
||||
} else {
|
||||
o->to.sin_addr.s_addr = htonl(INADDR_BROADCAST);
|
||||
}
|
||||
@@ -228,59 +229,27 @@ static void send_ddp(out_t *o, const uint8_t *data, size_t len)
|
||||
|
||||
static void send_artnet(out_t *o, const uint8_t *data, size_t len)
|
||||
{
|
||||
static uint8_t pkt[18 + UNIVERSE_BYTES + 1];
|
||||
static uint8_t pkt[DMX_PACKET_MAX];
|
||||
o->seq = o->seq % 255 + 1;
|
||||
int base = o->universe;
|
||||
for (size_t off = 0, u = 0; off < len; off += UNIVERSE_BYTES, u++) {
|
||||
size_t n = len - off < UNIVERSE_BYTES ? len - off : UNIVERSE_BYTES;
|
||||
size_t dl = n + (n & 1);
|
||||
dl = dl < 2 ? 2 : dl;
|
||||
int uni = base + u;
|
||||
memcpy(pkt, "Art-Net\0", 8);
|
||||
uint8_t h[10] = { 0x00, 0x50, 0, 14, o->seq, 0, uni & 0xFF, (uni >> 8) & 0x7F, dl >> 8, dl & 0xFF };
|
||||
memcpy(pkt + 8, h, 10);
|
||||
memset(pkt + 18, 0, dl);
|
||||
memcpy(pkt + 18, data + off, n);
|
||||
send_pkt(o, pkt, 18 + dl);
|
||||
send_pkt(o, pkt, dmx_artnet_packet(pkt, o->seq, o->universe + u, data + off, n));
|
||||
}
|
||||
}
|
||||
|
||||
static void put16(uint8_t *p, unsigned v)
|
||||
{
|
||||
p[0] = v >> 8;
|
||||
p[1] = v;
|
||||
}
|
||||
|
||||
static void send_sacn(out_t *o, const uint8_t *data, size_t len)
|
||||
{
|
||||
static uint8_t pkt[126 + UNIVERSE_BYTES];
|
||||
static uint8_t pkt[DMX_PACKET_MAX];
|
||||
char source[64];
|
||||
snprintf(source, sizeof(source), "led-controller %.48s", o->name);
|
||||
o->seq++;
|
||||
for (size_t off = 0, u = 0; off < len; off += UNIVERSE_BYTES, u++) {
|
||||
size_t n = len - off < UNIVERSE_BYTES ? len - off : UNIVERSE_BYTES;
|
||||
int uni = o->universe + u;
|
||||
size_t total = 126 + n;
|
||||
memset(pkt, 0, 126);
|
||||
put16(pkt, 0x0010);
|
||||
memcpy(pkt + 4, "ASC-E1.17\0\0\0", 12);
|
||||
put16(pkt + 16, 0x7000 | (total - 16));
|
||||
pkt[21] = 0x04;
|
||||
memcpy(pkt + 22, o->cid, 16);
|
||||
put16(pkt + 38, 0x7000 | (total - 38));
|
||||
pkt[43] = 0x02;
|
||||
snprintf((char *)pkt + 44, 64, "led-controller %.48s", o->name);
|
||||
pkt[108] = 100;
|
||||
pkt[111] = o->seq;
|
||||
put16(pkt + 113, uni);
|
||||
put16(pkt + 115, 0x7000 | (total - 115));
|
||||
pkt[117] = 0x02;
|
||||
pkt[118] = 0xA1;
|
||||
put16(pkt + 121, 0x0001);
|
||||
put16(pkt + 123, n + 1);
|
||||
memcpy(pkt + 126, data + off, n);
|
||||
if (!o->host[0]) {
|
||||
o->to.sin_addr.s_addr = htonl(0xEFFF0000 | (uni & 0xFFFF));
|
||||
o->to.sin_addr.s_addr = htonl(dmx_sacn_group(uni));
|
||||
}
|
||||
send_pkt(o, pkt, total);
|
||||
send_pkt(o, pkt, dmx_sacn_packet(pkt, o->cid, source, o->seq, uni, data + off, n));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+40
-7
@@ -18,6 +18,8 @@
|
||||
#include "store.h"
|
||||
#include "wifi_drv.h"
|
||||
|
||||
static const char *TAG = "devices";
|
||||
|
||||
#define IDENTIFY_OFF_MS 2000
|
||||
|
||||
// Trimmed copy of a string field; false when missing or blank
|
||||
@@ -189,8 +191,11 @@ static esp_err_t create_device(httpd_req_t *req)
|
||||
return api_json(req, "201 Created", o, true);
|
||||
}
|
||||
|
||||
// Settings a driver keeps in its own settings.json and takes from a device_config message
|
||||
static const char *const DEVICE_CONFIG_KEYS[] = { "name", "max_brightness", "num_leds", "color_order", "startup_mode", "reversed" };
|
||||
// Settings a driver keeps in its own settings.json and takes from a device_config message. "pin" (the strip's
|
||||
// data GPIO) and "espnow_channel" (the driver restarts onto it) are what the bare ESP-NOW driver adds: with no
|
||||
// web interface or USB config, this is how its settings are changed. Drivers announce them back.
|
||||
static const char *const DEVICE_CONFIG_KEYS[] = { "name", "max_brightness", "num_leds", "color_order", "startup_mode", "reversed",
|
||||
"pin", "espnow_channel" };
|
||||
|
||||
// The driver settings present in a device update, or NULL when it has none. Caller deletes the result.
|
||||
static cJSON *device_config_from(const cJSON *body)
|
||||
@@ -666,19 +671,47 @@ static esp_err_t ping_devices(httpd_req_t *req)
|
||||
}
|
||||
uint8_t pkt[6] = { 0x4C, 0x05, id & 255, (id >> 8) & 255, (id >> 16) & 255, id >> 24 };
|
||||
esp_err_t err = ESP_OK;
|
||||
if (unicast) { // one acked frame to each known device
|
||||
if (unicast) { // one frame to each known device
|
||||
// The MACs are collected under the lock and sent after it: there are often more devices than the send queue
|
||||
// holds, so a full queue is waited on rather than failing the ping, and HTTP must not wait meanwhile.
|
||||
int nmac = 0;
|
||||
uint8_t(*macs)[6] = malloc((size_t)cJSON_GetArraySize(store_coll("device")) * 6 + 6);
|
||||
if (!macs) {
|
||||
err = ESP_ERR_NO_MEM;
|
||||
}
|
||||
cJSON *d;
|
||||
cJSON_ArrayForEach(d, store_coll("device"))
|
||||
{
|
||||
unsigned m[6];
|
||||
const cJSON *tr = cJSON_GetObjectItem(d, "transport");
|
||||
bool wifi = cJSON_IsString(tr) && !strcmp(tr->valuestring, "wifi"); // ids are hostnames, not MACs
|
||||
if (!wifi && d->string && sscanf(d->string, "%2x%2x%2x%2x%2x%2x", &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) == 6) {
|
||||
uint8_t mac[6] = { m[0], m[1], m[2], m[3], m[4], m[5] };
|
||||
esp_err_t e = espnow_tx_send(mac, pkt, sizeof(pkt));
|
||||
err = e != ESP_OK ? e : err;
|
||||
if (macs && !wifi && d->string &&
|
||||
sscanf(d->string, "%2x%2x%2x%2x%2x%2x", &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) == 6) {
|
||||
for (int k = 0; k < 6; k++) {
|
||||
macs[nmac][k] = (uint8_t)m[k];
|
||||
}
|
||||
nmac++;
|
||||
}
|
||||
}
|
||||
if (macs) {
|
||||
store_unlock();
|
||||
int sent = 0;
|
||||
for (int i = 0; i < nmac; i++) {
|
||||
esp_err_t e = espnow_tx_send(macs[i], pkt, sizeof(pkt));
|
||||
for (int tries = 0; e == ESP_ERR_NO_MEM && tries < 100; tries++) { // up to 0.5 s for room
|
||||
vTaskDelay(pdMS_TO_TICKS(5));
|
||||
e = espnow_tx_send(macs[i], pkt, sizeof(pkt));
|
||||
}
|
||||
sent += e == ESP_OK;
|
||||
if (e != ESP_OK) {
|
||||
ESP_LOGW(TAG, "ping: no send to %02x%02x%02x%02x%02x%02x: %s", macs[i][0], macs[i][1], macs[i][2],
|
||||
macs[i][3], macs[i][4], macs[i][5], esp_err_to_name(e));
|
||||
}
|
||||
}
|
||||
store_lock();
|
||||
free(macs);
|
||||
err = (nmac == 0 || sent > 0) ? ESP_OK : ESP_FAIL; // a few unsent frames only cost those replies
|
||||
}
|
||||
} else {
|
||||
err = espnow_tx_send(NULL, pkt, sizeof(pkt));
|
||||
vTaskDelay(pdMS_TO_TICKS(20));
|
||||
|
||||
+669
@@ -0,0 +1,669 @@
|
||||
// DMX definitions and DMX bridges (see bridge_dmx.h).
|
||||
// /dmx-definitions {name, manufacturer, model, mode, channels: [names], defaults: {name: value}}: the format of the
|
||||
// rig sim's room "dmx_definitions". The sim's two presets are seeded when there are none.
|
||||
// /dmx-bridges {name, universes: [{id, name, number, outputs: [...], fixtures: [...]}]}. A fixture without a
|
||||
// MAC gets a new one (locally administered, unique). Saving a running bridge applies at once;
|
||||
// deleting one also takes it off the running bridges.
|
||||
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "api_util.h"
|
||||
#include "bridge.h"
|
||||
#include "dmx_wire.h"
|
||||
#include "esp_random.h"
|
||||
#include "store.h"
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
#include "bridge_dmx.h"
|
||||
#endif
|
||||
|
||||
#define NAME_MAX_LEN 64
|
||||
#define UNIVERSES_MAX 32
|
||||
#define OUTPUTS_MAX 8
|
||||
#define FIXTURES_MAX 128 // per universe
|
||||
|
||||
/* ------------------------------------------------------------ definitions */
|
||||
|
||||
static const char *const BCC145[] = { "Dimmer", "Strobe", "Red", "Green", "Blue", "White", "Macro", "Speed" };
|
||||
static const char *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",
|
||||
};
|
||||
|
||||
static cJSON *make_def(const char *name, const char *maker, const char *model, const char *mode,
|
||||
const char *const *chans, size_t n)
|
||||
{
|
||||
cJSON *d = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(d, "name", name);
|
||||
cJSON_AddStringToObject(d, "manufacturer", maker);
|
||||
cJSON_AddStringToObject(d, "model", model);
|
||||
cJSON_AddStringToObject(d, "mode", mode);
|
||||
cJSON_AddItemToObject(d, "channels", cJSON_CreateStringArray(chans, (int)n));
|
||||
cJSON_AddObjectToObject(d, "defaults");
|
||||
return d;
|
||||
}
|
||||
|
||||
void dmx_seed_definitions(void)
|
||||
{
|
||||
if (store_coll("dmx_definition")->child) {
|
||||
return;
|
||||
}
|
||||
char id[16];
|
||||
api_add("dmx_definition", make_def("beamZ BCC145", "beamZ", "BCC145", "8 Channel", BCC145, 8), id, sizeof(id));
|
||||
api_add("dmx_definition",
|
||||
make_def("Small Eye 7 Mover", "Small Eye 7", "Mover", "43 Channel", MOVER_43,
|
||||
sizeof(MOVER_43) / sizeof(MOVER_43[0])),
|
||||
id, sizeof(id));
|
||||
store_save("dmx_definition");
|
||||
}
|
||||
|
||||
// Trimmed string field into buf; "" when missing
|
||||
static void text(const cJSON *obj, const char *key, char *buf, size_t len)
|
||||
{
|
||||
const cJSON *v = cJSON_GetObjectItem(obj, key);
|
||||
const char *s = cJSON_IsString(v) ? v->valuestring : "";
|
||||
while (isspace((unsigned char)*s)) {
|
||||
s++;
|
||||
}
|
||||
snprintf(buf, len, "%s", s);
|
||||
for (int i = (int)strlen(buf) - 1; i >= 0 && isspace((unsigned char)buf[i]); i--) {
|
||||
buf[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
static bool int_of(const cJSON *v, int *out)
|
||||
{
|
||||
if (cJSON_IsNumber(v) && v->valuedouble == (int)v->valuedouble) {
|
||||
*out = (int)v->valuedouble;
|
||||
return true;
|
||||
}
|
||||
if (cJSON_IsString(v) && v->valuestring[0]) {
|
||||
char *end;
|
||||
long n = strtol(v->valuestring, &end, 10);
|
||||
if (!*end) {
|
||||
*out = (int)n;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static cJSON *validate_def(const cJSON *data, char *err, size_t elen)
|
||||
{
|
||||
cJSON *d = cJSON_CreateObject();
|
||||
char buf[NAME_MAX_LEN];
|
||||
text(data, "name", buf, sizeof(buf));
|
||||
if (!buf[0]) {
|
||||
snprintf(err, elen, "name is required");
|
||||
goto fail;
|
||||
}
|
||||
cJSON_AddStringToObject(d, "name", buf);
|
||||
static const char *const META[] = { "manufacturer", "model", "mode" };
|
||||
for (size_t i = 0; i < 3; i++) {
|
||||
text(data, META[i], buf, sizeof(buf));
|
||||
cJSON_AddStringToObject(d, META[i], buf);
|
||||
}
|
||||
const cJSON *chans = cJSON_GetObjectItem(data, "channels");
|
||||
if (!cJSON_IsArray(chans) || !cJSON_GetArraySize(chans) || cJSON_GetArraySize(chans) > DMX_CHANNELS) {
|
||||
snprintf(err, elen, "channels must be a list of 1 to %d names", DMX_CHANNELS);
|
||||
goto fail;
|
||||
}
|
||||
cJSON *out = cJSON_AddArrayToObject(d, "channels");
|
||||
const cJSON *c;
|
||||
cJSON_ArrayForEach(c, chans)
|
||||
{
|
||||
char name[48] = "";
|
||||
if (cJSON_IsString(c)) {
|
||||
const char *s = c->valuestring;
|
||||
while (isspace((unsigned char)*s)) {
|
||||
s++;
|
||||
}
|
||||
snprintf(name, sizeof(name), "%s", s);
|
||||
for (int i = (int)strlen(name) - 1; i >= 0 && isspace((unsigned char)name[i]); i--) {
|
||||
name[i] = 0;
|
||||
}
|
||||
}
|
||||
if (!name[0]) {
|
||||
snprintf(err, elen, "channel %d has no name", cJSON_GetArraySize(out) + 1);
|
||||
goto fail;
|
||||
}
|
||||
cJSON_AddItemToArray(out, cJSON_CreateString(name));
|
||||
}
|
||||
cJSON *defs = cJSON_AddObjectToObject(d, "defaults");
|
||||
const cJSON *dv;
|
||||
cJSON_ArrayForEach(dv, cJSON_GetObjectItem(data, "defaults"))
|
||||
{
|
||||
int v;
|
||||
if (!int_of(dv, &v) || v < 0 || v > 255) {
|
||||
snprintf(err, elen, "default of %.40s must be 0 to 255", dv->string);
|
||||
goto fail;
|
||||
}
|
||||
cJSON_AddNumberToObject(defs, dv->string, v);
|
||||
}
|
||||
return d;
|
||||
fail:
|
||||
cJSON_Delete(d);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// The bridges and fixtures using definition def_id: a description of the first, or false
|
||||
static bool def_in_use(const char *def_id, char *who, size_t n)
|
||||
{
|
||||
const cJSON *b;
|
||||
cJSON_ArrayForEach(b, store_coll("dmx_bridge"))
|
||||
{
|
||||
const cJSON *u;
|
||||
cJSON_ArrayForEach(u, cJSON_GetObjectItem(b, "universes"))
|
||||
{
|
||||
const cJSON *f;
|
||||
cJSON_ArrayForEach(f, cJSON_GetObjectItem(u, "fixtures"))
|
||||
{
|
||||
const cJSON *d = cJSON_GetObjectItem(f, "definition");
|
||||
if (cJSON_IsString(d) && !strcmp(d->valuestring, def_id)) {
|
||||
const cJSON *fn = cJSON_GetObjectItem(f, "name"), *bn = cJSON_GetObjectItem(b, "name");
|
||||
snprintf(who, n, "fixture %s of bridge %s", cJSON_IsString(fn) ? fn->valuestring : "?",
|
||||
cJSON_IsString(bn) ? bn->valuestring : b->string);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static void reload_bridges_using(const char *def_id)
|
||||
{
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
const cJSON *b;
|
||||
cJSON_ArrayForEach(b, store_coll("dmx_bridge"))
|
||||
{
|
||||
const cJSON *u;
|
||||
bool uses = false;
|
||||
cJSON_ArrayForEach(u, cJSON_GetObjectItem(b, "universes"))
|
||||
{
|
||||
const cJSON *f;
|
||||
cJSON_ArrayForEach(f, cJSON_GetObjectItem(u, "fixtures"))
|
||||
{
|
||||
const cJSON *d = cJSON_GetObjectItem(f, "definition");
|
||||
uses = uses || (cJSON_IsString(d) && !strcmp(d->valuestring, def_id));
|
||||
}
|
||||
}
|
||||
if (uses) {
|
||||
bridge_dmx_reload(b->string);
|
||||
}
|
||||
}
|
||||
#else
|
||||
(void)def_id;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool dmx_definitions_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret)
|
||||
{
|
||||
const int method = req->method;
|
||||
cJSON *all = store_coll("dmx_definition");
|
||||
char err[128];
|
||||
if (method == HTTP_GET || n > 2) {
|
||||
return false; // reads (and unknown actions) are the generic collection's
|
||||
}
|
||||
if (n == 1 && method == HTTP_POST) {
|
||||
cJSON *body = api_body(req);
|
||||
if (!body) {
|
||||
*ret = ESP_OK;
|
||||
return true;
|
||||
}
|
||||
cJSON *d = validate_def(body, err, sizeof(err));
|
||||
cJSON_Delete(body);
|
||||
if (!d) {
|
||||
*ret = api_error(req, "400 Bad Request", err);
|
||||
return true;
|
||||
}
|
||||
char id[16];
|
||||
api_add("dmx_definition", d, id, sizeof(id));
|
||||
store_save("dmx_definition");
|
||||
*ret = api_json(req, "201 Created", d, false);
|
||||
return true;
|
||||
}
|
||||
if (n != 2) {
|
||||
return false;
|
||||
}
|
||||
cJSON *rec = cJSON_GetObjectItem(all, seg[1]);
|
||||
if (!rec) {
|
||||
*ret = api_error(req, "404 Not Found", "DMX definition not found");
|
||||
return true;
|
||||
}
|
||||
if (method == HTTP_DELETE) {
|
||||
char who[160];
|
||||
if (def_in_use(seg[1], who, sizeof(who))) {
|
||||
snprintf(err, sizeof(err), "the definition is in use (%.100s)", who);
|
||||
*ret = api_error(req, "409 Conflict", err);
|
||||
return true;
|
||||
}
|
||||
cJSON_DeleteItemFromObject(all, seg[1]);
|
||||
store_save("dmx_definition");
|
||||
*ret = api_message(req, "200 OK", "Deleted");
|
||||
return true;
|
||||
}
|
||||
if (method != HTTP_PUT) {
|
||||
return false;
|
||||
}
|
||||
cJSON *body = api_body(req);
|
||||
if (!body) {
|
||||
*ret = ESP_OK;
|
||||
return true;
|
||||
}
|
||||
cJSON *merged = cJSON_Duplicate(rec, true);
|
||||
api_merge(merged, body);
|
||||
cJSON_Delete(body);
|
||||
cJSON *d = validate_def(merged, err, sizeof(err));
|
||||
cJSON_Delete(merged);
|
||||
if (!d) {
|
||||
*ret = api_error(req, "400 Bad Request", err);
|
||||
return true;
|
||||
}
|
||||
// A fixture must still fit in its universe with the new channel count
|
||||
int nch = cJSON_GetArraySize(cJSON_GetObjectItem(d, "channels"));
|
||||
const cJSON *b;
|
||||
cJSON_ArrayForEach(b, store_coll("dmx_bridge"))
|
||||
{
|
||||
const cJSON *u;
|
||||
cJSON_ArrayForEach(u, cJSON_GetObjectItem(b, "universes"))
|
||||
{
|
||||
const cJSON *f;
|
||||
cJSON_ArrayForEach(f, cJSON_GetObjectItem(u, "fixtures"))
|
||||
{
|
||||
const cJSON *dd = cJSON_GetObjectItem(f, "definition");
|
||||
const cJSON *a = cJSON_GetObjectItem(f, "address");
|
||||
if (cJSON_IsString(dd) && !strcmp(dd->valuestring, seg[1]) && cJSON_IsNumber(a) &&
|
||||
a->valueint + nch - 1 > DMX_CHANNELS) {
|
||||
cJSON_Delete(d);
|
||||
snprintf(err, sizeof(err), "%d channels from address %d of a fixture using it pass channel 512",
|
||||
nch, a->valueint);
|
||||
*ret = api_error(req, "400 Bad Request", err);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
api_set(d, "id", cJSON_CreateString(seg[1]));
|
||||
cJSON_ReplaceItemInObject(all, seg[1], d);
|
||||
store_save("dmx_definition");
|
||||
reload_bridges_using(seg[1]);
|
||||
*ret = api_json(req, "200 OK", d, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- bridges */
|
||||
|
||||
static bool mac_taken(const char *mac, const char *self_bridge, const cJSON *mine)
|
||||
{
|
||||
// Fixtures of the other bridges
|
||||
const cJSON *b;
|
||||
cJSON_ArrayForEach(b, store_coll("dmx_bridge"))
|
||||
{
|
||||
if (self_bridge && !strcmp(b->string, self_bridge)) {
|
||||
continue;
|
||||
}
|
||||
const cJSON *u;
|
||||
cJSON_ArrayForEach(u, cJSON_GetObjectItem(b, "universes"))
|
||||
{
|
||||
const cJSON *f;
|
||||
cJSON_ArrayForEach(f, cJSON_GetObjectItem(u, "fixtures"))
|
||||
{
|
||||
const cJSON *m = cJSON_GetObjectItem(f, "mac");
|
||||
if (cJSON_IsString(m) && !strcmp(m->valuestring, mac)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// This bridge's fixtures checked so far
|
||||
const cJSON *u;
|
||||
cJSON_ArrayForEach(u, cJSON_GetObjectItem(mine, "universes"))
|
||||
{
|
||||
const cJSON *f;
|
||||
cJSON_ArrayForEach(f, cJSON_GetObjectItem(u, "fixtures"))
|
||||
{
|
||||
const cJSON *m = cJSON_GetObjectItem(f, "mac");
|
||||
if (cJSON_IsString(m) && !strcmp(m->valuestring, mac)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A real driver with that MAC (a device that is not a DMX fixture)
|
||||
const cJSON *dev = cJSON_GetObjectItem(store_coll("device"), mac);
|
||||
return dev && !cJSON_IsTrue(cJSON_GetObjectItem(dev, "dmx_fixture"));
|
||||
}
|
||||
|
||||
static void new_mac(char out[13], const char *self_bridge, const cJSON *mine)
|
||||
{
|
||||
do {
|
||||
uint8_t m[6];
|
||||
uint32_t a = esp_random(), b = esp_random();
|
||||
m[0] = 0x02; // locally administered, unicast
|
||||
m[1] = a;
|
||||
m[2] = a >> 8;
|
||||
m[3] = a >> 16;
|
||||
m[4] = b;
|
||||
m[5] = b >> 8;
|
||||
snprintf(out, 13, "%02x%02x%02x%02x%02x%02x", m[0], m[1], m[2], m[3], m[4], m[5]);
|
||||
} while (mac_taken(out, self_bridge, mine));
|
||||
}
|
||||
|
||||
static cJSON *validate_output(const cJSON *o, int number, char *err, size_t elen)
|
||||
{
|
||||
cJSON *out = cJSON_CreateObject();
|
||||
char type[16], buf[96];
|
||||
text(o, "type", type, sizeof(type));
|
||||
for (char *c = type; *c; c++) {
|
||||
*c = (char)tolower((unsigned char)*c);
|
||||
}
|
||||
if (!type[0]) {
|
||||
snprintf(type, sizeof(type), "artnet");
|
||||
}
|
||||
if (strcmp(type, "artnet") && strcmp(type, "sacn") && strcmp(type, "dmx_serial") && strcmp(type, "sim")) {
|
||||
snprintf(err, elen, "output type must be artnet, sacn, dmx_serial or sim");
|
||||
goto fail;
|
||||
}
|
||||
cJSON_AddStringToObject(out, "type", type);
|
||||
// sim: the universe goes to the rig simulator inside this process (no host or port; Art-Net numbering)
|
||||
bool serial = !strcmp(type, "dmx_serial"), sacn = !strcmp(type, "sacn"), sim = !strcmp(type, "sim");
|
||||
text(o, "host", buf, sizeof(buf));
|
||||
cJSON_AddStringToObject(out, "host", serial || sim ? "" : buf);
|
||||
const cJSON *pv = cJSON_GetObjectItem(o, "port");
|
||||
int port;
|
||||
if (serial || sim || !pv || cJSON_IsNull(pv) || (cJSON_IsString(pv) && !pv->valuestring[0])) {
|
||||
cJSON_AddNullToObject(out, "port");
|
||||
} else if (!int_of(pv, &port) || port < 1 || port > 65535) {
|
||||
snprintf(err, elen, "port must be 1 to 65535");
|
||||
goto fail;
|
||||
} else {
|
||||
cJSON_AddNumberToObject(out, "port", port);
|
||||
}
|
||||
const cJSON *uv = cJSON_GetObjectItem(o, "universe");
|
||||
int uni = number;
|
||||
if (!uv || cJSON_IsNull(uv) || (cJSON_IsString(uv) && !uv->valuestring[0])) {
|
||||
cJSON_AddNullToObject(out, "universe");
|
||||
} else if (!int_of(uv, &uni)) {
|
||||
snprintf(err, elen, "an output's universe must be a number");
|
||||
goto fail;
|
||||
} else {
|
||||
cJSON_AddNumberToObject(out, "universe", uni);
|
||||
}
|
||||
if (!serial && sacn && (uni < 1 || uni > 63999)) {
|
||||
snprintf(err, elen, "sACN universe must be 1 to 63999 (this output sends %d)", uni);
|
||||
goto fail;
|
||||
}
|
||||
if (!serial && !sacn && (uni < 0 || uni > 32767)) {
|
||||
snprintf(err, elen, "%s universe must be 0 to 32767 (this output sends %d)", sim ? "Simulator" : "Art-Net", uni);
|
||||
goto fail;
|
||||
}
|
||||
text(o, "serial_port", buf, sizeof(buf));
|
||||
if (serial && !buf[0]) {
|
||||
snprintf(err, elen, "serial_port is required for dmx_serial");
|
||||
goto fail;
|
||||
}
|
||||
cJSON_AddStringToObject(out, "serial_port", serial ? buf : "");
|
||||
text(o, "dmx_mode", buf, sizeof(buf));
|
||||
if (!buf[0]) {
|
||||
snprintf(buf, sizeof(buf), "enttec_pro");
|
||||
}
|
||||
if (strcmp(buf, "enttec_pro") && strcmp(buf, "open_dmx")) {
|
||||
snprintf(err, elen, "dmx_mode must be enttec_pro or open_dmx");
|
||||
goto fail;
|
||||
}
|
||||
cJSON_AddStringToObject(out, "dmx_mode", buf);
|
||||
cJSON_AddBoolToObject(out, "enabled", !cJSON_IsFalse(cJSON_GetObjectItem(o, "enabled")));
|
||||
return out;
|
||||
fail:
|
||||
cJSON_Delete(out);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// The normalised record, or NULL with err set. self: the record's id (NULL for a new one).
|
||||
static cJSON *validate_bridge(const cJSON *data, const char *self, char *err, size_t elen)
|
||||
{
|
||||
cJSON *doc = cJSON_CreateObject();
|
||||
char buf[NAME_MAX_LEN];
|
||||
text(data, "name", buf, sizeof(buf));
|
||||
if (!buf[0]) {
|
||||
snprintf(err, elen, "name is required");
|
||||
goto fail;
|
||||
}
|
||||
cJSON_AddStringToObject(doc, "name", buf);
|
||||
const cJSON *ulist = cJSON_GetObjectItem(data, "universes");
|
||||
if (ulist && !cJSON_IsNull(ulist) && !cJSON_IsArray(ulist)) {
|
||||
snprintf(err, elen, "universes must be a list");
|
||||
goto fail;
|
||||
}
|
||||
if (cJSON_GetArraySize(ulist) > UNIVERSES_MAX) {
|
||||
snprintf(err, elen, "a bridge has at most %d universes", UNIVERSES_MAX);
|
||||
goto fail;
|
||||
}
|
||||
cJSON *unis = cJSON_AddArrayToObject(doc, "universes");
|
||||
const cJSON *defs = store_coll("dmx_definition");
|
||||
int next_u = 1, next_f = 1;
|
||||
// ids already given keep; new ones count up past the largest
|
||||
const cJSON *u;
|
||||
cJSON_ArrayForEach(u, ulist)
|
||||
{
|
||||
char id[16];
|
||||
text(u, "id", id, sizeof(id));
|
||||
if (id[0] == 'u' && atoi(id + 1) >= next_u) {
|
||||
next_u = atoi(id + 1) + 1;
|
||||
}
|
||||
const cJSON *f;
|
||||
cJSON_ArrayForEach(f, cJSON_GetObjectItem(u, "fixtures"))
|
||||
{
|
||||
text(f, "id", id, sizeof(id));
|
||||
if (id[0] == 'f' && atoi(id + 1) >= next_f) {
|
||||
next_f = atoi(id + 1) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
int ui = 0;
|
||||
cJSON_ArrayForEach(u, ulist)
|
||||
{
|
||||
ui++;
|
||||
cJSON *nu = cJSON_CreateObject();
|
||||
cJSON_AddItemToArray(unis, nu);
|
||||
char id[16];
|
||||
text(u, "id", id, sizeof(id));
|
||||
if (!id[0]) {
|
||||
snprintf(id, sizeof(id), "u%d", next_u++);
|
||||
}
|
||||
cJSON_AddStringToObject(nu, "id", id);
|
||||
text(u, "name", buf, sizeof(buf));
|
||||
if (!buf[0]) {
|
||||
snprintf(buf, sizeof(buf), "Universe %d", ui);
|
||||
}
|
||||
cJSON_AddStringToObject(nu, "name", buf);
|
||||
int number = ui - 1;
|
||||
const cJSON *nv = cJSON_GetObjectItem(u, "number");
|
||||
if (nv && !cJSON_IsNull(nv) && (!int_of(nv, &number) || number < 0 || number > 63999)) {
|
||||
snprintf(err, elen, "universe %s: number must be 0 to 63999", buf);
|
||||
goto fail;
|
||||
}
|
||||
cJSON_AddNumberToObject(nu, "number", number);
|
||||
const cJSON *olist = cJSON_GetObjectItem(u, "outputs");
|
||||
if (cJSON_GetArraySize(olist) > OUTPUTS_MAX) {
|
||||
snprintf(err, elen, "universe %s: at most %d outputs", buf, OUTPUTS_MAX);
|
||||
goto fail;
|
||||
}
|
||||
cJSON *outs = cJSON_AddArrayToObject(nu, "outputs");
|
||||
const cJSON *o;
|
||||
cJSON_ArrayForEach(o, olist)
|
||||
{
|
||||
char oerr[96];
|
||||
cJSON *no = validate_output(o, number, oerr, sizeof(oerr));
|
||||
if (!no) {
|
||||
snprintf(err, elen, "universe %.40s: %s", buf, oerr);
|
||||
goto fail;
|
||||
}
|
||||
cJSON_AddItemToArray(outs, no);
|
||||
}
|
||||
const cJSON *flist = cJSON_GetObjectItem(u, "fixtures");
|
||||
if (cJSON_GetArraySize(flist) > FIXTURES_MAX) {
|
||||
snprintf(err, elen, "universe %s: at most %d fixtures", buf, FIXTURES_MAX);
|
||||
goto fail;
|
||||
}
|
||||
cJSON *fixtures = cJSON_AddArrayToObject(nu, "fixtures");
|
||||
uint8_t owner[DMX_CHANNELS + 1] = { 0 }; // which fixture (1-based, in this universe) holds each channel
|
||||
int fi = 0;
|
||||
const cJSON *f;
|
||||
cJSON_ArrayForEach(f, flist)
|
||||
{
|
||||
fi++;
|
||||
cJSON *nf = cJSON_CreateObject();
|
||||
char fid[16], fname[NAME_MAX_LEN], def_id[24];
|
||||
text(f, "id", fid, sizeof(fid));
|
||||
if (!fid[0]) {
|
||||
snprintf(fid, sizeof(fid), "f%d", next_f++);
|
||||
}
|
||||
text(f, "name", fname, sizeof(fname));
|
||||
if (!fname[0]) {
|
||||
cJSON_Delete(nf);
|
||||
snprintf(err, elen, "universe %s: fixture %d needs a name", buf, fi);
|
||||
goto fail;
|
||||
}
|
||||
text(f, "definition", def_id, sizeof(def_id));
|
||||
if (!def_id[0] && cJSON_IsNumber(cJSON_GetObjectItem(f, "definition"))) {
|
||||
snprintf(def_id, sizeof(def_id), "%d", cJSON_GetObjectItem(f, "definition")->valueint);
|
||||
}
|
||||
const cJSON *def = cJSON_GetObjectItem(defs, def_id);
|
||||
if (!def) {
|
||||
cJSON_Delete(nf);
|
||||
snprintf(err, elen, "fixture %s: no such DMX definition", fname);
|
||||
goto fail;
|
||||
}
|
||||
int nch = cJSON_GetArraySize(cJSON_GetObjectItem(def, "channels"));
|
||||
int addr;
|
||||
if (!int_of(cJSON_GetObjectItem(f, "address"), &addr) || addr < 1 || addr > DMX_CHANNELS) {
|
||||
cJSON_Delete(nf);
|
||||
snprintf(err, elen, "fixture %s: address must be 1 to 512", fname);
|
||||
goto fail;
|
||||
}
|
||||
if (addr + nch - 1 > DMX_CHANNELS) {
|
||||
cJSON_Delete(nf);
|
||||
snprintf(err, elen, "fixture %s: %d channels from address %d pass channel 512", fname, nch, addr);
|
||||
goto fail;
|
||||
}
|
||||
for (int c = addr; c < addr + nch; c++) {
|
||||
if (owner[c]) {
|
||||
const cJSON *other = cJSON_GetArrayItem(fixtures, owner[c] - 1);
|
||||
cJSON_Delete(nf);
|
||||
snprintf(err, elen, "fixture %s: channel %d is already used by %s", fname, c,
|
||||
cJSON_GetObjectItem(other, "name")->valuestring);
|
||||
goto fail;
|
||||
}
|
||||
owner[c] = (uint8_t)fi;
|
||||
}
|
||||
const cJSON *mv = cJSON_GetObjectItem(f, "mac");
|
||||
char mac[13];
|
||||
if (!mv || cJSON_IsNull(mv) || (cJSON_IsString(mv) && !mv->valuestring[0])) {
|
||||
new_mac(mac, self, doc);
|
||||
} else if (!api_mac(mv, mac)) {
|
||||
cJSON_Delete(nf);
|
||||
snprintf(err, elen, "fixture %s: mac must be 12 hex digits", fname);
|
||||
goto fail;
|
||||
} else {
|
||||
int first = (int)strtol((char[3]){ mac[0], mac[1], 0 }, NULL, 16);
|
||||
if ((first & 1) || !strcmp(mac, "000000000000")) {
|
||||
cJSON_Delete(nf);
|
||||
snprintf(err, elen, "fixture %s: mac must be a unicast address, not zero", fname);
|
||||
goto fail;
|
||||
}
|
||||
if (mac_taken(mac, self, doc)) {
|
||||
cJSON_Delete(nf);
|
||||
snprintf(err, elen, "fixture %s: mac %s is already used by another fixture or driver", fname, mac);
|
||||
goto fail;
|
||||
}
|
||||
}
|
||||
cJSON_AddStringToObject(nf, "id", fid);
|
||||
cJSON_AddStringToObject(nf, "name", fname);
|
||||
cJSON_AddStringToObject(nf, "mac", mac);
|
||||
cJSON_AddStringToObject(nf, "definition", def_id);
|
||||
cJSON_AddNumberToObject(nf, "address", addr);
|
||||
cJSON_AddItemToArray(fixtures, nf);
|
||||
}
|
||||
}
|
||||
return doc;
|
||||
fail:
|
||||
cJSON_Delete(doc);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
bool dmx_bridges_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret)
|
||||
{
|
||||
const int method = req->method;
|
||||
cJSON *all = store_coll("dmx_bridge");
|
||||
char err[160];
|
||||
if (method == HTTP_GET || n > 2) {
|
||||
return false;
|
||||
}
|
||||
if (n == 1 && method == HTTP_POST) {
|
||||
cJSON *body = api_body(req);
|
||||
if (!body) {
|
||||
*ret = ESP_OK;
|
||||
return true;
|
||||
}
|
||||
cJSON *doc = validate_bridge(body, NULL, err, sizeof(err));
|
||||
cJSON_Delete(body);
|
||||
if (!doc) {
|
||||
*ret = api_error(req, "400 Bad Request", err);
|
||||
return true;
|
||||
}
|
||||
char id[16];
|
||||
api_add("dmx_bridge", doc, id, sizeof(id));
|
||||
store_save("dmx_bridge");
|
||||
*ret = api_json(req, "201 Created", doc, false);
|
||||
return true;
|
||||
}
|
||||
if (n != 2) {
|
||||
return false;
|
||||
}
|
||||
cJSON *rec = cJSON_GetObjectItem(all, seg[1]);
|
||||
if (!rec) {
|
||||
*ret = api_error(req, "404 Not Found", "DMX bridge not found");
|
||||
return true;
|
||||
}
|
||||
char addr[BRIDGE_ADDR_MAX];
|
||||
snprintf(addr, sizeof(addr), "dmx:%s", seg[1]);
|
||||
if (method == HTTP_DELETE) {
|
||||
cJSON_DeleteItemFromObject(all, seg[1]);
|
||||
store_save("dmx_bridge");
|
||||
api_bridges_remove(addr);
|
||||
*ret = api_message(req, "200 OK", "Deleted");
|
||||
return true;
|
||||
}
|
||||
if (method != HTTP_PUT) {
|
||||
return false;
|
||||
}
|
||||
cJSON *body = api_body(req);
|
||||
if (!body) {
|
||||
*ret = ESP_OK;
|
||||
return true;
|
||||
}
|
||||
cJSON *merged = cJSON_Duplicate(rec, true);
|
||||
api_merge(merged, body);
|
||||
cJSON_Delete(body);
|
||||
cJSON *doc = validate_bridge(merged, seg[1], err, sizeof(err));
|
||||
cJSON_Delete(merged);
|
||||
if (!doc) {
|
||||
*ret = api_error(req, "400 Bad Request", err);
|
||||
return true;
|
||||
}
|
||||
api_set(doc, "id", cJSON_CreateString(seg[1]));
|
||||
cJSON_ReplaceItemInObject(all, seg[1], doc);
|
||||
store_save("dmx_bridge");
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
bridge_dmx_reload(seg[1]);
|
||||
#endif
|
||||
*ret = api_json(req, "200 OK", doc, false);
|
||||
return true;
|
||||
}
|
||||
@@ -292,6 +292,32 @@ static esp_err_t fire_sequence(httpd_req_t *req, const char *id)
|
||||
return api_json(req, "200 OK", o, true);
|
||||
}
|
||||
|
||||
// POST /sequences/<id>/preview {zone_id?}: play it on the simulated drivers only, alongside what plays live
|
||||
static esp_err_t preview_sequence(httpd_req_t *req, const char *id)
|
||||
{
|
||||
const char *profile = api_current_profile();
|
||||
if (!profile) {
|
||||
return api_error(req, "404 Not Found", "No profile available");
|
||||
}
|
||||
cJSON *body = api_body_opt(req);
|
||||
if (!body) {
|
||||
return ESP_OK;
|
||||
}
|
||||
char zone[24] = "";
|
||||
api_id(cJSON_GetObjectItem(body, "zone_id"), zone, sizeof(zone));
|
||||
cJSON_Delete(body);
|
||||
const char *msg;
|
||||
esp_err_t err = seqplay_preview(id, zone, profile, &msg);
|
||||
if (err != ESP_OK) {
|
||||
return api_error(req, err == ESP_ERR_NOT_FOUND ? "404 Not Found" : "400 Bad Request",
|
||||
msg ? msg : "sequence not found");
|
||||
}
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddTrueToObject(o, "ok");
|
||||
cJSON_AddStringToObject(o, "sequence_id", id);
|
||||
return api_json(req, "200 OK", o, true);
|
||||
}
|
||||
|
||||
bool sequences_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret)
|
||||
{
|
||||
cJSON *all = store_coll("sequence");
|
||||
@@ -341,6 +367,17 @@ bool sequences_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret)
|
||||
*ret = api_json(req, "200 OK", o, true);
|
||||
return true;
|
||||
}
|
||||
if (n == 3 && method == HTTP_POST && !strcmp(seg[1], "preview") && !strcmp(seg[2], "stop")) {
|
||||
seqplay_preview_stop();
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddTrueToObject(o, "ok");
|
||||
*ret = api_json(req, "200 OK", o, true);
|
||||
return true;
|
||||
}
|
||||
if (n == 3 && method == HTTP_POST && !strcmp(seg[2], "preview")) {
|
||||
*ret = preview_sequence(req, seg[1]);
|
||||
return true;
|
||||
}
|
||||
if (n == 3 && method == HTTP_POST && !strcmp(seg[2], "fire")) {
|
||||
*ret = fire_sequence(req, seg[1]);
|
||||
return true;
|
||||
|
||||
@@ -98,6 +98,57 @@ static esp_err_t send_presets(httpd_req_t *req)
|
||||
return api_json(req, "200 OK", o, true);
|
||||
}
|
||||
|
||||
// A preset that was saved goes to every driver, which keeps it: sequences then only select it
|
||||
static void push_saved(const char *id)
|
||||
{
|
||||
cJSON *ids = cJSON_CreateArray();
|
||||
cJSON_AddItemToArray(ids, cJSON_CreateString(id));
|
||||
engine_send_presets(ids, true, NULL, NULL, NULL);
|
||||
cJSON_Delete(ids);
|
||||
}
|
||||
|
||||
// POST /presets/sync: every preset of the current profile to every driver (broadcast), saved on each
|
||||
static esp_err_t sync_presets(httpd_req_t *req)
|
||||
{
|
||||
cJSON *ids = cJSON_CreateArray();
|
||||
const cJSON *it;
|
||||
cJSON_ArrayForEach(it, store_coll("preset"))
|
||||
{
|
||||
if (api_preset_in_profile(it)) {
|
||||
cJSON_AddItemToArray(ids, cJSON_CreateString(it->string));
|
||||
}
|
||||
}
|
||||
int sent = 0;
|
||||
esp_err_t err = ids->child ? engine_send_presets(ids, true, NULL, NULL, &sent) : ESP_ERR_NOT_FOUND;
|
||||
cJSON_Delete(ids);
|
||||
if (err != ESP_OK) {
|
||||
return api_result(req, err, "");
|
||||
}
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "message", "Presets synced to all drivers");
|
||||
cJSON_AddNumberToObject(o, "presets_sent", sent);
|
||||
return api_json(req, "200 OK", o, true);
|
||||
}
|
||||
|
||||
// POST /presets/clear: every driver deletes its stored presets (broadcast), the counterpart of Sync to Devices
|
||||
static esp_err_t clear_presets_all(httpd_req_t *req)
|
||||
{
|
||||
cJSON *msg = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(msg, "v", "1");
|
||||
cJSON_AddTrueToObject(msg, "clear_presets");
|
||||
cJSON_AddTrueToObject(msg, "save");
|
||||
cJSON *messages = cJSON_CreateArray();
|
||||
cJSON_AddItemToArray(messages, msg);
|
||||
esp_err_t err = engine_push(messages, NULL);
|
||||
cJSON_Delete(messages);
|
||||
if (err != ESP_OK) {
|
||||
return api_result(req, err, "");
|
||||
}
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "message", "Presets cleared on all drivers");
|
||||
return api_json(req, "200 OK", o, true);
|
||||
}
|
||||
|
||||
bool presets_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret)
|
||||
{
|
||||
const int method = req->method;
|
||||
@@ -109,6 +160,14 @@ bool presets_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret)
|
||||
*ret = send_presets(req);
|
||||
return true;
|
||||
}
|
||||
if (n == 2 && method == HTTP_POST && !strcmp(seg[1], "sync")) {
|
||||
*ret = sync_presets(req);
|
||||
return true;
|
||||
}
|
||||
if (n == 2 && method == HTTP_POST && !strcmp(seg[1], "clear")) {
|
||||
*ret = clear_presets_all(req);
|
||||
return true;
|
||||
}
|
||||
const char *profile = api_current_profile();
|
||||
if (n == 1 && method == HTTP_POST) {
|
||||
if (!profile) {
|
||||
@@ -127,6 +186,7 @@ bool presets_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret)
|
||||
char id[16];
|
||||
api_add("preset", rec, id, sizeof(id));
|
||||
store_save("preset");
|
||||
push_saved(id);
|
||||
*ret = send_keyed(req, "201 Created", id, rec);
|
||||
return true;
|
||||
}
|
||||
@@ -147,6 +207,7 @@ bool presets_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret)
|
||||
api_set(rec, "profile_id", cJSON_CreateString(profile));
|
||||
}
|
||||
store_save("preset");
|
||||
push_saved(seg[1]);
|
||||
*ret = api_json(req, "200 OK", rec, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
+174
-85
@@ -61,11 +61,11 @@ typedef struct {
|
||||
int norder; // the lane's targets in order (chase)
|
||||
bool chase, chase_off;
|
||||
int corder, width, pos, dir;
|
||||
char last[ID_MAX]; // preset last uploaded to the lane's targets
|
||||
} lane_t;
|
||||
|
||||
typedef struct {
|
||||
bool active, overlay;
|
||||
bool preview; // the editor's preview: plays to the simulated drivers only (seqplay_preview)
|
||||
char seq[ID_MAX], zone[ID_MAX], profile[ID_MAX];
|
||||
lane_t *lane;
|
||||
int nlanes;
|
||||
@@ -88,6 +88,7 @@ typedef struct {
|
||||
// Lanes and targets live in PSRAM, allocated by seqplay_init.
|
||||
static player_t s_base; // the sequence
|
||||
static player_t s_ovl; // a one-shot sequence over it
|
||||
static player_t s_prev; // a preview on the simulated drivers; while it plays, the others skip them
|
||||
static macs_t s_covered; // drivers the one-shot lights; the sequence's sends skip them
|
||||
static macs_t s_restore; // while set (n > 0), sends go only to these drivers
|
||||
static bool s_restoring;
|
||||
@@ -293,8 +294,59 @@ static uint32_t mask_of(const player_t *p, const cJSON *list, int nuser)
|
||||
return m;
|
||||
}
|
||||
|
||||
// Group ids for a target mask; while an animation plays over the sequence, or while drivers are being
|
||||
// restored after it, they become the drivers' own groups for just the drivers that may be sent to.
|
||||
// Which drivers a player may reach: the preview only the simulated ones; while a preview plays, the others
|
||||
// never the simulated ones
|
||||
static bool sim_ok(const player_t *p, const char *mac)
|
||||
{
|
||||
if (p->preview) {
|
||||
return engine_mac_is_sim(mac);
|
||||
}
|
||||
return !s_prev.active || !engine_mac_is_sim(mac);
|
||||
}
|
||||
|
||||
// Groups as the drivers' own d<mac> groups for just the drivers player p may send to. restoring_rules: also apply
|
||||
// the one-shot's rules (skip what it covers; while restoring, only the drivers being restored). Wi-Fi drivers
|
||||
// count by the MAC in their record, like ESP-NOW ones. A group with no sim driver in it stays a group while only
|
||||
// the preview's rule applies (members without a known MAC keep getting it).
|
||||
static cJSON *drivers_for(const player_t *p, cJSON *groups, bool restoring_rules)
|
||||
{
|
||||
const bool restoring = restoring_rules && s_restoring;
|
||||
const bool exclude = restoring_rules && p == &s_base && s_ovl.active && s_covered.n;
|
||||
const bool sim_rule = p->preview || s_prev.active;
|
||||
if (!restoring && !exclude && !sim_rule) {
|
||||
return groups;
|
||||
}
|
||||
cJSON *drivers = cJSON_CreateArray();
|
||||
const cJSON *g;
|
||||
cJSON_ArrayForEach(g, groups)
|
||||
{
|
||||
if (!restoring && !exclude && !p->preview && !engine_group_has_sim(g->valuestring)) {
|
||||
add_id(drivers, g->valuestring); // no simulated driver to leave out
|
||||
continue;
|
||||
}
|
||||
char macs[MACS_MAX][13];
|
||||
int n = engine_group_macs(g->valuestring, macs, MACS_MAX);
|
||||
if (!n && !restoring && !p->preview) { // no known members: nothing to leave out
|
||||
add_id(drivers, g->valuestring);
|
||||
}
|
||||
for (int i = 0; i < n; i++) {
|
||||
bool keep = restoring ? macs_has(&s_restore, macs[i]) : !exclude || !macs_has(&s_covered, macs[i]);
|
||||
if (keep && sim_rule) {
|
||||
keep = sim_ok(p, macs[i]);
|
||||
}
|
||||
if (keep) {
|
||||
char gid[GROUP_ID_MAX] = "d";
|
||||
memcpy(gid + 1, macs[i], 13); // 12 hex digits and the NUL
|
||||
add_id(drivers, gid);
|
||||
}
|
||||
}
|
||||
}
|
||||
cJSON_Delete(groups);
|
||||
return drivers;
|
||||
}
|
||||
|
||||
// Group ids for a target mask; while an animation plays over the sequence, while drivers are being restored
|
||||
// after it, or while a preview plays, they become the drivers' own groups for just the drivers that may be sent to.
|
||||
static cJSON *groups_for(const player_t *p, uint32_t mask)
|
||||
{
|
||||
cJSON *out = cJSON_CreateArray();
|
||||
@@ -305,30 +357,7 @@ static cJSON *groups_for(const player_t *p, uint32_t mask)
|
||||
}
|
||||
}
|
||||
}
|
||||
bool exclude = p == &s_base && s_ovl.active && s_covered.n;
|
||||
if (!s_restoring && !exclude) {
|
||||
return out;
|
||||
}
|
||||
cJSON *drivers = cJSON_CreateArray();
|
||||
const cJSON *g;
|
||||
cJSON_ArrayForEach(g, out)
|
||||
{
|
||||
char macs[MACS_MAX][13];
|
||||
int n = engine_group_macs(g->valuestring, macs, MACS_MAX);
|
||||
if (!n && !s_restoring) { // no known members: nothing to leave out
|
||||
add_id(drivers, g->valuestring);
|
||||
}
|
||||
for (int i = 0; i < n; i++) {
|
||||
bool keep = s_restoring ? macs_has(&s_restore, macs[i]) : !macs_has(&s_covered, macs[i]);
|
||||
if (keep) {
|
||||
char gid[GROUP_ID_MAX] = "d";
|
||||
memcpy(gid + 1, macs[i], 13); // 12 hex digits and the NUL
|
||||
add_id(drivers, gid);
|
||||
}
|
||||
}
|
||||
}
|
||||
cJSON_Delete(out);
|
||||
return drivers;
|
||||
return drivers_for(p, out, true);
|
||||
}
|
||||
|
||||
static void send_msg(cJSON *msg)
|
||||
@@ -368,24 +397,6 @@ static void upload(const player_t *p, uint32_t mask, cJSON *presets)
|
||||
send_msg(m);
|
||||
}
|
||||
|
||||
// Upload presets of steps [from, to) of a lane (each once) to all of the lane's targets
|
||||
static void send_presets(const player_t *p, int lane, int from, int to)
|
||||
{
|
||||
const lane_t *l = &p->lane[lane];
|
||||
cJSON *presets = cJSON_CreateObject();
|
||||
for (int i = from; i < to && i < l->n; i++) {
|
||||
const step_t *st = &l->step[i];
|
||||
if (st->anim || st->rest || !st->id[0] || cJSON_GetObjectItem(presets, st->id)) {
|
||||
continue;
|
||||
}
|
||||
cJSON *pl = engine_preset_payload(st->id);
|
||||
if (pl) {
|
||||
cJSON_AddItemToObject(presets, st->id, pl);
|
||||
}
|
||||
}
|
||||
upload(p, l->mask, presets);
|
||||
}
|
||||
|
||||
static void select_on(const player_t *p, uint32_t mask, const char *preset)
|
||||
{
|
||||
if (!mask) {
|
||||
@@ -448,17 +459,14 @@ static void send_lane(player_t *p, int lane)
|
||||
}
|
||||
const step_t *st = &l->step[l->idx];
|
||||
if (st->anim) {
|
||||
if (!p->overlay && !s_restoring) {
|
||||
if (!p->overlay && !p->preview && !s_restoring) { // a preview leaves the live one-shot alone
|
||||
fire(st->id, p->zone, p->profile, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
uint32_t lit = st->rest ? 0 : st->mask ? st->mask : l->chase ? chase_mask(l) : l->mask;
|
||||
// Presets are on the drivers already (sent when saved, or by a sync): a step only selects one
|
||||
if (lit && st->id[0]) {
|
||||
if (strcmp(l->last, st->id)) {
|
||||
send_presets(p, lane, l->idx, l->idx + 1);
|
||||
memcpy(l->last, st->id, ID_MAX);
|
||||
}
|
||||
select_on(p, lit, st->id);
|
||||
}
|
||||
if (st->rest || st->others_off || (l->chase && l->chase_off)) {
|
||||
@@ -611,7 +619,8 @@ static void anchor_bar(void)
|
||||
}
|
||||
|
||||
// Turn off what a sequence lit: its own targets only (they may lie outside its zone). Sequences never use the zone's
|
||||
// groups; those belong to presets played directly in a zone
|
||||
// groups; those belong to presets played directly in a zone. Selects the saved "off" preset rather than clearing the
|
||||
// drivers' preset stores, so the presets stay on the drivers for the next sequence or zone play
|
||||
static void clear_sequence(const player_t *p)
|
||||
{
|
||||
cJSON *groups = cJSON_CreateArray();
|
||||
@@ -624,10 +633,10 @@ static void clear_sequence(const player_t *p)
|
||||
cJSON_Delete(groups);
|
||||
return;
|
||||
}
|
||||
cJSON *m = message(groups);
|
||||
cJSON *m = message(drivers_for(p, groups, false));
|
||||
if (m) {
|
||||
cJSON_AddTrueToObject(m, "clear_presets");
|
||||
cJSON_AddTrueToObject(m, "save");
|
||||
cJSON *sel = cJSON_AddArrayToObject(m, "select");
|
||||
cJSON_AddItemToArray(sel, cJSON_CreateString("off"));
|
||||
send_msg(m);
|
||||
}
|
||||
}
|
||||
@@ -661,13 +670,15 @@ static void zone_brightness(const char *zone_id)
|
||||
char m[MACS_MAX][13];
|
||||
int k = engine_group_macs(t[i], m, MACS_MAX);
|
||||
for (int j = 0; j < k; j++) {
|
||||
macs_add(&macs, m[j]);
|
||||
if (!engine_mac_is_wifi(m[j])) { // Wi-Fi drivers get theirs by hostname below
|
||||
macs_add(&macs, m[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < macs.n; i++) {
|
||||
zone_brightness_push(macs.m[i], zone_b);
|
||||
}
|
||||
// Wi-Fi drivers are listed by hostname, so they are not among the MACs above
|
||||
// Wi-Fi drivers, by hostname (those with a MAC were left out above)
|
||||
char w[MACS_MAX][GROUP_ID_MAX];
|
||||
int nw = engine_zone_wifi_ids(zone_id, w, MACS_MAX);
|
||||
for (int i = 0; i < nw; i++) {
|
||||
@@ -709,23 +720,10 @@ static esp_err_t load(player_t *p, const char *seq_id, const char *zone_id, cons
|
||||
l->t0 = now + (l->timed ? l->t0 : 0);
|
||||
l->started = l->timed ? l->t0 <= now : l->wait == 0;
|
||||
}
|
||||
// Step-0 presets of the lanes that start now, their selects, then every other preset (main's
|
||||
// _prime_all_lanes)
|
||||
for (int i = 0; i < p->nlanes; i++) {
|
||||
lane_t *l = &p->lane[i];
|
||||
if (l->started) {
|
||||
send_presets(p, i, 0, 1);
|
||||
snprintf(l->last, ID_MAX, "%s", l->step[0].rest || l->step[0].anim ? "" : l->step[0].id);
|
||||
}
|
||||
}
|
||||
p->active = true;
|
||||
for (int i = 0; i < p->nlanes; i++) {
|
||||
send_lane(p, i);
|
||||
}
|
||||
for (int i = 0; i < p->nlanes; i++) {
|
||||
lane_t *l = &p->lane[i];
|
||||
send_presets(p, i, l->started ? 1 : 0, l->n);
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
@@ -825,16 +823,16 @@ static void note_was(const macs_t *covered)
|
||||
}
|
||||
|
||||
// Put the drivers in `drivers` back to what they showed when the one-shot started: the running sequence, a
|
||||
// preset, or off. A preset played or stopped on one of their zones since then wins. Wi-Fi drivers (hostname
|
||||
// ids) are not handled here
|
||||
static void restore(const macs_t *drivers)
|
||||
// preset, or off. A preset played or stopped on one of their zones since then wins. Wi-Fi drivers count by
|
||||
// the MAC in their record. after_ovl: the one-shot is over (not a preview ending: its notes stay)
|
||||
static void restore(const macs_t *drivers, bool after_ovl)
|
||||
{
|
||||
if (!drivers->n) {
|
||||
return;
|
||||
}
|
||||
s_restore = *drivers;
|
||||
s_restoring = true;
|
||||
if (s_base_clear_pending) { // the sequence ended under the one-shot
|
||||
if (after_ovl && s_base_clear_pending) { // the sequence ended under the one-shot
|
||||
s_base_clear_pending = false;
|
||||
clear_sequence(&s_base);
|
||||
}
|
||||
@@ -862,7 +860,8 @@ static void restore(const macs_t *drivers)
|
||||
// A noted WAS_BASE here means that sequence has stopped or no longer lights it: off
|
||||
snprintf(show[nt], ID_MAX, "%s", w->kind == WAS_PRESET ? w->preset : "off");
|
||||
t[nt].n = 1;
|
||||
snprintf(t[nt].g[0], GROUP_ID_MAX, "d%s", mac);
|
||||
t[nt].g[0][0] = 'd';
|
||||
memcpy(t[nt].g[0] + 1, mac, 13); // 12 hex digits (checked above) and the NUL
|
||||
nt++;
|
||||
}
|
||||
// One send per preset: upload it, then select it on its drivers
|
||||
@@ -879,7 +878,8 @@ static void restore(const macs_t *drivers)
|
||||
}
|
||||
}
|
||||
done |= mask;
|
||||
ESP_LOGI(TAG, "one-shot over: %d driver(s) back to %s", __builtin_popcount(mask), show[i]);
|
||||
ESP_LOGI(TAG, "%s over: %d driver(s) back to %s", after_ovl ? "one-shot" : "preview",
|
||||
__builtin_popcount(mask), show[i]);
|
||||
if (strcmp(show[i], "off")) {
|
||||
cJSON *presets = cJSON_CreateObject();
|
||||
cJSON *pl = engine_preset_payload(show[i]);
|
||||
@@ -891,14 +891,14 @@ static void restore(const macs_t *drivers)
|
||||
select_on(&pt, mask, show[i]);
|
||||
}
|
||||
if (back_on_base.n) {
|
||||
ESP_LOGI(TAG, "one-shot over: %d driver(s) back to sequence %s", back_on_base.n, s_base.seq);
|
||||
ESP_LOGI(TAG, "%s over: %d driver(s) back to sequence %s", after_ovl ? "one-shot" : "preview",
|
||||
back_on_base.n, s_base.seq);
|
||||
s_restore = back_on_base;
|
||||
for (int i = 0; i < s_base.nlanes; i++) {
|
||||
s_base.lane[i].last[0] = 0; // they may have missed its upload
|
||||
send_lane(&s_base, i);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < drivers->n; i++) {
|
||||
for (int i = 0; after_ovl && i < drivers->n; i++) {
|
||||
was_drop(drivers->m[i]);
|
||||
}
|
||||
s_restoring = false;
|
||||
@@ -914,10 +914,44 @@ static void overlay_end(void)
|
||||
ESP_LOGI(TAG, "one-shot %s over", s_ovl.seq);
|
||||
macs_t was = s_covered;
|
||||
s_covered.n = 0;
|
||||
restore(&was);
|
||||
restore(&was, true);
|
||||
s_nwas = 0;
|
||||
}
|
||||
|
||||
// End the preview: the simulated drivers it lit drop its presets, then go back to what the live players show
|
||||
// them (the one-shot, the sequence, or their zones' last preset)
|
||||
static void preview_end(void)
|
||||
{
|
||||
if (!s_prev.active) {
|
||||
return;
|
||||
}
|
||||
macs_t lit = { 0 }, all = { 0 };
|
||||
covered_by(&s_prev, &all);
|
||||
for (int i = 0; i < all.n; i++) {
|
||||
if (engine_mac_is_sim(all.m[i])) {
|
||||
macs_add(&lit, all.m[i]);
|
||||
}
|
||||
}
|
||||
s_prev.active = false;
|
||||
ESP_LOGI(TAG, "preview %s over: %d simulated driver(s)", s_prev.seq, lit.n);
|
||||
clear_sequence(&s_prev);
|
||||
// Under the one-shot: it shows them again. The rest: the sequence, a preset, or off
|
||||
macs_t on_ovl = { 0 }, rest = { 0 };
|
||||
for (int i = 0; i < lit.n; i++) {
|
||||
macs_add(s_ovl.active && macs_has(&s_covered, lit.m[i]) ? &on_ovl : &rest, lit.m[i]);
|
||||
}
|
||||
if (on_ovl.n) {
|
||||
s_restore = on_ovl;
|
||||
s_restoring = true;
|
||||
for (int i = 0; i < s_ovl.nlanes; i++) {
|
||||
send_lane(&s_ovl, i);
|
||||
}
|
||||
s_restoring = false;
|
||||
s_restore.n = 0;
|
||||
}
|
||||
restore(&rest, false);
|
||||
}
|
||||
|
||||
// Play sequence seq_id once over whatever runs (a one-shot). A new one replaces the one playing; drivers the new one
|
||||
// leaves alone go back to what they showed.
|
||||
static void fire(const char *seq_id, const char *zone_id, const char *profile_id, bool synced)
|
||||
@@ -930,7 +964,7 @@ static void fire(const char *seq_id, const char *zone_id, const char *profile_id
|
||||
s_covered.n = 0;
|
||||
if (load(&s_ovl, seq_id, zone_id, profile_id, synced, &msg) != ESP_OK) {
|
||||
ESP_LOGW(TAG, "one-shot %s did not start: %s", seq_id, msg ? msg : "not found");
|
||||
restore(&was);
|
||||
restore(&was, true);
|
||||
s_nwas = 0;
|
||||
return;
|
||||
}
|
||||
@@ -942,7 +976,7 @@ static void fire(const char *seq_id, const char *zone_id, const char *profile_id
|
||||
macs_add(&back, was.m[i]);
|
||||
}
|
||||
}
|
||||
restore(&back);
|
||||
restore(&back, true);
|
||||
ESP_LOGI(TAG, "one-shot %s in zone %s: %d lane(s), %d driver(s)", seq_id, zone_id, s_ovl.nlanes, s_covered.n);
|
||||
}
|
||||
|
||||
@@ -969,7 +1003,7 @@ static void step_lane(player_t *p, int i, int64_t now)
|
||||
l->count = 0;
|
||||
l->idx = 0;
|
||||
l->t0 = start;
|
||||
l->last[0] = 0; // step 0 goes up again on each wrap
|
||||
// no re-upload on a wrap: the lane's presets are still on the drivers from its start
|
||||
if (l->chase) {
|
||||
chase_move(l);
|
||||
}
|
||||
@@ -1005,6 +1039,10 @@ static void finish_if_done(player_t *p)
|
||||
overlay_end();
|
||||
return;
|
||||
}
|
||||
if (p->preview) {
|
||||
preview_end();
|
||||
return;
|
||||
}
|
||||
readout(s_done_readout, sizeof(s_done_readout));
|
||||
p->active = false;
|
||||
if (s_ovl.active) {
|
||||
@@ -1066,7 +1104,7 @@ static void tick(player_t *p, bool beat)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (beat && !p->overlay) {
|
||||
if (beat && !p->overlay && !p->preview) {
|
||||
if (p->anchor_next && !p->lane[0].timed) {
|
||||
anchor_bar();
|
||||
}
|
||||
@@ -1100,6 +1138,7 @@ static void sub_tick(void)
|
||||
store_lock();
|
||||
tick(&s_base, false);
|
||||
tick(&s_ovl, false);
|
||||
tick(&s_prev, false);
|
||||
store_unlock();
|
||||
}
|
||||
|
||||
@@ -1146,6 +1185,7 @@ static void on_beat(bool downbeat)
|
||||
if (!fired) {
|
||||
tick(&s_ovl, true);
|
||||
}
|
||||
tick(&s_prev, true);
|
||||
store_unlock();
|
||||
}
|
||||
|
||||
@@ -1160,6 +1200,7 @@ static void beat_task(void *arg)
|
||||
store_lock();
|
||||
advance_time(&s_base);
|
||||
advance_time(&s_ovl);
|
||||
advance_time(&s_prev);
|
||||
int64_t interval = 60LL * 1000000 / simulated_bpm();
|
||||
store_unlock();
|
||||
int64_t now = esp_timer_get_time();
|
||||
@@ -1207,8 +1248,8 @@ static void beat_task(void *arg)
|
||||
|
||||
esp_err_t seqplay_init(void)
|
||||
{
|
||||
player_t *ps[] = { &s_base, &s_ovl };
|
||||
for (int i = 0; i < 2; i++) {
|
||||
player_t *ps[] = { &s_base, &s_ovl, &s_prev };
|
||||
for (int i = 0; i < 3; i++) {
|
||||
ps[i]->lane = heap_caps_calloc(LANES_MAX, sizeof(lane_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
|
||||
ps[i]->target = heap_caps_calloc(TARGETS_MAX, sizeof(target_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
|
||||
if (!ps[i]->lane || !ps[i]->target) {
|
||||
@@ -1216,6 +1257,7 @@ esp_err_t seqplay_init(void)
|
||||
}
|
||||
}
|
||||
s_ovl.overlay = true;
|
||||
s_prev.preview = true;
|
||||
store_lock();
|
||||
const cJSON *a = cJSON_GetObjectItem(store_settings(), "audio_timing");
|
||||
s_audio = !cJSON_IsFalse(a);
|
||||
@@ -1290,6 +1332,36 @@ esp_err_t seqplay_fire(const char *seq_id, const char *zone_id, const char *prof
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t seqplay_preview(const char *seq_id, const char *zone_id, const char *profile_id, const char **msg)
|
||||
{
|
||||
*msg = NULL;
|
||||
if (!owned(seq_id, profile_id)) {
|
||||
*msg = "sequence not found";
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
if (!zone_id || !zone_id[0]) {
|
||||
zone_id = s_base.active ? s_base.zone : NULL;
|
||||
}
|
||||
if (!zone_id || !cJSON_GetObjectItem(store_coll("zone"), zone_id)) {
|
||||
*msg = "zone not found";
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
preview_end(); // a new preview replaces the one playing
|
||||
esp_err_t err = load(&s_prev, seq_id, zone_id, profile_id, false, msg);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
ESP_LOGI(TAG, "preview %s in zone %s: %d lane(s)", seq_id, zone_id, s_prev.nlanes);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void seqplay_preview_stop(void)
|
||||
{
|
||||
store_lock();
|
||||
preview_end();
|
||||
store_unlock();
|
||||
}
|
||||
|
||||
void seqplay_overlay_stop(void)
|
||||
{
|
||||
store_lock();
|
||||
@@ -1347,6 +1419,9 @@ void seqplay_stop_if(const char *seq_id)
|
||||
store_lock();
|
||||
bool playing = s_base.active && !strcmp(s_base.seq, seq_id);
|
||||
bool anim = s_ovl.active && !strcmp(s_ovl.seq, seq_id);
|
||||
if (s_prev.active && !strcmp(s_prev.seq, seq_id)) {
|
||||
preview_end();
|
||||
}
|
||||
store_unlock();
|
||||
if (playing) {
|
||||
seqplay_stop(true);
|
||||
@@ -1525,11 +1600,25 @@ static cJSON *overlay_status(void)
|
||||
return o;
|
||||
}
|
||||
|
||||
static cJSON *preview_status(void)
|
||||
{
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddBoolToObject(o, "active", s_prev.active);
|
||||
if (s_prev.active) {
|
||||
cJSON_AddStringToObject(o, "sequence_id", s_prev.seq);
|
||||
cJSON_AddStringToObject(o, "zone_id", s_prev.zone);
|
||||
cJSON_AddBoolToObject(o, "loop", s_prev.loop);
|
||||
cJSON_AddItemToObject(o, "lanes", lanes_status(&s_prev));
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
cJSON *seqplay_status(void)
|
||||
{
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
store_lock();
|
||||
cJSON_AddItemToObject(o, "overlay", overlay_status());
|
||||
cJSON_AddItemToObject(o, "preview", preview_status());
|
||||
if (!s_base.active) {
|
||||
cJSON_AddFalseToObject(o, "active");
|
||||
cJSON_AddStringToObject(o, "beat_readout", "");
|
||||
|
||||
+8
-1
@@ -33,6 +33,13 @@ esp_err_t seqplay_fire(const char *seq_id, const char *zone_id, const char *prof
|
||||
void seqplay_end_base_in(const char *zone_id);
|
||||
// Whether sequence seq_id is a one-shot: its `loop` is off (older records: kind "animation")
|
||||
bool seqplay_is_oneshot(const char *seq_id);
|
||||
// Preview sequence seq_id on the simulated drivers only (devices with "sim": true), alongside whatever plays
|
||||
// live: same beats, but the live sequence and one-shot skip the simulated drivers while it plays. It loops unless
|
||||
// the sequence is a one-shot; one-shot steps inside it are skipped. A new preview replaces the one playing.
|
||||
// zone_id NULL or "": the live sequence's zone. Errors as seqplay_start. Call with the store locked.
|
||||
esp_err_t seqplay_preview(const char *seq_id, const char *zone_id, const char *profile_id, const char **msg);
|
||||
// End the preview: the simulated drivers go back to what plays live
|
||||
void seqplay_preview_stop(void);
|
||||
// End the one-shot now and restore its drivers
|
||||
void seqplay_overlay_stop(void);
|
||||
// How long sequence seq_id plays once: *beats and *secs (each converted from the other at the current
|
||||
@@ -41,7 +48,7 @@ void seqplay_length(const char *seq_id, double *beats, double *secs);
|
||||
|
||||
// Stop the sequence and any animation; with clear, the zone's drivers drop their presets
|
||||
void seqplay_stop(bool clear);
|
||||
// Stop when seq_id is the one playing (it was edited or deleted)
|
||||
// Stop when seq_id is the one playing, or previewing (it was edited or deleted)
|
||||
void seqplay_stop_if(const char *seq_id);
|
||||
|
||||
// Align beat counters: "step" restarts the current step's beat count, "pass" restarts the sequence.
|
||||
|
||||
@@ -29,6 +29,7 @@ static const char *db_root(void)
|
||||
static const char *const NAMES[] = {
|
||||
"device", "zone", "preset", "profile", "palette", "pattern",
|
||||
"sequence", "scene", "group", "output", "settings", "user", "role",
|
||||
"dmx_definition", "dmx_bridge",
|
||||
};
|
||||
#define N_COLL (sizeof(NAMES) / sizeof(NAMES[0]))
|
||||
|
||||
@@ -181,6 +182,11 @@ void store_next_id(const char *name, char *buf, size_t len)
|
||||
snprintf(buf, len, "%ld", max + 1);
|
||||
}
|
||||
|
||||
const char *store_dir(void)
|
||||
{
|
||||
return db_root();
|
||||
}
|
||||
|
||||
cJSON *store_settings(void)
|
||||
{
|
||||
return store_coll("settings");
|
||||
|
||||
@@ -22,6 +22,9 @@ esp_err_t store_save(const char *name);
|
||||
// Next numeric string id for a collection ("1" when empty); writes into buf
|
||||
void store_next_id(const char *name, char *buf, size_t len);
|
||||
|
||||
// The directory the collections are kept in ("/db", or LED_SIM_DB on the host build)
|
||||
const char *store_dir(void);
|
||||
|
||||
// Settings are one flat object (the "settings" collection itself)
|
||||
cJSON *store_settings(void);
|
||||
|
||||
|
||||
Reference in new issue
Block a user