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

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

1716 lines
60 KiB
C

#include "engine.h"
#include <ctype.h>
#include <strings.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "api_util.h"
#include "bridge.h"
#include "envelope.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "espnow_tx.h"
#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"
static const char *TAG = "engine";
#define FRAME_REPEAT 2 // every state frame goes out twice; messages are idempotent
#define JSON_MAX 232
/* ---------------------------------------------------------------- sending */
static esp_err_t tx(const uint8_t *mac, const void *data, size_t len, bool commit, int repeat)
{
// The bulk queue is bounded; wait for room instead of dropping state
for (int i = 0; i < 400; i++) {
esp_err_t err = rel_send(mac, data, len, commit, repeat);
if (err != ESP_ERR_NO_MEM) {
return err;
}
vTaskDelay(pdMS_TO_TICKS(5));
}
return ESP_ERR_TIMEOUT;
}
static bool parse_mac(const char *s, uint8_t mac[6])
{
if (strlen(s) != 12) {
return false;
}
for (int i = 0; i < 6; i++) {
if (!isxdigit((unsigned char)s[2 * i]) || !isxdigit((unsigned char)s[2 * i + 1])) {
return false;
}
char b[3] = { s[2 * i], s[2 * i + 1], 0 };
mac[i] = strtoul(b, NULL, 16);
}
return true;
}
// Broadcast (no targets): sent `repeat` times under one sequence number, never acked; the
// state version digest covers losses. With targets: unicast per MAC, acked and retransmitted.
// commit (broadcast only) tells drivers this frame completes a state change.
static char s_gid[24]; // group being addressed; "" = plain CMD (all addressed drivers apply it)
static bool s_save; // append the CMD save byte (driver persists presets / brightness)
// Envelopes travel as 0x4C CMD (4C 03 env) or, for a zone, GROUP_CMD (4C 04 <len><group> env) so only
// drivers in that group apply them. JSON messages go as they are.
static size_t wrap_wire(uint8_t *out, const uint8_t *frame, size_t len)
{
if (len == 0 || (frame[0] != 2 && frame[0] != 3)) { // not a v2/v3 envelope (JSON goes as it is)
memcpy(out, frame, len);
return len;
}
size_t off = 0;
out[off++] = 0x4C;
if (s_gid[0]) {
size_t gl = strlen(s_gid);
out[off++] = 0x04;
out[off++] = gl;
memcpy(out + off, s_gid, gl);
off += gl;
} else {
out[off++] = 0x03;
}
memcpy(out + off, frame, len);
off += len;
if (s_save) {
out[off++] = 1; // 4C 03 / 4C 04 carry an optional trailing save flag after the envelope
}
return off;
}
static esp_err_t emit_c(const cJSON *targets, const uint8_t *frame, size_t len, int repeat, bool commit)
{
uint8_t wire[REL_FRAG_MAX];
if (len + 3 + strlen(s_gid) + 1 > sizeof(wire)) {
return ESP_ERR_INVALID_SIZE;
}
len = wrap_wire(wire, frame, len);
frame = wire;
esp_err_t ret = ESP_OK;
int n = cJSON_IsArray(targets) ? cJSON_GetArraySize(targets) : 0;
if (n == 0) {
return tx(NULL, frame, len, commit, repeat);
}
for (int i = 0; i < n; i++) {
const cJSON *t = cJSON_GetArrayItem(targets, i);
uint8_t mac[6];
if (cJSON_IsString(t) && parse_mac(t->valuestring, mac)) {
esp_err_t e = tx(mac, frame, len, false, 1);
if (e != ESP_OK) {
ret = e;
}
}
}
return ret;
}
/* --------------------------------------------------------------- presets */
static bool id_text(const cJSON *v, char *buf, size_t len)
{
buf[0] = 0;
if (cJSON_IsString(v) && v->valuestring[0]) {
snprintf(buf, len, "%s", v->valuestring);
} else if (cJSON_IsNumber(v)) {
snprintf(buf, len, "%d", (int)v->valuedouble);
}
return buf[0] != 0;
}
// Palette colour idx of a profile, or NULL
static const cJSON *palette_color(const cJSON *profile_id, int idx)
{
char pidbuf[24], palbuf[24];
if (!id_text(profile_id, pidbuf, sizeof(pidbuf))) {
return NULL;
}
cJSON *profile = cJSON_GetObjectItem(store_coll("profile"), pidbuf);
if (!id_text(cJSON_GetObjectItem(profile, "palette_id"), palbuf, sizeof(palbuf))) {
return NULL;
}
cJSON *pal = cJSON_GetObjectItem(store_coll("palette"), palbuf);
if (cJSON_IsObject(pal)) { // older records hold {"colors": [...]}
pal = cJSON_GetObjectItem(pal, "colors");
}
const cJSON *c = idx >= 0 ? cJSON_GetArrayItem(pal, idx) : NULL;
return cJSON_IsString(c) && c->valuestring[0] ? c : NULL;
}
cJSON *engine_preset_payload(const char *preset_id)
{
cJSON *rec = cJSON_GetObjectItem(store_coll("preset"), preset_id);
if (!rec) {
return NULL;
}
cJSON *out = cJSON_Duplicate(rec, true);
const cJSON *pid = cJSON_GetObjectItem(out, "profile_id");
cJSON *refs = cJSON_GetObjectItem(out, "palette_refs");
cJSON *colors = cJSON_GetObjectItem(out, "colors");
int n = cJSON_IsArray(refs) && cJSON_IsArray(colors) ? cJSON_GetArraySize(colors) : 0;
for (int i = 0; i < n; i++) {
const cJSON *ref = cJSON_GetArrayItem(refs, i);
const cJSON *c = cJSON_IsNumber(ref) ? palette_color(pid, (int)ref->valuedouble) : NULL;
if (c) {
cJSON_ReplaceItemInArray(colors, i, cJSON_Duplicate(c, true));
}
}
const cJSON *bref = cJSON_GetObjectItem(out, "background_palette_ref");
const cJSON *bg = cJSON_IsNumber(bref) ? palette_color(pid, (int)bref->valuedouble) : NULL;
if (bg) {
cJSON_DeleteItemFromObject(out, "bg");
cJSON_DeleteItemFromObject(out, "background");
cJSON_AddItemToObject(out, "background", cJSON_Duplicate(bg, true));
}
const cJSON *mode = cJSON_GetObjectItem(out, "mode");
if (cJSON_IsNumber(mode) || (cJSON_IsString(mode) && mode->valuestring[0])) { // style mode travels as n6
int m = cJSON_IsNumber(mode) ? (int)mode->valuedouble : atoi(mode->valuestring);
cJSON_DeleteItemFromObject(out, "n6");
cJSON_AddNumberToObject(out, "n6", m < 0 ? 0 : m);
}
return out;
}
static cJSON *preset_payload(const char *preset_id)
{
return engine_preset_payload(preset_id);
}
/* ------------------------------------------------------------ zone play */
static const cJSON *zone_names(const char *zone_id)
{
cJSON *z = cJSON_GetObjectItem(store_coll("zone"), zone_id);
cJSON *names = cJSON_GetObjectItem(z, "names");
return cJSON_IsArray(names) ? names : NULL;
}
static bool name_seen(const cJSON *names, int upto, const char *name)
{
for (int i = 0; i < upto; i++) {
const cJSON *o = cJSON_GetArrayItem(names, i);
if (cJSON_IsString(o) && strcmp(o->valuestring, name) == 0) {
return true;
}
}
return false;
}
/* Driver groups. A driver's group list holds the ids of the registry groups ("group" collection)
whose devices list its MAC, plus "z<zone id>" for every zone that names the driver directly (zones
from before groups). A zone plays to its group_ids and, when it names drivers, to "z<zone id>". */
int engine_zone_targets(const char *zone_id, char out[][GROUP_ID_MAX], int max)
{
const cJSON *z = cJSON_GetObjectItem(store_coll("zone"), zone_id);
if (!z) {
return -1;
}
int n = 0;
const cJSON *g;
cJSON_ArrayForEach(g, cJSON_GetObjectItem(z, "group_ids"))
{
if (n < max && id_text(g, out[n], GROUP_ID_MAX)) {
n++;
}
}
const cJSON *names = zone_names(zone_id);
if (n < max && names && cJSON_GetArraySize(names) > 0) {
snprintf(out[n++], GROUP_ID_MAX, "z%s", zone_id);
}
return n;
}
static bool mac_listed(const cJSON *list, const char *hex)
{
const cJSON *it;
cJSON_ArrayForEach(it, list)
{
if (!cJSON_IsString(it)) {
continue;
}
char m[13];
int k = 0;
for (const char *c = it->valuestring; *c && k < 12; c++) {
if (*c != ':' && *c != '-') {
m[k++] = tolower((unsigned char)*c);
}
}
m[k] = 0;
if (k == 12 && !strcmp(m, hex)) {
return true;
}
}
return false;
}
// Is the driver (mac, name) a member of group gid?
static bool in_group(const uint8_t mac[6], const char *name, const char *gid)
{
if (gid[0] == 'z') {
return name && name_seen(zone_names(gid + 1), cJSON_GetArraySize(zone_names(gid + 1)), name);
}
char hex[13];
snprintf(hex, sizeof(hex), "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
if (gid[0] == 'd' && strlen(gid) == 13) { // a driver's own group, d<mac>
return !strcmp(gid + 1, hex);
}
return mac_listed(cJSON_GetObjectItem(cJSON_GetObjectItem(store_coll("group"), gid), "devices"), hex);
}
static bool driver_in_zone(const uint8_t mac[6], const char *name, 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 (in_group(mac, name, t[i])) {
return true;
}
}
return false;
}
/* Wi-Fi drivers (transport "wifi") get the preset as a JSON API call, not an ESP-NOW frame */
static bool is_wifi(const cJSON *dev)
{
const cJSON *tr = cJSON_GetObjectItem(dev, "transport");
return cJSON_IsString(tr) && !strcmp(tr->valuestring, "wifi");
}
// Whether the Wi-Fi device (its id and record) is in group gid: a group id, "z<zone>" or "d<mac>"
static bool wifi_in_group(const cJSON *dev, const char *id, const char *gid)
{
if (gid[0] == 'z') {
const cJSON *name = cJSON_GetObjectItem(dev, "name"), *names = zone_names(gid + 1);
return cJSON_IsString(name) && names && name_seen(names, cJSON_GetArraySize(names), name->valuestring);
}
if (gid[0] == 'd') {
// a driver's own group: d<mac>, the MAC in its record (a Wi-Fi driver's record has one too)
const cJSON *mac = cJSON_GetObjectItem(dev, "mac");
return cJSON_IsString(mac) && !strcmp(mac->valuestring, gid + 1);
}
const cJSON *group = cJSON_GetObjectItem(store_coll("group"), gid);
const cJSON *list = group ? cJSON_GetObjectItem(group, "devices") : NULL, *it;
cJSON_ArrayForEach(it, list)
{
if (cJSON_IsString(it) && !strcmp(it->valuestring, id)) {
return true;
}
}
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)
{
char t[ZONE_TARGETS_MAX][GROUP_ID_MAX];
int n = engine_zone_targets(zone_id, t, ZONE_TARGETS_MAX);
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
if (!is_wifi(d)) {
continue;
}
bool in = false;
for (int i = 0; i < n && !in; i++) {
in = wifi_in_group(d, d->string, t[i]);
}
if (!in) {
continue;
}
cJSON *body = NULL;
if (payload) {
body = wifi_drv_preset_body(payload);
} else {
body = cJSON_CreateObject();
cJSON_AddStringToObject(body, "pattern", "off");
}
if (body) {
wifi_drv_post(d->string, "/api/pattern", body);
}
}
}
// Whether a Wi-Fi device is addressed by a message: its targets (ids), else its groups, else all of them
static bool wifi_selected(const cJSON *dev, const char *id, const cJSON *targets, const cJSON *groups)
{
if (cJSON_IsArray(targets) && cJSON_GetArraySize(targets) > 0) {
const cJSON *t;
// A Wi-Fi driver is named by its hostname, or by its MAC when the UI resolved the device to one
const cJSON *dmac = cJSON_GetObjectItem(dev, "mac");
cJSON_ArrayForEach(t, targets)
{
if (cJSON_IsString(t) && (!strcmp(t->valuestring, id) || (cJSON_IsString(dmac) && !strcasecmp(t->valuestring, dmac->valuestring)))) {
return true;
}
}
return false;
}
if (cJSON_IsArray(groups) && groups->child) {
const cJSON *g;
cJSON_ArrayForEach(g, groups)
{
if (cJSON_IsString(g) && wifi_in_group(dev, id, g->valuestring)) {
return true;
}
}
return false;
}
return true;
}
// The Wi-Fi part of a v1 message: select (["preset", step], or {group: preset}) becomes /api/pattern,
// b becomes /api/brightness. The preset travels with the select, so a driver never runs a stale one.
static void wifi_push(const cJSON *m, const cJSON *targets)
{
const cJSON *groups = cJSON_GetObjectItem(m, "groups");
const cJSON *sel = cJSON_GetObjectItem(m, "select");
const cJSON *presets = cJSON_GetObjectItem(m, "presets");
const cJSON *b = cJSON_GetObjectItem(m, "b");
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
const char *id = d->string;
if (!is_wifi(d) || !wifi_selected(d, id, targets, groups)) {
continue;
}
const char *name = NULL;
if (cJSON_IsArray(sel)) {
const cJSON *p0 = cJSON_GetArrayItem(sel, 0);
name = cJSON_IsString(p0) ? p0->valuestring : NULL;
} else if (cJSON_IsObject(sel)) {
const cJSON *it;
cJSON_ArrayForEach(it, sel)
{
const cJSON *v = cJSON_IsArray(it) ? cJSON_GetArrayItem(it, 0) : it;
// A key is "*", the device's id or name, or a group the device is in
const cJSON *dn = cJSON_GetObjectItem(d, "name");
bool named = !strcmp(it->string, id) || (cJSON_IsString(dn) && !strcmp(it->string, dn->valuestring));
if (cJSON_IsString(v) && (!strcmp(it->string, "*") || named || wifi_in_group(d, id, it->string))) {
name = v->valuestring;
break;
}
}
} else if (cJSON_IsNumber(b)) {
cJSON *body = cJSON_CreateObject();
cJSON_AddNumberToObject(body, "brightness", b->valuedouble);
wifi_drv_post(id, "/api/brightness", body);
continue;
}
if (!name) {
continue;
}
cJSON *body = NULL, *stored = NULL;
if (!strcmp(name, "off")) {
body = cJSON_CreateObject();
cJSON_AddStringToObject(body, "pattern", "off");
cJSON_AddNumberToObject(body, "fade", 0); // not the fade of the preset it replaces
} else {
const cJSON *pv = presets ? cJSON_GetObjectItem(presets, name) : NULL;
if (!pv) {
stored = engine_preset_payload(name);
pv = stored;
}
body = wifi_drv_preset_body(pv);
cJSON_Delete(stored);
}
if (body) {
cJSON_AddTrueToObject(body, "select"); // a select restarts the pattern and fades in (fade)
wifi_drv_post(id, "/api/pattern", body);
}
// ESP-NOW carries b in the same frame as the select; the Wi-Fi driver takes it in its own call
if (cJSON_IsNumber(b)) {
cJSON *bb = cJSON_CreateObject();
cJSON_AddNumberToObject(bb, "brightness", b->valuedouble);
wifi_drv_post(id, "/api/brightness", bb);
}
}
}
// Wi-Fi drivers keep their own preset store: each preset sent is saved on the drivers it is addressed to
// (every Wi-Fi device when the send has no targets), and def becomes their startup preset
static void wifi_store_presets(const cJSON *presets, const cJSON *targets, const char *def)
{
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
if (!is_wifi(d) || !wifi_selected(d, d->string, targets, NULL)) {
continue;
}
const cJSON *p;
cJSON_ArrayForEach(p, presets)
{
cJSON *body = wifi_drv_preset_body(p);
if (body) {
cJSON_AddStringToObject(body, "name", p->string);
wifi_drv_post(d->string, "/api/presets", body);
}
}
if (def && def[0] && cJSON_GetObjectItem(presets, def)) {
cJSON *body = cJSON_CreateObject();
cJSON_AddStringToObject(body, "name", def);
wifi_drv_post(d->string, "/api/presets/startup", body);
}
}
}
// Send one envelope frame to every group the zone plays to, as GROUP_CMDs
static esp_err_t emit_zone(const char *zone_id, const uint8_t *frame, size_t len, bool commit)
{
char t[ZONE_TARGETS_MAX][GROUP_ID_MAX];
int n = engine_zone_targets(zone_id, t, ZONE_TARGETS_MAX);
esp_err_t ret = n < 0 ? ESP_ERR_NOT_FOUND : ESP_OK;
for (int i = 0; i < n; i++) {
snprintf(s_gid, sizeof(s_gid), "%s", t[i]);
esp_err_t e = emit_c(NULL, frame, len, FRAME_REPEAT, commit);
if (e != ESP_OK) {
ret = e;
}
}
s_gid[0] = 0;
return ret;
}
// Select a preset for the whole zone. The select entry's key is ignored by drivers when it is the
// only entry.
static esp_err_t select_zone(const char *zone_id, const char *preset_name)
{
uint8_t frame[ENV_FRAME_MAX];
env_blob_t sel;
env_blob_init(&sel);
env_add_select(&sel, "*", preset_name, -1);
return emit_zone(zone_id, frame, env_frame(frame, -1, NULL, &sel), true);
}
/* What each zone last played, so a driver that missed it can be brought back in step */
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)
{
zone_cur_t *slot = NULL;
for (int i = 0; i < 16; i++) {
if (strcmp(s_cur[i].zone, zone_id) == 0) {
slot = &s_cur[i];
break;
}
if (!slot && !s_cur[i].zone[0]) {
slot = &s_cur[i];
}
}
if (slot) {
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;
}
}
static esp_err_t play_locked(const char *zone_id, const char *preset_id)
{
if (!cJSON_GetObjectItem(store_coll("zone"), zone_id)) {
return ESP_ERR_NOT_FOUND;
}
cJSON *payload = preset_payload(preset_id);
if (!payload) {
return ESP_ERR_NOT_FOUND;
}
wifi_zone(zone_id, payload);
uint8_t frame[ENV_FRAME_MAX];
env_blob_t pb;
env_blob_init(&pb);
rel_bump_ver();
bool fit = env_add_preset(&pb, preset_id, payload);
cJSON_Delete(payload);
if (!fit) {
return ESP_ERR_INVALID_SIZE;
}
esp_err_t ret = emit_zone(zone_id, frame, env_frame(frame, -1, &pb, NULL), false);
if (ret == ESP_OK) {
ret = select_zone(zone_id, preset_id);
}
if (ret == ESP_OK) {
zone_cur_set(zone_id, preset_id);
}
return ret;
}
void engine_zone_note(const char *zone_id, const char *preset_id)
{
store_lock();
zone_cur_set(zone_id, preset_id);
store_unlock();
}
const char *engine_zone_current(const char *zone_id)
{
for (int i = 0; i < 16; i++) {
if (s_cur[i].zone[0] && !strcmp(s_cur[i].zone, zone_id)) {
return s_cur[i].preset;
}
}
return NULL;
}
int engine_zone_wifi_ids(const char *zone_id, char out[][GROUP_ID_MAX], int max)
{
char t[ZONE_TARGETS_MAX][GROUP_ID_MAX];
int nt = engine_zone_targets(zone_id, t, ZONE_TARGETS_MAX);
int n = 0;
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
if (!d->string || !is_wifi(d)) {
continue;
}
for (int i = 0; i < nt && n < max; i++) {
if (wifi_in_group(d, d->string, t[i])) {
snprintf(out[n++], GROUP_ID_MAX, "%s", d->string);
break;
}
}
}
return n;
}
int engine_group_macs(const char *gid, char out[][13], int max)
{
int n = 0;
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
uint8_t mac[6];
const cJSON *name = cJSON_GetObjectItem(d, "name");
if (n < max && d->string && parse_mac(d->string, mac) &&
in_group(mac, cJSON_IsString(name) ? name->valuestring : NULL, gid)) {
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;
}
esp_err_t engine_play(const char *zone_id, const char *preset_id)
{
store_lock();
esp_err_t ret = play_locked(zone_id, preset_id);
store_unlock();
return ret;
}
esp_err_t engine_stop(const char *zone_id)
{
store_lock();
rel_bump_ver();
esp_err_t ret = select_zone(zone_id, "off");
wifi_zone(zone_id, NULL);
if (ret == ESP_OK) {
zone_cur_set(zone_id, "off");
}
store_unlock();
return ret;
}
static const char *device_name_for(const uint8_t mac[6]);
/* ------------------------------------------------------------ push/send */
static bool only_binary_keys(const cJSON *m)
{
const cJSON *it;
cJSON_ArrayForEach(it, m)
{
const char *k = it->string;
if (strcmp(k, "v") && strcmp(k, "presets") && strcmp(k, "select") && strcmp(k, "b") && strcmp(k, "save") &&
strcmp(k, "groups")) {
return false;
}
}
// A background colour has no place in the binary preset record
const cJSON *p;
cJSON_ArrayForEach(p, cJSON_GetObjectItem(m, "presets"))
{
if (cJSON_GetObjectItem(p, "bg") || cJSON_GetObjectItem(p, "background")) {
return false;
}
}
return true;
}
static esp_err_t push_binary(const cJSON *m, const cJSON *targets)
{
uint8_t frame[ENV_FRAME_MAX];
esp_err_t ret = ESP_OK;
const cJSON *b = cJSON_GetObjectItem(m, "b");
int brightness = cJSON_IsNumber(b) ? (int)b->valuedouble : -1;
const cJSON *sv = cJSON_GetObjectItem(m, "save");
const bool save = cJSON_IsTrue(sv) || (cJSON_IsNumber(sv) && sv->valuedouble != 0);
bool sent_any = false;
const cJSON *presets = cJSON_GetObjectItem(m, "presets"), *it;
const cJSON *select_obj = cJSON_GetObjectItem(m, "select");
const bool has_select = (cJSON_IsObject(select_obj) || cJSON_IsArray(select_obj)) && select_obj->child;
env_blob_t pb;
env_blob_init(&pb);
cJSON_ArrayForEach(it, presets)
{
if (!env_add_preset(&pb, it->string, it)) {
size_t len = env_frame(frame, sent_any ? -1 : brightness, &pb, NULL);
ret = emit_c(targets, frame, len, FRAME_REPEAT, false);
sent_any = true;
env_blob_init(&pb);
if (!env_add_preset(&pb, it->string, it)) {
ESP_LOGW(TAG, "preset %s too large for one frame", it->string);
}
}
}
if (pb.data[0]) {
size_t len = env_frame(frame, sent_any ? -1 : brightness, &pb, NULL);
s_save = save; // only the last presets frame asks the driver to persist
ret = emit_c(targets, frame, len, FRAME_REPEAT, !has_select);
s_save = false;
sent_any = true;
}
const cJSON *select = cJSON_GetObjectItem(m, "select");
env_blob_t sb;
env_blob_init(&sb);
if (cJSON_IsArray(select) && select->child) { // ["preset", step?]: every addressed driver
const cJSON *p0 = cJSON_GetArrayItem(select, 0), *s1 = cJSON_GetArrayItem(select, 1);
char pname[32];
if (id_text(p0, pname, sizeof(pname))) {
env_add_select(&sb, "*", pname, cJSON_IsNumber(s1) ? (int)s1->valuedouble : -1);
}
select = NULL;
}
cJSON_ArrayForEach(it, select)
{
const char *pname = NULL;
int step = -1;
if (cJSON_IsArray(it) && cJSON_GetArraySize(it) > 0) {
const cJSON *p0 = cJSON_GetArrayItem(it, 0), *s1 = cJSON_GetArrayItem(it, 1);
pname = cJSON_IsString(p0) ? p0->valuestring : NULL;
if (cJSON_IsNumber(s1)) {
step = (int)s1->valuedouble;
}
} else if (cJSON_IsString(it)) {
pname = it->valuestring;
}
if (!pname) {
continue;
}
if (!env_add_select(&sb, it->string, pname, step)) {
size_t len = env_frame(frame, sent_any ? -1 : brightness, NULL, &sb);
ret = emit_c(targets, frame, len, FRAME_REPEAT, true);
sent_any = true;
env_blob_init(&sb);
env_add_select(&sb, it->string, pname, step);
}
}
if (sb.data[0]) {
size_t len = env_frame(frame, sent_any ? -1 : brightness, NULL, &sb);
ret = emit_c(targets, frame, len, FRAME_REPEAT, true);
sent_any = true;
}
if (!sent_any && brightness >= 0) { // brightness-only message
size_t len = env_frame(frame, brightness, NULL, NULL);
s_save = save;
ret = emit_c(targets, frame, len, FRAME_REPEAT, true);
s_save = false;
}
return ret;
}
// Long v1 keys and their wire short forms (led-driver/src/v1_wire.py, preset.py)
static const char *const TOP_SHORT[][2] = {
{ "presets", "p" }, { "select", "s" }, { "groups", "g" }, { "set_groups", "sg" },
{ "save", "sv" }, { "default", "df" }, { "device_config", "dc" }, { "clear_presets", "cp" },
{ "manifest", "mf" },
};
static const char *const PRESET_SHORT[][2] = {
{ "pattern", "p" }, { "colors", "c" }, { "delay", "d" }, { "brightness", "b" }, { "auto", "a" }, { "background", "bg" },
{ "fade", "f" },
};
// Presets are always timed in ms; beats belong to sequences (seqplay.c), so no tb goes to drivers
static const char *const PRESET_KEYS[] = { "p", "c", "d", "b", "a", "bg", "n1", "n2", "n3", "n4", "n5", "n6", "f" };
static const char *short_key(const char *const map[][2], size_t n, const char *k)
{
for (size_t i = 0; i < n; i++) {
if (!strcmp(map[i][0], k)) {
return map[i][1];
}
}
return k;
}
// Copy of a preset with short keys and only the fields drivers store
static cJSON *compact_preset(const cJSON *p)
{
cJSON *o = cJSON_CreateObject();
const cJSON *it;
cJSON_ArrayForEach(it, p)
{
const char *k = short_key(PRESET_SHORT, sizeof(PRESET_SHORT) / sizeof(PRESET_SHORT[0]), it->string);
bool keep = false;
for (size_t i = 0; i < sizeof(PRESET_KEYS) / sizeof(PRESET_KEYS[0]) && !keep; i++) {
keep = !strcmp(k, PRESET_KEYS[i]);
}
if (keep && !cJSON_GetObjectItem(o, k)) {
cJSON_AddItemToObject(o, k, cJSON_Duplicate(it, true));
}
}
return o;
}
// Copy of a v1 message in its short wire form
static cJSON *compact(const cJSON *m)
{
cJSON *o = cJSON_CreateObject();
const cJSON *it;
cJSON_ArrayForEach(it, m)
{
const char *k = short_key(TOP_SHORT, sizeof(TOP_SHORT) / sizeof(TOP_SHORT[0]), it->string);
if (cJSON_GetObjectItem(o, k)) {
continue;
}
if (!strcmp(k, "p") && cJSON_IsObject(it)) {
cJSON *ps = cJSON_AddObjectToObject(o, "p");
const cJSON *p;
cJSON_ArrayForEach(p, it)
{
cJSON_AddItemToObject(ps, p->string, compact_preset(p));
}
} else {
cJSON_AddItemToObject(o, k, cJSON_Duplicate(it, true));
}
}
return o;
}
static esp_err_t emit_json(const cJSON *targets, const cJSON *msg, bool commit)
{
char *s = cJSON_PrintUnformatted(msg);
if (!s) {
return ESP_ERR_NO_MEM;
}
esp_err_t ret = strlen(s) <= JSON_MAX ? emit_c(targets, (const uint8_t *)s, strlen(s), 1, commit)
: ESP_ERR_INVALID_SIZE;
free(s);
return ret;
}
// JSON text path for keys the binary envelope cannot carry (default, manifest, bg, ...)
static esp_err_t push_json(const cJSON *m_long, const cJSON *targets)
{
cJSON *m = compact(m_long);
esp_err_t ret = emit_json(targets, m, true);
if (ret != ESP_ERR_INVALID_SIZE) {
cJSON_Delete(m);
return ret;
}
// Too big: the presets go over several messages (each with the group filter, so drivers outside
// the groups ignore them); the other keys ride on the last one
const cJSON *presets = cJSON_GetObjectItem(m, "p"), *groups = cJSON_GetObjectItem(m, "g");
if (!cJSON_IsObject(presets)) {
cJSON_Delete(m);
return ESP_ERR_INVALID_SIZE;
}
ret = ESP_OK;
cJSON *batch = NULL;
const cJSON *it = presets->child;
while (it) {
batch = cJSON_CreateObject();
cJSON_AddStringToObject(batch, "v", "1");
cJSON *bp = cJSON_AddObjectToObject(batch, "p");
if (groups) {
cJSON_AddItemReferenceToObject(batch, "g", (cJSON *)groups);
}
do {
cJSON_AddItemReferenceToObject(bp, it->string, (cJSON *)it);
char *out = cJSON_PrintUnformatted(batch);
size_t len = out ? strlen(out) : 0;
free(out);
if (len > JSON_MAX - 48 && cJSON_GetArraySize(bp) > 1) { // room for the last message's other keys
cJSON_DeleteItemFromObject(bp, it->string);
break;
}
it = it->next;
} while (it);
if (it) { // more to come: this part goes now
esp_err_t e = emit_json(targets, batch, false);
ret = e != ESP_OK ? e : ret;
cJSON_Delete(batch);
batch = NULL;
}
}
if (!batch) {
batch = cJSON_CreateObject();
cJSON_AddStringToObject(batch, "v", "1");
}
const cJSON *k;
cJSON_ArrayForEach(k, m)
{
if (strcmp(k->string, "v") && strcmp(k->string, "p") && !cJSON_GetObjectItem(batch, k->string)) {
cJSON_AddItemReferenceToObject(batch, k->string, (cJSON *)k);
}
}
esp_err_t e = emit_json(targets, batch, true);
ret = e != ESP_OK ? e : ret;
cJSON_Delete(batch);
cJSON_Delete(m);
return ret;
}
esp_err_t engine_push(const cJSON *messages, const cJSON *targets)
{
esp_err_t ret = ESP_OK;
const cJSON *m;
store_lock();
cJSON_ArrayForEach(m, messages)
{
if (!cJSON_IsObject(m)) {
continue;
}
wifi_push(m, targets);
if (!cJSON_IsArray(targets) || cJSON_GetArraySize(targets) == 0) {
rel_bump_ver(); // a broadcast state change: drivers that miss it resync from the digest
}
const cJSON *groups = cJSON_GetObjectItem(m, "groups");
esp_err_t e = ESP_OK;
if (!only_binary_keys(m)) {
e = push_json(m, targets);
} else if (cJSON_IsArray(groups) && groups->child) {
// One GROUP_CMD per group: only its members apply the presets and the select
const cJSON *g;
cJSON_ArrayForEach(g, groups)
{
if (id_text(g, s_gid, sizeof(s_gid))) {
esp_err_t r = push_binary(m, targets);
e = r != ESP_OK ? r : e;
}
}
s_gid[0] = 0;
} else {
e = push_binary(m, targets);
}
if (e != ESP_OK) {
ret = e;
}
}
store_unlock();
return ret;
}
esp_err_t engine_send_presets(const cJSON *ids, bool save, const char *def, const cJSON *targets, int *sent)
{
cJSON *msg = cJSON_CreateObject();
cJSON_AddStringToObject(msg, "v", "1");
cJSON *presets = cJSON_AddObjectToObject(msg, "presets");
int count = 0;
store_lock();
const cJSON *id;
cJSON_ArrayForEach(id, ids)
{
char key[24];
if (cJSON_IsNumber(id)) {
snprintf(key, sizeof(key), "%d", (int)id->valuedouble);
} else if (cJSON_IsString(id)) {
snprintf(key, sizeof(key), "%s", id->valuestring);
} else {
continue;
}
cJSON *p = preset_payload(key);
if (!p) {
continue;
}
cJSON_AddItemToObject(presets, key, p);
count++;
}
if (sent) {
*sent = count;
}
esp_err_t ret = ESP_ERR_NOT_FOUND;
if (count) {
if (save) {
cJSON_AddTrueToObject(msg, "save");
}
if (!cJSON_IsArray(targets) || cJSON_GetArraySize(targets) == 0) {
rel_bump_ver();
}
wifi_store_presets(presets, targets, def);
ret = push_binary(msg, targets);
// The startup preset needs the driver names (the driver checks it is addressed); targeted sends only
if (ret == ESP_OK && def && cJSON_GetObjectItem(presets, def) && cJSON_IsArray(targets)) {
cJSON *names = cJSON_CreateArray();
const cJSON *t;
cJSON_ArrayForEach(t, targets)
{
uint8_t mac[6];
const char *n = cJSON_IsString(t) && parse_mac(t->valuestring, mac) ? device_name_for(mac) : NULL;
if (n) {
cJSON_AddItemToArray(names, cJSON_CreateString(n));
}
}
if (cJSON_GetArraySize(names)) {
cJSON *d = cJSON_CreateObject();
cJSON_AddStringToObject(d, "v", "1");
cJSON_AddStringToObject(d, "default", def);
cJSON_AddItemToObject(d, "targets", names);
names = NULL;
ret = push_json(d, targets);
cJSON_Delete(d);
}
cJSON_Delete(names);
}
}
store_unlock();
cJSON_Delete(msg);
return ret;
}
static const char *device_name_for(const uint8_t mac[6])
{
char hex[13];
snprintf(hex, sizeof(hex), "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
const cJSON *addr = cJSON_GetObjectItem(d, "address"), *name = cJSON_GetObjectItem(d, "name");
if (cJSON_IsString(name) && (strcasecmp(d->string, hex) == 0 || (cJSON_IsString(addr) && strcasecmp(addr->valuestring, hex) == 0))) {
return name->valuestring;
}
}
return NULL;
}
/* Unicast helpers: acked and retransmitted by the link */
static esp_err_t send_cmd(const uint8_t mac[6], const uint8_t *env, size_t len, bool commit)
{
uint8_t wire[REL_FRAG_MAX];
if (len + 2 > sizeof(wire)) {
return ESP_ERR_INVALID_SIZE;
}
wire[0] = 0x4C;
wire[1] = 0x03; // CMD
memcpy(wire + 2, env, len);
return rel_send(mac, wire, len + 2, commit, 1);
}
// GROUPS packet: the driver's own group d<mac> (sequences address single drivers with it), then every
// group and zone it belongs to. A list with nothing but its own group replaces whatever the driver
// stored, so it is only sent when allow_empty is set (a zone or device was edited); a driver that merely
// announced itself and is in no zone keeps the groups it already has.
// Wire: [4C][02][count] then per id [len][id]. Returns its length; *count gets the number of groups and
// zones (not counting its own group).
static size_t build_groups(uint8_t pkt[REL_FRAG_MAX], const uint8_t mac[6], const char *name, int *count)
{
size_t off = 3;
*count = 0;
const cJSON *g;
char gid[GROUP_ID_MAX];
// Its own group first, so a long list never cuts it off
pkt[off++] = 13;
off += snprintf((char *)pkt + off, REL_FRAG_MAX - off, "d%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3],
mac[4], mac[5]);
cJSON_ArrayForEach(g, store_coll("group"))
{
size_t gl = strlen(g->string);
if (gl < GROUP_ID_MAX && off + 1 + gl <= REL_FRAG_MAX && in_group(mac, name, g->string)) {
pkt[off++] = gl;
memcpy(pkt + off, g->string, gl);
off += gl;
(*count)++;
}
}
const cJSON *z;
cJSON_ArrayForEach(z, store_coll("zone"))
{
const cJSON *names = cJSON_GetObjectItem(z, "names");
snprintf(gid, sizeof(gid), "z%s", z->string);
size_t gl = strlen(gid);
if (cJSON_IsArray(names) && name_seen(names, cJSON_GetArraySize(names), name) && off + 1 + gl <= REL_FRAG_MAX &&
gl < GROUP_ID_MAX - 1) {
pkt[off++] = gl;
memcpy(pkt + off, gid, gl);
off += gl;
(*count)++;
}
}
pkt[0] = 0x4C;
pkt[1] = 0x02; // GROUPS
pkt[2] = *count + 1; // *count leaves out the driver's own group
return off;
}
static void send_groups(const uint8_t mac[6], const char *name, bool allow_empty)
{
uint8_t pkt[REL_FRAG_MAX];
int count;
size_t len = build_groups(pkt, mac, name, &count);
if (count == 0 && !allow_empty) {
return;
}
// 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])
{
return parse_mac(s, mac);
}
/* Drivers that stopped acking (switched off, out of range). Every unicast to one holds a pending slot
for its whole retry run, so a few zone edits would fill the link and starve the next zone play.
Group updates go to such a driver at most once per DEAD_RETRY_US; a driver that comes back gets its
groups when it announces (boot) or resyncs (missed state). */
#define DEAD_FAILS 3
#define DEAD_RETRY_US (30LL * 1000000)
static struct {
uint8_t mac[6];
int64_t tried_us;
} s_dead[16];
static bool skip_unresponsive(const uint8_t mac[6])
{
int fails;
rel_peer_status(mac, &fails);
if (fails < DEAD_FAILS) {
return false;
}
int slot = 0;
for (int i = 0; i < 16; i++) {
if (!memcmp(s_dead[i].mac, mac, 6)) {
slot = i;
break;
}
if (s_dead[i].tried_us < s_dead[slot].tried_us) {
slot = i; // oldest entry, if this driver has none
}
}
int64_t now = esp_timer_get_time();
if (!memcmp(s_dead[slot].mac, mac, 6) && now - s_dead[slot].tried_us < DEAD_RETRY_US) {
return true;
}
memcpy(s_dead[slot].mac, mac, 6);
s_dead[slot].tried_us = now;
return false;
}
/* 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");
const char *hex = cJSON_IsString(addr) ? addr->valuestring : d->string;
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;
}
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)
{
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;
}
vTaskDelay(pdMS_TO_TICKS(5));
}
}
// All are in flight at once; then collect each outcome (rel gives up after about 2 s)
*total = n;
*sent = *failed = 0;
for (int i = 0; i < n; i++) {
bool ok = out[i].queued && rel_wait(out[i].mac, out[i].seq, 3000) == ESP_OK;
if (ok) {
(*sent)++;
} else {
(*failed)++;
}
}
free(out);
}
// A driver said hello at boot: register it, then tell it which zones it belongs to
// Groups that list key from list to instead
static void groups_rename(const char *from, const char *to)
{
cJSON *g;
cJSON_ArrayForEach(g, store_coll("group"))
{
cJSON *list = cJSON_GetObjectItem(g, "devices");
for (int i = 0; list && i < cJSON_GetArraySize(list); i++) {
cJSON *it = cJSON_GetArrayItem(list, i);
if (cJSON_IsString(it) && !strcmp(it->valuestring, from)) {
cJSON_ReplaceItemInArray(list, i, cJSON_CreateString(to));
}
}
}
}
// Move a device to a new key and transport, keeping its fields. Groups that listed the old key list the
// new one. ESP-NOW devices are keyed by MAC and Wi-Fi devices by hostname, so a board that changes
// mode changes key. Caller holds the store lock.
static void device_rekey(const char *from, const char *to, const char *transport, const char *address)
{
cJSON *devs = store_coll("device");
cJSON *old = cJSON_GetObjectItem(devs, from);
if (!old || !strcmp(from, to)) {
return;
}
cJSON *rec = cJSON_Duplicate(old, 1);
api_set(rec, "id", cJSON_CreateString(to));
api_set(rec, "transport", cJSON_CreateString(transport));
api_set(rec, "address", cJSON_CreateString(address));
cJSON_DeleteItemFromObject(devs, from);
cJSON_DeleteItemFromObject(devs, to); // a record discovery made for the same board
cJSON_AddItemToObject(devs, to, rec);
groups_rename(from, to);
store_save("device");
store_save("group");
ESP_LOGI(TAG, "device %s is now %s (%s)", from, transport, to);
}
// Keep the record under key to (its settings and zones) and drop from, which is the same board on the other
// transport. Falls back to a move when there is no record under to.
static void device_fold(const char *from, const char *to, const char *transport, const char *address)
{
cJSON *devs = store_coll("device");
cJSON *keep = cJSON_GetObjectItem(devs, to);
if (!keep) {
device_rekey(from, to, transport, address);
return;
}
// The configured record wins: its settings and zones go onto the record discovery made
const cJSON *old = cJSON_GetObjectItem(devs, from);
for (const cJSON *c = old ? old->child : NULL; c; c = c->next) {
if (c->string && strcmp(c->string, "id") && strcmp(c->string, "transport") &&
strcmp(c->string, "address") && strcmp(c->string, "mac")) {
api_set(keep, c->string, cJSON_Duplicate(c, 1));
}
}
cJSON_DeleteItemFromObject(devs, from);
api_set(keep, "transport", cJSON_CreateString(transport));
api_set(keep, "address", cJSON_CreateString(address));
groups_rename(from, to);
store_save("device");
store_save("group");
ESP_LOGI(TAG, "device %s is now %s (%s), settings kept", from, transport, to);
}
// A Wi-Fi driver reported its MAC (its status). Remember it on its record. An ESP-NOW record with the same
// MAC is the same board, now on Wi-Fi: it becomes the Wi-Fi device under the hostname.
void engine_wifi_mac(const char *host, const char *mac)
{
store_lock();
cJSON *devs = store_coll("device");
const cJSON *esp = cJSON_GetObjectItem(devs, mac);
const cJSON *et = esp ? cJSON_GetObjectItem(esp, "transport") : NULL;
if (cJSON_IsString(et) && !strcmp(et->valuestring, "espnow")) {
char addr[WIFI_DRV_ID_MAX + 8];
snprintf(addr, sizeof(addr), "%s.local", host);
device_fold(mac, host, "wifi", addr);
}
cJSON *rec = cJSON_GetObjectItem(devs, host);
const cJSON *m = rec ? cJSON_GetObjectItem(rec, "mac") : NULL;
if (rec && !(cJSON_IsString(m) && !strcmp(m->valuestring, mac))) {
api_set(rec, "mac", cJSON_CreateString(mac));
store_save("device");
}
store_unlock();
}
static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len)
{
char name[48] = "";
char *cfg = NULL; // the driver's settings as JSON
int cfg_len = 0;
if (pkt[0] == '{') {
cJSON *j = cJSON_ParseWithLength((const char *)pkt, len);
const cJSON *n = cJSON_GetObjectItem(j, "name");
if (cJSON_IsString(n)) {
snprintf(name, sizeof(name), "%s", n->valuestring);
}
const cJSON *c = cJSON_GetObjectItem(j, "cfg");
if (cJSON_IsObject(c)) {
cfg = cJSON_PrintUnformatted(c);
cfg_len = cfg ? (int)strlen(cfg) : 0;
}
cJSON_Delete(j);
} else if (len > 3 && pkt[2] > 0 && 3 + pkt[2] <= len) { // 4C 01 <len><name> ...
snprintf(name, sizeof(name), "%.*s", pkt[2] < sizeof(name) - 1 ? pkt[2] : (int)sizeof(name) - 1, pkt + 3);
int co = 3 + pkt[2] + 6; // after u16 num_leds, colour order, startup mode, brightness, type: [len][json]
if (co < len && pkt[co] > 0 && co + 1 + pkt[co] <= len) {
cfg = (char *)pkt + co + 1;
cfg_len = pkt[co];
}
}
if (!name[0]) {
if (pkt[0] == '{') {
free(cfg);
}
return;
}
char hex[13];
snprintf(hex, sizeof(hex), "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
store_lock();
cJSON *devs = store_coll("device");
// A board that was a Wi-Fi device (keyed by hostname) and is back on ESP-NOW: same MAC, new key
if (!cJSON_GetObjectItem(devs, hex)) {
const cJSON *d;
char from[WIFI_DRV_ID_MAX + 1] = "";
cJSON_ArrayForEach(d, devs)
{
const cJSON *m = cJSON_GetObjectItem(d, "mac");
if (cJSON_IsString(m) && !strcmp(m->valuestring, hex)) {
snprintf(from, sizeof(from), "%s", d->string);
break;
}
}
if (from[0]) {
device_rekey(from, hex, "espnow", hex);
}
}
cJSON *rec = cJSON_GetObjectItem(devs, hex);
const cJSON *old = cJSON_GetObjectItem(rec, "name");
// 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);
cJSON_AddStringToObject(rec, "name", name);
cJSON_AddStringToObject(rec, "type", "led");
cJSON_AddStringToObject(rec, "transport", "espnow");
cJSON_AddStringToObject(rec, "address", hex);
api_apply_driver_cfg(rec, cfg, cfg_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 {
bool changed = false;
if (!cJSON_IsString(old) || strcmp(old->valuestring, name) != 0) {
cJSON_ReplaceItemInObject(rec, "name", cJSON_CreateString(name));
changed = true;
}
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) {
cJSON_AddTrueToObject(rec, "sim");
}
changed = true;
}
if (changed) {
store_save("device");
}
}
if (pkt[0] == '{') {
free(cfg);
}
// 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 */
static void resync_driver(const uint8_t mac[6])
{
uint8_t frame[ENV_FRAME_MAX];
store_lock();
const char *name = device_name_for(mac);
if (name) {
send_groups(mac, name, false); // membership first, in case the driver lost it
}
const zone_cur_t *best = NULL;
for (int i = 0; name && i < 16; i++) {
if (s_cur[i].zone[0] && driver_in_zone(mac, name, s_cur[i].zone) &&
(!best || (int16_t)(s_cur[i].ver - best->ver) > 0)) {
best = &s_cur[i];
}
}
bool sent = false;
if (best) {
if (strcmp(best->preset, "off") != 0) {
cJSON *payload = preset_payload(best->preset);
env_blob_t pb;
env_blob_init(&pb);
if (payload && env_add_preset(&pb, best->preset, payload)) {
send_cmd(mac, frame, env_frame(frame, -1, &pb, NULL), false);
}
cJSON_Delete(payload);
}
env_blob_t sb;
env_blob_init(&sb);
if (env_add_select(&sb, name, best->preset, -1)) {
sent = send_cmd(mac, frame, env_frame(frame, -1, NULL, &sb), true) == ESP_OK;
}
}
if (!sent) { // nothing to replay: an empty envelope still lets the driver adopt the version
send_cmd(mac, frame, env_frame(frame, -1, NULL, NULL), true);
}
store_unlock();
}
esp_err_t engine_init(void)
{
wifi_drv_init();
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;
}
bool engine_mac_in_zone(const char *hex12, const char *zone_id)
{
uint8_t mac[6];
if (!hex_mac(hex12, mac)) {
return false;
}
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;
}