#include "engine.h" #include #include #include #include #include #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/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 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" 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". */ 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 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" or "d" 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') { return false; // a driver's own group is an ESP-NOW MAC } 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; } // 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; } zone_cur_t; static zone_cur_t s_cur[16]; 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(); } } 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]); } } 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" }, { "beat_time", "tb" }, }; static const char *const PRESET_KEYS[] = { "p", "c", "d", "b", "a", "bg", "n1", "n2", "n3", "n4", "n5", "n6", "f", "tb" }; 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 (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; } rel_send(mac, pkt, len, false, 1); } 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; } // Re-send group membership to every registered ESP-NOW driver (zones or devices changed) void engine_groups_changed(void) { 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"); 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); } } store_unlock(); } #define PUSH_MAX 32 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)); } n++; } } store_unlock(); // 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)++; } } } // 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 ... 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); 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"); } 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; } 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); } send_groups(mac, name, false); store_unlock(); } /* 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(); rel_set_resync_cb(resync_driver); rel_set_announce_cb(on_announce); return ESP_OK; }