feat: device groups, combined brightness and beat-driven sequences from main

Groups (registry of driver MACs, optionally scoped to a profile) become
the drivers' group membership, alongside z<zone id> for zones that still
name drivers. Zones play to their group_ids. Group and device routes for
driver config, brightness (global x groups x device x zone) and identify.
The push path takes main's message shape: select as a list, groups as a
filter (one GROUP_CMD per group, or JSON when a preset has a background),
short keys so JSON fits a frame.

Sequences follow main: lanes of {preset_id, beats} steps played to each
lane's groups, advanced by the mic's beats or a clock at
audio_simulated_bpm; a switch waits for the next beat or downbeat; sync-
phase, stop (clears the zone's drivers) and status. This replaces the
time-based per-zone sequencer and scene playback, as in main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-11-03 18:09:42 +13:00
1 parent 19fea0b0a1
commit 04b56c6ef2
12 files changed
+1922 -579

No files matched your search

+327 -372
View File
@@ -17,7 +17,6 @@
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 */
@@ -53,7 +52,7 @@ static bool parse_mac(const char *s, uint8_t mac[6])
// 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 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
@@ -109,59 +108,78 @@ static esp_err_t emit_c(const cJSON *targets, const uint8_t *frame, size_t len,
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)
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");
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);
int n = cJSON_IsArray(refs) && cJSON_IsArray(colors) ? cJSON_GetArraySize(colors) : 0;
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));
}
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)
@@ -182,18 +200,104 @@ static bool name_seen(const cJSON *names, int upto, const char *name)
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.
/* 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]);
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;
}
// 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);
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;
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 */
@@ -223,12 +327,9 @@ static void zone_cur_set(const char *zone_id, const char *preset_id)
}
}
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) {
if (!cJSON_GetObjectItem(store_coll("zone"), zone_id)) {
return ESP_ERR_NOT_FOUND;
}
cJSON *payload = preset_payload(preset_id);
@@ -244,10 +345,7 @@ static esp_err_t play_locked(const char *zone_id, const char *preset_id)
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;
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);
}
@@ -260,7 +358,6 @@ static esp_err_t play_locked(const char *zone_id, const char *preset_id)
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;
@@ -269,11 +366,9 @@ esp_err_t engine_play(const char *zone_id, const char *preset_id)
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) {
esp_err_t ret = select_zone(zone_id, "off");
if (ret == ESP_OK) {
zone_cur_set(zone_id, "off");
}
store_unlock();
@@ -290,7 +385,16 @@ static bool only_binary_keys(const cJSON *m)
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")) {
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;
}
}
@@ -309,7 +413,7 @@ static esp_err_t push_binary(const cJSON *m, const cJSON *targets)
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;
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)
@@ -335,6 +439,14 @@ static esp_err_t push_binary(const cJSON *m, const cJSON *targets)
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;
@@ -373,65 +485,143 @@ static esp_err_t push_binary(const cJSON *m, const cJSON *targets)
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)
// 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" },
};
static const char *const PRESET_KEYS[] = { "p", "c", "d", "b", "a", "bg", "n1", "n2", "n3", "n4", "n5", "n6" };
static const char *short_key(const char *const map[][2], size_t n, const char *k)
{
char *s = cJSON_PrintUnformatted(m);
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;
if (strlen(s) <= JSON_MAX) {
ret = emit_c(targets, (const uint8_t *)s, strlen(s), 1, true);
free(s);
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;
}
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");
// 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;
}
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 *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);
}
cJSON_AddItemReferenceToObject(bp, it->string, (cJSON *)it);
cur += need;
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, "presets")) {
if (strcmp(k->string, "v") && strcmp(k->string, "p") && !cJSON_GetObjectItem(batch, k->string)) {
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);
}
esp_err_t e = emit_json(targets, batch, true);
ret = e != ESP_OK ? e : ret;
cJSON_Delete(batch);
cJSON_Delete(m);
return ret;
}
@@ -448,7 +638,24 @@ esp_err_t engine_push(const cJSON *messages, const cJSON *targets)
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);
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;
}
@@ -523,266 +730,6 @@ esp_err_t engine_send_presets(const cJSON *ids, bool save, const char *def, cons
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;
}
cJSON *engine_seq_status(void)
{
cJSON *o = cJSON_CreateObject();
store_lock();
for (int i = 0; i < MAX_RUNNERS; i++) {
const runner_t *r = &s_run[i];
if (!r->used) {
continue;
}
cJSON *s = cJSON_AddObjectToObject(o, r->seq);
cJSON_AddStringToObject(s, "sequence_id", r->seq);
cJSON_AddStringToObject(s, "zone_id", r->zone);
cJSON_AddNumberToObject(s, "step_index", r->step);
cJSON_AddNumberToObject(s, "pass", r->rounds);
const cJSON *steps = steps_of(r->seq);
const cJSON *pid = cJSON_GetObjectItem(cJSON_GetArrayItem(steps, r->step), "preset_id");
cJSON_AddItemToObject(s, "preset_id", pid ? cJSON_Duplicate(pid, false) : cJSON_CreateNull());
cJSON_AddTrueToObject(s, "running");
}
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];
@@ -816,19 +763,32 @@ static esp_err_t send_cmd(const uint8_t mac[6], const uint8_t *env, size_t len,
// a driver that merely announced itself and is in no zone keeps the groups it already has.
// GROUPS packet for a driver: [4C][02][count] then per zone [len][zone id]. Returns its length;
// *count gets the number of zones.
static size_t build_groups(uint8_t pkt[REL_FRAG_MAX], const char *name, int *count)
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];
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");
size_t gl = strlen(z->string);
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 < 16) {
gl < GROUP_ID_MAX - 1) {
pkt[off++] = gl;
memcpy(pkt + off, z->string, gl);
memcpy(pkt + off, gid, gl);
off += gl;
(*count)++;
}
@@ -843,7 +803,7 @@ 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, name, &count);
size_t len = build_groups(pkt, mac, name, &count);
if (count == 0 && !allow_empty) {
return;
}
@@ -932,7 +892,7 @@ void engine_groups_push_all(int *total, int *sent, int *failed)
hex_mac(hex, out[n].mac)) {
uint8_t pkt[REL_FRAG_MAX];
int count;
size_t len = build_groups(pkt, name->valuestring, &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);
@@ -1010,8 +970,7 @@ static void resync_driver(const uint8_t mac[6])
}
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) &&
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];
}
@@ -1043,9 +1002,5 @@ 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;
}