#include "engine.h" #include #include #include #include #include #include "envelope.h" #include "esp_log.h" #include "esp_timer.h" #include "espnow_tx.h" #include "rel.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 MAX_RUNNERS 8 #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[16]; // zone being played; "" = 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) { // not a v2 envelope 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; } static esp_err_t emit(const cJSON *targets, const uint8_t *frame, size_t len, int repeat) { return emit_c(targets, frame, len, repeat, false); } /* --------------------------------------------------------------- presets */ // Preset record with palette references applied. Caller deletes the result. static cJSON *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); cJSON *refs = cJSON_GetObjectItem(out, "palette_refs"); cJSON *colors = cJSON_GetObjectItem(out, "colors"); if (!cJSON_IsArray(refs) || !cJSON_IsArray(colors)) { return out; } cJSON *pid = cJSON_GetObjectItem(out, "profile_id"); char pidbuf[24] = ""; if (cJSON_IsString(pid)) { snprintf(pidbuf, sizeof(pidbuf), "%s", pid->valuestring); } else if (cJSON_IsNumber(pid)) { snprintf(pidbuf, sizeof(pidbuf), "%d", (int)pid->valuedouble); } cJSON *profile = cJSON_GetObjectItem(store_coll("profile"), pidbuf); cJSON *palid = cJSON_GetObjectItem(profile, "palette_id"); char palbuf[24] = ""; if (cJSON_IsString(palid)) { snprintf(palbuf, sizeof(palbuf), "%s", palid->valuestring); } else if (cJSON_IsNumber(palid)) { snprintf(palbuf, sizeof(palbuf), "%d", (int)palid->valuedouble); } cJSON *pal = cJSON_GetObjectItem(store_coll("palette"), palbuf); if (!cJSON_IsArray(pal)) { return out; } int n = cJSON_GetArraySize(colors); for (int i = 0; i < n; i++) { cJSON *ref = cJSON_GetArrayItem(refs, i); if (cJSON_IsNumber(ref)) { int idx = (int)ref->valuedouble; cJSON *c = cJSON_GetArrayItem(pal, idx); if (idx >= 0 && c && (cJSON_IsString(c) ? c->valuestring[0] : true)) { cJSON_ReplaceItemInArray(colors, i, cJSON_Duplicate(c, true)); } } } return out; } /* ------------------------------------------------------------ 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; } // Select a preset for the whole zone: one GROUP_CMD, applied by every driver in the zone's group. // 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); snprintf(s_gid, sizeof(s_gid), "%s", zone_id); esp_err_t ret = emit_c(NULL, frame, env_frame(frame, -1, NULL, &sel), FRAME_REPEAT, true); s_gid[0] = 0; return ret; } /* 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 void runner_stop_zone(const char *zone_id); static esp_err_t play_locked(const char *zone_id, const char *preset_id) { const cJSON *names = zone_names(zone_id); if (!names) { return ESP_ERR_NOT_FOUND; } cJSON *payload = preset_payload(preset_id); if (!payload) { return ESP_ERR_NOT_FOUND; } 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; } size_t len = env_frame(frame, -1, &pb, NULL); snprintf(s_gid, sizeof(s_gid), "%s", zone_id); esp_err_t ret = emit(NULL, frame, len, FRAME_REPEAT); s_gid[0] = 0; if (ret == ESP_OK) { ret = select_zone(zone_id, preset_id); } if (ret == ESP_OK) { zone_cur_set(zone_id, preset_id); } return ret; } esp_err_t engine_play(const char *zone_id, const char *preset_id) { store_lock(); runner_stop_zone(zone_id); // a manual pick ends that zone's sequence 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(); runner_stop_zone(zone_id); const cJSON *names = zone_names(zone_id); rel_bump_ver(); esp_err_t ret = names ? select_zone(zone_id, "off") : ESP_ERR_NOT_FOUND; if (names) { 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")) { 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) && 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); 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; } // JSON text path for keys the binary envelope cannot carry (save, default, manifest, ...) static esp_err_t push_json(const cJSON *m, const cJSON *targets) { char *s = cJSON_PrintUnformatted(m); if (!s) { return ESP_ERR_NO_MEM; } esp_err_t ret; if (strlen(s) <= JSON_MAX) { ret = emit_c(targets, (const uint8_t *)s, strlen(s), 1, true); free(s); return ret; } free(s); // Too big: split the presets over several messages, the other keys go on the last one const cJSON *presets = cJSON_GetObjectItem(m, "presets"); if (!cJSON_IsObject(presets)) { return ESP_ERR_INVALID_SIZE; } const size_t base = strlen("{\"v\":\"1\",\"presets\":{}}"); const size_t room = JSON_MAX - 48; // keep space for save/default on the last message ret = ESP_OK; cJSON *batch = cJSON_CreateObject(); cJSON_AddStringToObject(batch, "v", "1"); cJSON *bp = cJSON_AddObjectToObject(batch, "presets"); size_t cur = base; const cJSON *it; cJSON_ArrayForEach(it, presets) { char *ps = cJSON_PrintUnformatted(it); size_t need = (ps ? strlen(ps) : 0) + strlen(it->string) + 4; free(ps); if (bp->child && cur + need > room) { char *out = cJSON_PrintUnformatted(batch); ret = emit(targets, (const uint8_t *)out, strlen(out), 1); free(out); cJSON_Delete(batch); batch = cJSON_CreateObject(); cJSON_AddStringToObject(batch, "v", "1"); bp = cJSON_AddObjectToObject(batch, "presets"); cur = base; } cJSON_AddItemReferenceToObject(bp, it->string, (cJSON *)it); cur += need; } const cJSON *k; cJSON_ArrayForEach(k, m) { if (strcmp(k->string, "v") && strcmp(k->string, "presets")) { cJSON_AddItemReferenceToObject(batch, k->string, (cJSON *)k); } } char *out = cJSON_PrintUnformatted(batch); if (out) { ret = emit_c(targets, (const uint8_t *)out, strlen(out), 1, true); free(out); } cJSON_Delete(batch); 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; } if (!cJSON_IsArray(targets) || cJSON_GetArraySize(targets) == 0) { rel_bump_ver(); // a broadcast state change: drivers that miss it resync from the digest } esp_err_t e = only_binary_keys(m) ? push_binary(m, targets) : push_json(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(); } 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; } /* ------------------------------------------------------------ sequencer */ typedef struct { bool used; char seq[16]; char zone[16]; int step; int rounds; int64_t deadline_us; } runner_t; static runner_t s_run[MAX_RUNNERS]; static TaskHandle_t s_task; static void set_active(const char *seq_id, bool on) { cJSON *rec = cJSON_GetObjectItem(store_coll("sequence"), seq_id); if (!rec) { return; } cJSON_DeleteItemFromObject(rec, "active"); cJSON_AddBoolToObject(rec, "active", on); store_save("sequence"); } static void runner_free(runner_t *r) { r->used = false; set_active(r->seq, false); } static void runner_stop_zone(const char *zone_id) { for (int i = 0; i < MAX_RUNNERS; i++) { if (s_run[i].used && strcmp(s_run[i].zone, zone_id) == 0) { runner_free(&s_run[i]); } } } static const cJSON *steps_of(const char *seq_id) { cJSON *rec = cJSON_GetObjectItem(store_coll("sequence"), seq_id); cJSON *steps = cJSON_GetObjectItem(rec, "steps"); return cJSON_IsArray(steps) && cJSON_GetArraySize(steps) ? steps : NULL; } static int64_t step_duration_us(const cJSON *step) { double d = 1.0; const cJSON *v = cJSON_GetObjectItem(step, "duration_s"); if (cJSON_IsNumber(v)) { d = v->valuedouble; } d = d < 0.5 ? 0.5 : (d > 600 ? 600 : d); return (int64_t)(d * 1e6); } // Play step r->step and move the deadline on from the previous deadline (no drift) static void run_step(runner_t *r, bool first) { const cJSON *steps = steps_of(r->seq); const cJSON *step = steps ? cJSON_GetArrayItem(steps, r->step) : NULL; if (!step) { runner_free(r); return; } const cJSON *pid = cJSON_GetObjectItem(step, "preset_id"); char key[24] = ""; if (cJSON_IsString(pid)) { snprintf(key, sizeof(key), "%s", pid->valuestring); } else if (cJSON_IsNumber(pid)) { snprintf(key, sizeof(key), "%d", (int)pid->valuedouble); } play_locked(r->zone, key); r->deadline_us = (first ? esp_timer_get_time() : r->deadline_us) + step_duration_us(step); } static void runner_advance(runner_t *r) { cJSON *rec = cJSON_GetObjectItem(store_coll("sequence"), r->seq); const cJSON *steps = steps_of(r->seq); if (!rec || !steps) { runner_free(r); return; } if (++r->step >= cJSON_GetArraySize(steps)) { r->step = 0; r->rounds++; const cJSON *loop = cJSON_GetObjectItem(rec, "loop"); const cJSON *rc = cJSON_GetObjectItem(rec, "repeat_count"); int repeat = cJSON_IsNumber(rc) ? (int)rc->valuedouble : 0; if (!cJSON_IsTrue(loop) || (repeat > 0 && r->rounds >= repeat)) { runner_free(r); return; } } run_step(r, false); } static void seq_task(void *arg) { for (;;) { int64_t next = INT64_MAX; store_lock(); int64_t now = esp_timer_get_time(); for (int i = 0; i < MAX_RUNNERS; i++) { runner_t *r = &s_run[i]; if (r->used && now >= r->deadline_us) { runner_advance(r); } if (r->used && r->deadline_us < next) { next = r->deadline_us; } } store_unlock(); TickType_t wait = portMAX_DELAY; if (next != INT64_MAX) { int64_t us = next - esp_timer_get_time(); wait = us <= 0 ? 0 : pdMS_TO_TICKS((us + 999) / 1000); } ulTaskNotifyTake(pdTRUE, wait); } } esp_err_t engine_seq_play(const char *seq_id) { store_lock(); cJSON *rec = cJSON_GetObjectItem(store_coll("sequence"), seq_id); cJSON *z = cJSON_GetObjectItem(rec, "zone_id"); char zone[16] = ""; if (cJSON_IsString(z)) { snprintf(zone, sizeof(zone), "%s", z->valuestring); } else if (cJSON_IsNumber(z)) { snprintf(zone, sizeof(zone), "%d", (int)z->valuedouble); } esp_err_t ret = ESP_ERR_NOT_FOUND; if (rec && zone[0] && steps_of(seq_id) && zone_names(zone)) { runner_stop_zone(zone); runner_t *slot = NULL; for (int i = 0; i < MAX_RUNNERS && !slot; i++) { slot = s_run[i].used ? NULL : &s_run[i]; } if (!slot) { ret = ESP_ERR_NO_MEM; } else { memset(slot, 0, sizeof(*slot)); slot->used = true; snprintf(slot->seq, sizeof(slot->seq), "%s", seq_id); snprintf(slot->zone, sizeof(slot->zone), "%s", zone); set_active(seq_id, true); run_step(slot, true); ret = ESP_OK; } } store_unlock(); if (s_task) { xTaskNotifyGive(s_task); } return ret; } esp_err_t engine_seq_stop(const char *seq_id) { esp_err_t ret = ESP_ERR_NOT_FOUND; store_lock(); for (int i = 0; i < MAX_RUNNERS; i++) { if (s_run[i].used && strcmp(s_run[i].seq, seq_id) == 0) { runner_free(&s_run[i]); ret = ESP_OK; } } set_active(seq_id, false); store_unlock(); return ret; } static esp_err_t scene_each(const char *scene_id, bool play) { store_lock(); cJSON *scene = cJSON_GetObjectItem(store_coll("scene"), scene_id); cJSON *seqs = cJSON_GetObjectItem(scene, "sequences"); esp_err_t ret = cJSON_IsArray(seqs) ? ESP_OK : ESP_ERR_NOT_FOUND; const cJSON *id; cJSON_ArrayForEach(id, seqs) { char key[16]; 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; } play ? engine_seq_play(key) : engine_seq_stop(key); } store_unlock(); return ret; } esp_err_t engine_scene_play(const char *scene_id) { return scene_each(scene_id, true); } esp_err_t engine_scene_stop(const char *scene_id) { return scene_each(scene_id, false); } cJSON *engine_status(void) { cJSON *o = cJSON_CreateObject(), *zones = cJSON_AddObjectToObject(o, "zones"); store_lock(); for (int i = 0; i < MAX_RUNNERS; i++) { if (s_run[i].used) { cJSON *z = cJSON_AddObjectToObject(zones, s_run[i].zone); cJSON_AddStringToObject(z, "sequence_id", s_run[i].seq); cJSON_AddNumberToObject(z, "step", s_run[i].step); cJSON_AddNumberToObject(z, "round", s_run[i].rounds); } } store_unlock(); return o; } static void resume_task(void *arg) { vTaskDelay(pdMS_TO_TICKS(2000)); store_lock(); const cJSON *rec; cJSON_ArrayForEach(rec, store_coll("sequence")) { if (cJSON_IsTrue(cJSON_GetObjectItem(rec, "active"))) { char key[16]; snprintf(key, sizeof(key), "%s", rec->string); engine_seq_play(key); } } store_unlock(); vTaskDelete(NULL); } /* A driver reported a stale state version: replay what its zone is playing, then commit the version */ 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 ids of every zone whose driver names include `name` static void send_groups(const uint8_t mac[6], const char *name) { uint8_t pkt[REL_FRAG_MAX]; size_t off = 3; int count = 0; const cJSON *z; cJSON_ArrayForEach(z, store_coll("zone")) { const cJSON *names = cJSON_GetObjectItem(z, "names"); size_t gl = strlen(z->string); if (cJSON_IsArray(names) && name_seen(names, cJSON_GetArraySize(names), name) && off + 1 + gl <= sizeof(pkt) && gl < 16) { pkt[off++] = gl; memcpy(pkt + off, z->string, gl); off += gl; count++; } } pkt[0] = 0x4C; pkt[1] = 0x02; // GROUPS pkt[2] = count; rel_send(mac, pkt, off, false, 1); } static bool hex_mac(const char *s, uint8_t mac[6]) { return parse_mac(s, mac); } // 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)) { send_groups(mac, name->valuestring); } } store_unlock(); } // A driver said hello at boot: register it, then tell it which zones it belongs to static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len) { char name[48] = ""; 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); } 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); } if (!name[0]) { 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"); cJSON *rec = cJSON_GetObjectItem(devs, hex); const cJSON *old = cJSON_GetObjectItem(rec, "name"); 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); store_save("device"); ESP_LOGI(TAG, "new driver %s (%s)", name, hex); } else if (!cJSON_IsString(old) || strcmp(old->valuestring, name) != 0) { cJSON_ReplaceItemInObject(rec, "name", cJSON_CreateString(name)); store_save("device"); } send_groups(mac, name); 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); // membership first, in case the driver lost it } const zone_cur_t *best = NULL; for (int i = 0; name && i < 16; i++) { const cJSON *names = s_cur[i].zone[0] ? zone_names(s_cur[i].zone) : NULL; if (names && name_seen(names, cJSON_GetArraySize(names), name) && (!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) { rel_set_resync_cb(resync_driver); rel_set_announce_cb(on_announce); if (xTaskCreate(seq_task, "sequencer", 6144, NULL, 4, &s_task) != pdPASS) { return ESP_ERR_NO_MEM; } xTaskCreate(resume_task, "seq_resume", 4096, NULL, 3, NULL); return ESP_OK; }