From 04b56c6ef23ef1430266261677cb5b620717b249 Mon Sep 17 00:00:00 2001 From: jimmy Date: Tue, 3 Nov 2026 18:09:42 +1300 Subject: [PATCH] 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 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 --- main/CMakeLists.txt | 2 +- main/api.c | 62 ++-- main/api_util.h | 14 + main/engine.c | 699 +++++++++++++++++++++----------------------- main/engine.h | 29 +- main/main.c | 2 + main/res_device.c | 248 ++++++++++++---- main/res_group.c | 384 ++++++++++++++++++++++++ main/res_misc.c | 335 ++++++++++++++------- main/res_profile.c | 3 +- main/seqplay.c | 684 +++++++++++++++++++++++++++++++++++++++++++ main/seqplay.h | 39 +++ 12 files changed, 1922 insertions(+), 579 deletions(-) create mode 100644 main/res_group.c create mode 100644 main/seqplay.c create mode 100644 main/seqplay.h diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index 693a574..81b967f 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -1,5 +1,5 @@ idf_component_register(SRCS "main.c" "mic.c" "beat.c" "beat_dsp.c" "espnow_tx.c" "store.c" "api.c" "web.c" "envelope.c" "engine.c" "rel.c" "bench.c" "audio.c" "ota.c" "drv_ota.c" - "res_profile.c" "res_misc.c" "res_device.c" "patterns.c" "outputs.c" "ws.c" + "res_profile.c" "res_misc.c" "res_device.c" "res_group.c" "seqplay.c" "patterns.c" "outputs.c" "ws.c" INCLUDE_DIRS "." REQUIRES esp_eth esp_netif esp_event esp_driver_spi esp_driver_gpio nvs_flash app_update esp_app_format esp_http_server esp_timer esp_driver_i2s esp_wifi esp_rom json esp_driver_gpio diff --git a/main/api.c b/main/api.c index 297375e..b0afa9a 100644 --- a/main/api.c +++ b/main/api.c @@ -3,6 +3,7 @@ #include #include #include +#include #include "api_util.h" #include "cJSON.h" #include "esp_log.h" @@ -210,7 +211,7 @@ static bool route(const char *res, httpd_req_t *req, int n, api_seg_t seg, esp_e } ROUTERS[] = { { "profiles", profiles_route }, { "zones", zones_route }, { "presets", presets_route }, { "palettes", palettes_route }, { "sequences", sequences_route }, { "devices", devices_route }, - { "patterns", patterns_route }, { "outputs", outputs_route }, + { "patterns", patterns_route }, { "outputs", outputs_route }, { "groups", groups_route }, }; for (size_t i = 0; i < sizeof(ROUTERS) / sizeof(ROUTERS[0]); i++) { if (!strcmp(ROUTERS[i].res, res)) { @@ -238,14 +239,6 @@ static esp_err_t collection_handler_inner(httpd_req_t *req) cJSON *all = store_coll(coll); const int method = req->method; - if (n == 3 && method == HTTP_POST && !strcmp(seg[0], "scenes")) { - if (!strcmp(seg[2], "play")) { - return api_result(req, engine_scene_play(seg[1]), "Scene started"); - } - if (!strcmp(seg[2], "stop")) { - return api_result(req, engine_scene_stop(seg[1]), "Scene stopped"); - } - } if (n == 3) { return api_error(req, "404 Not Found", "unknown action"); } @@ -369,30 +362,42 @@ static esp_err_t put_settings(httpd_req_t *req) if (!body) { return ESP_OK; } - const cJSON *ch = cJSON_GetObjectItem(body, "wifi_channel"); - const cJSON *gb = cJSON_GetObjectItem(body, "global_brightness"); - const char *bad = (ch && !int_in(ch, 1, 11)) ? "wifi_channel must be an integer between 1 and 11" - : (gb && !int_in(gb, 0, 255)) ? "global_brightness must be an integer between 0 and 255" - : NULL; + static const struct { + const char *key; + int lo, hi; + const char *err; + } INTS[] = { + { "wifi_channel", 1, 11, "wifi_channel must be an integer between 1 and 11" }, + { "global_brightness", 0, 255, "global_brightness must be between 0 and 255" }, + { "audio_beat_phase_ms", 0, 500, "audio_beat_phase_ms must be between 0 and 500" }, + { "audio_input_volume", 0, 200, "audio_input_volume must be between 0 and 200" }, + }; + const char *bad = NULL; + for (size_t i = 0; i < sizeof(INTS) / sizeof(INTS[0]) && !bad; i++) { + const cJSON *v = cJSON_GetObjectItem(body, INTS[i].key); + if (v && !cJSON_IsNull(v) && !int_in(v, INTS[i].lo, INTS[i].hi)) { + bad = INTS[i].err; + } + } + const cJSON *sw = cJSON_GetObjectItem(body, "sequence_switch_wait"); + if (!bad && sw && !cJSON_IsNull(sw) && + !(cJSON_IsString(sw) && (!strcasecmp(sw->valuestring, "beat") || !strcasecmp(sw->valuestring, "downbeat")))) { + bad = "sequence_switch_wait must be beat or downbeat"; + } if (bad) { cJSON_Delete(body); return api_error(req, "400 Bad Request", bad); } - const cJSON *old = cJSON_GetObjectItem(store_settings(), "global_brightness"); - bool push = gb && !(cJSON_IsNumber(old) && old->valuedouble == gb->valuedouble); - int level = gb ? (int)gb->valuedouble : 0; + const cJSON *bpm = cJSON_GetObjectItem(body, "audio_simulated_bpm"); + if (bpm && !cJSON_IsNull(bpm)) { // clamped to the BPM range, like main's clamp_bpm + double v = cJSON_IsNumber(bpm) ? bpm->valuedouble : (cJSON_IsString(bpm) ? strtod(bpm->valuestring, NULL) : 120); + api_set(body, "audio_simulated_bpm", cJSON_CreateNumber((int)(v < 60 ? 60 : (v > 200 ? 200 : v)))); + } + // global_brightness is only stored: the UI pushes each driver its combined brightness + // (POST /devices//brightness, /groups//brightness) api_merge(store_settings(), body); cJSON_Delete(body); store_save("settings"); - if (push) { - // Server-wide brightness goes to every driver - cJSON *msgs = cJSON_CreateArray(), *m = cJSON_CreateObject(); - cJSON_AddStringToObject(m, "v", "1"); - cJSON_AddNumberToObject(m, "b", level); - cJSON_AddItemToArray(msgs, m); - engine_push(msgs, NULL); - cJSON_Delete(msgs); - } return api_message(req, "200 OK", "Settings updated successfully"); } @@ -406,7 +411,7 @@ static esp_err_t settings_handler_inner(httpd_req_t *req) if (n == 1 && req->method == HTTP_GET) { return api_json(req, "200 OK", store_settings(), false); } - if (n == 2 && strcmp(seg[1], "settings") == 0 && req->method == HTTP_PUT) { + if (req->method == HTTP_PUT && (n == 1 || (n == 2 && strcmp(seg[1], "settings") == 0))) { return put_settings(req); } return api_error(req, "404 Not Found", "unknown settings route"); @@ -500,7 +505,10 @@ LOCKED(test_handler) esp_err_t api_register(httpd_handle_t server) { + store_lock(); api_settings_defaults(); + api_migrate_sequences(); + store_unlock(); static const char *const ROUTES[] = { "/devices*", "/zones*", "/presets*", "/profiles*", "/palettes*", "/patterns*", "/sequences*", "/scenes*", "/groups*", "/outputs*", diff --git a/main/api_util.h b/main/api_util.h index af37b2f..26678ac 100644 --- a/main/api_util.h +++ b/main/api_util.h @@ -34,10 +34,23 @@ bool api_id(const cJSON *v, char *buf, size_t len); // Add rec under the collection's next id (with an "id" field when rec is an object); id gets the key void api_add(const char *coll, cJSON *rec, char *id, size_t len); +// "aa:bb:..", "AA-BB-.." or "aabb.." -> lowercase 12-hex MAC; false when not a MAC +bool api_mac(const cJSON *v, char out[13]); +// device_config from the fields a request may set (name, num_leds, color_order, startup_mode); NULL when +// none is valid. Caller owns the result. +cJSON *api_driver_config(const cJSON *name, const cJSON *num_leds, const cJSON *color_order, const cJSON *startup); +// Combined 0..255 brightness for a driver: global x its groups x device [x zone_b when >= 0] +int api_effective_brightness(const char *mac, int zone_b); +// Blink every member of a group, then "off" +esp_err_t api_identify_group(const char *group_id); + // Current profile id (settings.current_profile_id, else the first profile), or NULL const char *api_current_profile(void); bool api_preset_in_profile(const cJSON *rec); +// Bring records written by older versions into the current shape (at boot) +void api_migrate_sequences(void); + // Resource handlers, called with the store locked. Each returns true when it answered the request // (its result in *ret); false hands the request to the generic collection CRUD. bool profiles_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); @@ -45,6 +58,7 @@ bool zones_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); bool presets_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); bool palettes_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); bool sequences_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); +bool groups_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); bool devices_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); bool patterns_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); bool outputs_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); diff --git a/main/engine.c b/main/engine.c index 1ac7250..84496cf 100644 --- a/main/engine.c +++ b/main/engine.c @@ -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 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" 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]); + 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; } diff --git a/main/engine.h b/main/engine.h index 1572d69..cd6a233 100644 --- a/main/engine.h +++ b/main/engine.h @@ -4,15 +4,24 @@ #include "cJSON.h" #include "esp_err.h" -// Zone play/stop, preset push/send and the sequencer. Drivers run the patterns -// themselves; this builds preset + select frames and hands them to ESP-NOW. +// Zone play/stop and preset push/send. Drivers run the patterns themselves; this builds preset + +// select frames and hands them to ESP-NOW. Sequences are played by seqplay.c. -// Start the sequencer task; sequences marked active resume after a short delay +// Hook driver announce and resync replies esp_err_t engine_init(void); -// Select a preset on every driver named in the zone (broadcast, sent twice) +#define GROUP_ID_MAX 20 +#define ZONE_TARGETS_MAX 12 +// Group ids a zone plays to: its group_ids, plus "z" when it names drivers directly (zones +// from before groups). -1 when the zone does not exist. Call with the store locked. +int engine_zone_targets(const char *zone_id, char out[][GROUP_ID_MAX], int max); +// A preset ready to send: palette colours and background resolved, mode as n6. Caller owns it; +// NULL when there is no such preset. Call with the store locked. +cJSON *engine_preset_payload(const char *preset_id); + +// Select a preset on every driver in the zone's groups (broadcast, sent twice) esp_err_t engine_play(const char *zone_id, const char *preset_id); -// Turn the zone's drivers off and stop its sequence +// Turn the zone's drivers off esp_err_t engine_stop(const char *zone_id); // POST /presets/push: v1 messages for targets (MAC strings), or broadcast when targets is NULL @@ -20,16 +29,6 @@ esp_err_t engine_push(const cJSON *messages, const cJSON *targets); // POST /presets/send: presets from the current profile by id esp_err_t engine_send_presets(const cJSON *ids, bool save, const char *def, const cJSON *targets, int *sent); -esp_err_t engine_seq_play(const char *seq_id); -esp_err_t engine_seq_stop(const char *seq_id); -esp_err_t engine_scene_play(const char *scene_id); -esp_err_t engine_scene_stop(const char *scene_id); - -// Caller owns the result -cJSON *engine_status(void); -// Running sequences: {: {sequence_id, zone_id, step_index, pass, preset_id, running}}; caller owns it -cJSON *engine_seq_status(void); - // Zones or devices changed: re-send group membership to every registered ESP-NOW driver void engine_groups_changed(void); // POST /devices/groups: send every ESP-NOW driver its groups, including silent ones, and wait for the diff --git a/main/main.c b/main/main.c index bffb26e..c682277 100644 --- a/main/main.c +++ b/main/main.c @@ -32,6 +32,7 @@ #include "ws.h" #include "api.h" #include "engine.h" +#include "seqplay.h" #include "rel.h" #include "web.h" #include "audio.h" @@ -380,4 +381,5 @@ void app_main(void) ESP_ERROR_CHECK(rel_init()); ESP_ERROR_CHECK(engine_init()); ESP_ERROR_CHECK(mic_start()); + ESP_ERROR_CHECK(seqplay_init()); } diff --git a/main/res_device.c b/main/res_device.c index c3c898c..19b395b 100644 --- a/main/res_device.c +++ b/main/res_device.c @@ -17,26 +17,6 @@ #define IDENTIFY_OFF_MS 2000 -// "aa:bb:cc:dd:ee:ff", "AA-BB-..." or "aabbccddeeff" -> "aabbccddeeff"; false when not a MAC -static bool normalize_mac(const cJSON *v, char out[13]) -{ - if (!cJSON_IsString(v)) { - return false; - } - int n = 0; - for (const char *s = v->valuestring; *s; s++) { - if (*s == ':' || *s == '-') { - continue; - } - if (!isxdigit((unsigned char)*s) || n == 12) { - return false; - } - out[n++] = tolower((unsigned char)*s); - } - out[n] = 0; - return n == 12; -} - // Trimmed copy of a string field; false when missing or blank static bool trimmed(const cJSON *v, char *buf, size_t len) { @@ -98,6 +78,11 @@ static const char *normalize_device(cJSON *dev, const char *mac) } } api_set(dev, "zones", out); + const cJSON *ob = cJSON_GetObjectItem(dev, "output_brightness"); + if (ob && !cJSON_IsNull(ob) && + !(cJSON_IsNumber(ob) && ob->valuedouble == (int)ob->valuedouble && ob->valuedouble >= 0 && ob->valuedouble <= 255)) { + return "output_brightness must be between 0 and 255"; + } if (!cJSON_GetObjectItem(dev, "default_pattern")) { cJSON_AddNullToObject(dev, "default_pattern"); } @@ -118,7 +103,7 @@ static cJSON *with_connected(const cJSON *dev) static cJSON *find(const char *id, char mac[13]) { cJSON *v = cJSON_CreateString(id); - bool ok = normalize_mac(v, mac); + bool ok = api_mac(v, mac); cJSON_Delete(v); if (!ok) { snprintf(mac, 13, "%.12s", id); @@ -138,8 +123,8 @@ static esp_err_t create_device(httpd_req_t *req) bool wifi = cJSON_IsString(tr) && !strcmp(tr->valuestring, "wifi"); if (!trimmed(cJSON_GetObjectItem(body, "name"), name, sizeof(name))) { err = "name is required"; - } else if (!normalize_mac(cJSON_GetObjectItem(body, "mac"), mac) && - (wifi || !normalize_mac(cJSON_GetObjectItem(body, "address"), mac))) { + } else if (!api_mac(cJSON_GetObjectItem(body, "mac"), mac) && + (wifi || !api_mac(cJSON_GetObjectItem(body, "address"), mac))) { err = "mac is required (12 hex digits); for Wi-Fi include mac plus IP in address"; } cJSON_DeleteItemFromObject(body, "id"); @@ -220,7 +205,7 @@ static esp_err_t update_device(httpd_req_t *req, cJSON *dev, const char *mac) } char other[13]; const cJSON *bm = cJSON_GetObjectItem(body, "mac"); - if (bm && !cJSON_IsNull(bm) && !(normalize_mac(bm, other) && !strcmp(other, mac))) { + if (bm && !cJSON_IsNull(bm) && !(api_mac(bm, other) && !strcmp(other, mac))) { cJSON_Delete(body); return api_error(req, "400 Bad Request", "cannot change device mac; delete and re-add"); } @@ -245,51 +230,206 @@ static esp_err_t update_device(httpd_req_t *req, cJSON *dev, const char *mac) return api_json(req, "200 OK", merged, false); } +// Identify: a red 10 Hz blink, then "off" two seconds later. A device is addressed by its MAC; a +// group by one broadcast its members filter on (they blink together). +static const char IDENTIFY_PRESET[] = "{\"__identify\":{\"p\":\"blink\",\"c\":[\"#ff0000\"],\"d\":50,\"b\":128," + "\"a\":true,\"n1\":0,\"n2\":0,\"n3\":0,\"n4\":0,\"n5\":0,\"n6\":0}}"; + typedef struct { - char mac[13]; - char name[64]; + char mac[13]; // "" when addressing a group + char group[24]; } identify_t; +static esp_err_t identify_send(const identify_t *id, bool on) +{ + cJSON *msg = cJSON_CreateObject(); + cJSON_AddStringToObject(msg, "v", "1"); + if (on) { + cJSON_AddItemToObject(msg, "presets", cJSON_Parse(IDENTIFY_PRESET)); + } + cJSON *sel = cJSON_AddArrayToObject(msg, "select"); + cJSON_AddItemToArray(sel, cJSON_CreateString(on ? "__identify" : "off")); + if (id->mac[0]) { + return push_to(id->mac, msg); + } + cJSON *groups = cJSON_AddArrayToObject(msg, "groups"); + cJSON_AddItemToArray(groups, cJSON_CreateString(id->group)); + cJSON *messages = cJSON_CreateArray(); + cJSON_AddItemToArray(messages, msg); + esp_err_t err = engine_push(messages, NULL); + cJSON_Delete(messages); + return err; +} + static void identify_off_task(void *arg) { identify_t *id = arg; vTaskDelay(pdMS_TO_TICKS(IDENTIFY_OFF_MS)); - cJSON *msg = cJSON_CreateObject(); - cJSON_AddStringToObject(msg, "v", "1"); - cJSON *sel = cJSON_AddObjectToObject(msg, "select"), *off = cJSON_AddArrayToObject(sel, id->name); - cJSON_AddItemToArray(off, cJSON_CreateString("off")); - push_to(id->mac, msg); + identify_send(id, false); free(id); vTaskDelete(NULL); } -// Blink the driver red at 10 Hz for two seconds, then select "off" +static esp_err_t identify_start(const char *mac, const char *group) +{ + identify_t *id = calloc(1, sizeof(*id)); + if (!id) { + return ESP_ERR_NO_MEM; + } + snprintf(id->mac, sizeof(id->mac), "%s", mac ? mac : ""); + snprintf(id->group, sizeof(id->group), "%s", group ? group : ""); + esp_err_t err = identify_send(id, true); + if (err != ESP_OK || xTaskCreate(identify_off_task, "identify", 6144, id, 3, NULL) != pdPASS) { + free(id); + } + return err; +} + +esp_err_t api_identify_group(const char *group_id) +{ + return identify_start(NULL, group_id); +} + static esp_err_t identify(httpd_req_t *req, const cJSON *dev, const char *mac) { - const cJSON *name = cJSON_GetObjectItem(dev, "name"); - if (!cJSON_IsString(name) || !name->valuestring[0]) { - return api_error(req, "400 Bad Request", "Device has no name"); - } if (!is_espnow(dev)) { return api_error(req, "503 Service Unavailable", "Wi-Fi driver not connected"); } - cJSON *msg = cJSON_Parse("{\"v\":\"1\",\"presets\":{\"__identify\":{\"p\":\"blink\",\"c\":[\"#ff0000\"],\"d\":50," - "\"b\":128,\"a\":true,\"n1\":0,\"n2\":0,\"n3\":0,\"n4\":0,\"n5\":0,\"n6\":0}}}"); - cJSON *sel = cJSON_AddObjectToObject(msg, "select"), *pick = cJSON_AddArrayToObject(sel, name->valuestring); - cJSON_AddItemToArray(pick, cJSON_CreateString("__identify")); - esp_err_t err = push_to(mac, msg); - if (err != ESP_OK) { + if (identify_start(mac, NULL) != ESP_OK) { return api_error(req, "503 Service Unavailable", "Identify send failed"); } - identify_t *id = malloc(sizeof(*id)); - if (id) { - snprintf(id->mac, sizeof(id->mac), "%s", mac); - snprintf(id->name, sizeof(id->name), "%s", name->valuestring); - if (xTaskCreate(identify_off_task, "identify", 6144, id, 3, NULL) != pdPASS) { - free(id); + return api_message(req, "200 OK", "Identify sent"); +} + +/* ------------------------------------------------------------- brightness */ + +static int clamp255(const cJSON *v, int dflt) +{ + if (!cJSON_IsNumber(v)) { + return dflt; + } + int b = (int)v->valuedouble; + return b < 0 ? 0 : (b > 255 ? 255 : b); +} + +// global x each group listing the MAC (none: no factor) x device output_brightness [x zone], each a +// 0..255 factor: round(f1/255 * f2/255 * ... * 255). zone_b < 0 leaves the zone out. +int api_effective_brightness(const char *mac, int zone_b) +{ + double v = clamp255(cJSON_GetObjectItem(store_settings(), "global_brightness"), 255) / 255.0; + const cJSON *g; + cJSON_ArrayForEach(g, store_coll("group")) + { + const cJSON *it; + cJSON_ArrayForEach(it, cJSON_GetObjectItem(g, "devices")) + { + char m[13]; + if (api_mac(it, m) && !strcmp(m, mac)) { + v *= clamp255(cJSON_GetObjectItem(g, "output_brightness"), 255) / 255.0; + break; + } } } - return api_message(req, "200 OK", "Identify sent"); + const cJSON *dev = cJSON_GetObjectItem(store_coll("device"), mac); + v *= clamp255(cJSON_GetObjectItem(dev, "output_brightness"), 255) / 255.0; + if (zone_b >= 0) { + v *= (zone_b > 255 ? 255 : zone_b) / 255.0; + } + int b = (int)(v * 255 + 0.5); + return b < 0 ? 0 : (b > 255 ? 255 : b); +} + +// zone_brightness from a body: -1 when absent, -2 (error sent) when invalid +static int zone_brightness(httpd_req_t *req, const cJSON *body) +{ + const cJSON *z = cJSON_GetObjectItem(body, "zone_brightness"); + if (!z || cJSON_IsNull(z)) { + return -1; + } + if (!cJSON_IsNumber(z) || z->valuedouble != (int)z->valuedouble || z->valuedouble < 0 || z->valuedouble > 255) { + api_error(req, "400 Bad Request", "output_brightness must be an integer 0–255"); + return -2; + } + return (int)z->valuedouble; +} + +// POST /devices/resolve-brightness {macs, zone_brightness?} -> {values: {mac: brightness}} +static esp_err_t resolve_brightness(httpd_req_t *req) +{ + cJSON *body = api_body_opt(req); + if (!body) { + return ESP_OK; + } + const cJSON *macs = cJSON_GetObjectItem(body, "macs"); + if (!cJSON_IsArray(macs)) { + cJSON_Delete(body); + return api_error(req, "400 Bad Request", "macs must be an array"); + } + int zb = zone_brightness(req, body); + if (zb == -2) { + cJSON_Delete(body); + return ESP_OK; + } + cJSON *o = cJSON_CreateObject(), *values = cJSON_AddObjectToObject(o, "values"); + const cJSON *it; + cJSON_ArrayForEach(it, macs) + { + char mac[13]; + if (api_mac(it, mac) && !cJSON_GetObjectItem(values, mac)) { + cJSON_AddNumberToObject(values, mac, api_effective_brightness(mac, zb)); + } + } + cJSON_Delete(body); + return api_json(req, "200 OK", o, true); +} + +// POST /devices//brightness {zone_brightness?}: the combined brightness, saved on the driver +static esp_err_t device_brightness(httpd_req_t *req, const char *mac) +{ + cJSON *body = api_body_opt(req); + if (!body) { + return ESP_OK; + } + int zb = zone_brightness(req, body); + cJSON_Delete(body); + if (zb == -2) { + return ESP_OK; + } + int b = api_effective_brightness(mac, zb); + cJSON *msg = cJSON_CreateObject(); + cJSON_AddStringToObject(msg, "v", "1"); + cJSON_AddNumberToObject(msg, "b", b); + cJSON_AddTrueToObject(msg, "save"); + if (push_to(mac, msg) != ESP_OK) { + return api_error(req, "503 Service Unavailable", "Send failed"); + } + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "message", "brightness sent"); + cJSON_AddNumberToObject(o, "brightness", b); + return api_json(req, "200 OK", o, true); +} + +// POST /devices//driver-config {name, num_leds, color_order, startup_mode} +static esp_err_t device_driver_config(httpd_req_t *req, const char *mac) +{ + cJSON *body = api_body_opt(req); + if (!body) { + return ESP_OK; + } + cJSON *dc = api_driver_config(cJSON_GetObjectItem(body, "name"), cJSON_GetObjectItem(body, "num_leds"), + cJSON_GetObjectItem(body, "color_order"), cJSON_GetObjectItem(body, "startup_mode")); + cJSON_Delete(body); + if (!dc) { + return api_error(req, "400 Bad Request", "Provide at least one of name, num_leds, color_order, startup_mode"); + } + cJSON *msg = cJSON_CreateObject(); + cJSON_AddStringToObject(msg, "v", "1"); + cJSON_AddItemToObject(msg, "device_config", dc); + cJSON_AddTrueToObject(msg, "save"); + if (push_to(mac, msg) != ESP_OK) { + return api_error(req, "503 Service Unavailable", "Send failed"); + } + return api_message(req, "200 OK", "driver-config sent"); } /* ------------------------------------------------------------------- ping */ @@ -501,6 +641,10 @@ bool devices_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) *ret = push_groups(req); return true; } + if (n == 2 && method == HTTP_POST && !strcmp(seg[1], "resolve-brightness")) { + *ret = resolve_brightness(req); + return true; + } if (n == 1) { if (method == HTTP_GET) { cJSON *o = cJSON_CreateObject(), *d; @@ -526,8 +670,12 @@ bool devices_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) if (n == 3) { if (method == HTTP_POST && !strcmp(seg[2], "identify")) { *ret = identify(req, dev, mac); + } else if (method == HTTP_POST && !strcmp(seg[2], "brightness")) { + *ret = device_brightness(req, mac); + } else if (method == HTTP_POST && !strcmp(seg[2], "driver-config")) { + *ret = device_driver_config(req, mac); } else if (method == HTTP_POST && !strcmp(seg[2], "patterns")) { - *ret = api_error(req, "404 Not Found", "use POST /patterns//send with device_id"); + *ret = api_error(req, "400 Bad Request", "Pattern OTA push is not supported for ESP-NOW devices; use POST /patterns//send"); } else { *ret = api_error(req, "404 Not Found", "unknown action"); } diff --git a/main/res_group.c b/main/res_group.c new file mode 100644 index 0000000..424c0c4 --- /dev/null +++ b/main/res_group.c @@ -0,0 +1,384 @@ +// Device groups: main's controllers/group.py and models/group.py. A group lists driver MACs +// ("devices"); drivers learn the ids of the groups they are in and zones play to groups. A group +// with a profile_id shows only while that profile is current; without one it is shared. + +#include +#include +#include +#include +#include "api_util.h" +#include "engine.h" +#include "store.h" + +static const char *const DEFAULTS = + "{\"name\":\"\",\"devices\":[],\"wifi_driver_display_name\":null,\"wifi_driver_num_leds\":null," + "\"wifi_color_order\":null,\"wifi_startup_mode\":null,\"output_brightness\":255,\"bridge_id\":null," + "\"pattern\":\"on\",\"colors\":[\"000000\",\"FF0000\"],\"brightness\":100,\"delay\":100,\"step_offset\":0," + "\"step_increment\":1,\"n1\":0,\"n2\":0,\"n3\":0,\"n4\":0,\"n5\":0,\"n6\":0,\"n7\":0,\"n8\":0}"; + +bool api_mac(const cJSON *v, char out[13]) +{ + if (!cJSON_IsString(v)) { + return false; + } + int n = 0; + for (const char *s = v->valuestring; *s; s++) { + if (*s == ':' || *s == '-' || isspace((unsigned char)*s)) { + continue; + } + if (!isxdigit((unsigned char)*s) || n == 12) { + return false; + } + out[n++] = tolower((unsigned char)*s); + } + out[n] = 0; + return n == 12; +} + +static bool visible(const cJSON *g) +{ + char pid[24]; + if (!api_id(cJSON_GetObjectItem(g, "profile_id"), pid, sizeof(pid))) { + return true; + } + const char *cur = api_current_profile(); + return cur && !strcmp(cur, pid); +} + +static cJSON *find(const char *id) +{ + cJSON *g = cJSON_GetObjectItem(store_coll("group"), id); + return cJSON_IsObject(g) && visible(g) ? g : NULL; +} + +// Devices as lowercase 12-hex MACs (other entries kept as they are) +static void normalize_devices(cJSON *g) +{ + cJSON *list = cJSON_GetObjectItem(g, "devices"); + if (!cJSON_IsArray(list)) { + api_set(g, "devices", cJSON_CreateArray()); + return; + } + cJSON *it; + cJSON_ArrayForEach(it, list) + { + char mac[13]; + if (api_mac(it, mac) && strcmp(it->valuestring, mac)) { + cJSON_SetValuestring(it, mac); + } + } +} + +// profile_id may only name the current profile (or be null for a shared group); bridges are gone +static void sanitize(cJSON *data) +{ + cJSON_DeleteItemFromObject(data, "bridge_id"); + const cJSON *raw = cJSON_GetObjectItem(data, "profile_id"); + if (!raw) { + raw = cJSON_GetObjectItem(data, "profileId"); + } + if (!raw) { + return; + } + char pid[24]; + bool set = api_id(raw, pid, sizeof(pid)); + const char *cur = api_current_profile(); + bool ok = !set || (cur && !strcmp(cur, pid)); + cJSON_DeleteItemFromObject(data, "profileId"); + if (!ok) { + cJSON_DeleteItemFromObject(data, "profile_id"); + } else { + api_set(data, "profile_id", set ? cJSON_CreateString(pid) : cJSON_CreateNull()); + } +} + +/* Group actions send to each member MAC; replies list what could not be sent */ + +static const char *const COLOR_ORDERS[] = { "rgb", "rbg", "grb", "gbr", "brg", "bgr" }; +static const char *const STARTUP_MODES[] = { "default", "last", "off" }; + +static bool one_of(const char *s, const char *const *list, size_t n) +{ + for (size_t i = 0; i < n; i++) { + if (!strcmp(s, list[i])) { + return true; + } + } + return false; +} + +static void lower_trim(const cJSON *v, char *buf, size_t len) +{ + buf[0] = 0; + if (!cJSON_IsString(v)) { + return; + } + const char *s = v->valuestring; + while (isspace((unsigned char)*s)) { + s++; + } + snprintf(buf, len, "%s", s); + for (int i = strlen(buf) - 1; i >= 0 && isspace((unsigned char)buf[i]); i--) { + buf[i] = 0; + } + for (char *c = buf; *c; c++) { + *c = tolower((unsigned char)*c); + } +} + +cJSON *api_driver_config(const cJSON *name, const cJSON *num_leds, const cJSON *color_order, const cJSON *startup) +{ + cJSON *dc = cJSON_CreateObject(); + char buf[64]; + if (cJSON_IsString(name)) { + const char *s = name->valuestring; + while (isspace((unsigned char)*s)) { + s++; + } + snprintf(buf, sizeof(buf), "%s", s); + for (int i = strlen(buf) - 1; i >= 0 && isspace((unsigned char)buf[i]); i--) { + buf[i] = 0; + } + if (buf[0]) { + cJSON_AddStringToObject(dc, "name", buf); + } + } + double n = cJSON_IsNumber(num_leds) ? num_leds->valuedouble + : cJSON_IsString(num_leds) ? strtod(num_leds->valuestring, NULL) + : 0; + if (n >= 1 && n <= 2048 && n == (int)n) { + cJSON_AddNumberToObject(dc, "num_leds", (int)n); + } + lower_trim(color_order, buf, sizeof(buf)); + if (one_of(buf, COLOR_ORDERS, sizeof(COLOR_ORDERS) / sizeof(COLOR_ORDERS[0]))) { + cJSON_AddStringToObject(dc, "color_order", buf); + } + lower_trim(startup, buf, sizeof(buf)); + if (one_of(buf, STARTUP_MODES, sizeof(STARTUP_MODES) / sizeof(STARTUP_MODES[0]))) { + cJSON_AddStringToObject(dc, "startup_mode", buf); + } + if (!dc->child) { + cJSON_Delete(dc); + return NULL; + } + return dc; +} + +static void add_error(cJSON *errors, const char *mac, const char *err) +{ + cJSON *e = cJSON_CreateObject(); + cJSON_AddStringToObject(e, "mac", mac); + cJSON_AddStringToObject(e, "error", err); + cJSON_AddItemToArray(errors, e); +} + +static esp_err_t push_one(const char *mac, cJSON *msg) +{ + cJSON *messages = cJSON_CreateArray(), *targets = cJSON_CreateArray(); + cJSON_AddItemToArray(messages, msg); + cJSON_AddItemToArray(targets, cJSON_CreateString(mac)); + esp_err_t err = engine_push(messages, targets); + cJSON_Delete(messages); + cJSON_Delete(targets); + return err; +} + +// POST /groups//driver-config: the group's driver defaults (wifi_* fields, body overrides) to members +static esp_err_t driver_config(httpd_req_t *req, const cJSON *g) +{ + cJSON *body = api_body_opt(req); + if (!body) { + return ESP_OK; + } + static const char *const KEYS[] = { "wifi_driver_display_name", "wifi_driver_num_leds", "wifi_color_order", + "wifi_startup_mode" }; + const cJSON *v[4]; + for (int i = 0; i < 4; i++) { + v[i] = cJSON_GetObjectItem(body, KEYS[i]) ? cJSON_GetObjectItem(body, KEYS[i]) : cJSON_GetObjectItem(g, KEYS[i]); + } + cJSON *dc = api_driver_config(v[0], v[1], v[2], v[3]); + cJSON_Delete(body); + if (!dc) { + return api_error(req, "400 Bad Request", + "No driver defaults on this group (set display name, LEDs, colour order, or power-on pattern)"); + } + int sent = 0; + cJSON *errors = cJSON_CreateArray(); + const cJSON *it; + cJSON_ArrayForEach(it, cJSON_GetObjectItem(g, "devices")) + { + char mac[13]; + if (!api_mac(it, mac)) { + continue; + } + if (!cJSON_GetObjectItem(store_coll("device"), mac)) { + add_error(errors, mac, "not in registry"); + continue; + } + cJSON *msg = cJSON_CreateObject(); + cJSON_AddStringToObject(msg, "v", "1"); + cJSON_AddItemToObject(msg, "device_config", cJSON_Duplicate(dc, true)); + cJSON_AddTrueToObject(msg, "save"); + if (push_one(mac, msg) == ESP_OK) { + sent++; + } else { + add_error(errors, mac, "send failed"); + } + } + cJSON_Delete(dc); + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "message", "driver-config sent"); + cJSON_AddNumberToObject(o, "sent", sent); + cJSON_AddItemToObject(o, "errors", errors); + return api_json(req, "200 OK", o, true); +} + +// POST /groups//brightness: each member gets its combined brightness (global x groups x device) +static esp_err_t brightness(httpd_req_t *req, const cJSON *g) +{ + int sent = 0; + cJSON *errors = cJSON_CreateArray(); + const cJSON *it; + cJSON_ArrayForEach(it, cJSON_GetObjectItem(g, "devices")) + { + char mac[13]; + if (!api_mac(it, mac)) { + continue; + } + if (!cJSON_GetObjectItem(store_coll("device"), mac)) { + add_error(errors, mac, "not in registry"); + continue; + } + cJSON *msg = cJSON_CreateObject(); + cJSON_AddStringToObject(msg, "v", "1"); + cJSON_AddNumberToObject(msg, "b", api_effective_brightness(mac, -1)); + cJSON_AddTrueToObject(msg, "save"); + if (push_one(mac, msg) == ESP_OK) { + sent++; + } else { + add_error(errors, mac, "send failed"); + } + } + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "message", "brightness sent"); + cJSON_AddNumberToObject(o, "sent", sent); + cJSON_AddItemToObject(o, "errors", errors); + return api_json(req, "200 OK", o, true); +} + +// POST /groups//identify: every member blinks together (one GROUP_CMD), then goes off +static esp_err_t identify(httpd_req_t *req, const char *id, const cJSON *g) +{ + const cJSON *devs = cJSON_GetObjectItem(g, "devices"); + if (!cJSON_GetArraySize(devs)) { + return api_error(req, "400 Bad Request", "Group has no devices"); + } + int sent = 0; + cJSON *errors = cJSON_CreateArray(); + const cJSON *it; + cJSON_ArrayForEach(it, devs) + { + char mac[13]; + if (api_mac(it, mac)) { + sent++; + } else { + add_error(errors, cJSON_IsString(it) ? it->valuestring : "?", "invalid MAC"); + } + } + if (sent && api_identify_group(id) != ESP_OK) { + sent = 0; + add_error(errors, "*", "send failed"); + } + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "message", "identify group done"); + cJSON_AddNumberToObject(o, "sent", sent); + cJSON_AddItemToObject(o, "errors", errors); + return api_json(req, "200 OK", o, true); +} + +bool groups_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) +{ + cJSON *all = store_coll("group"); + const int method = req->method; + if (n == 1 && method == HTTP_GET) { + cJSON *o = cJSON_CreateObject(), *g; + cJSON_ArrayForEach(g, all) + { + if (cJSON_IsObject(g) && visible(g)) { + cJSON_AddItemReferenceToObject(o, g->string, g); + } + } + *ret = api_json(req, "200 OK", o, true); + return true; + } + if (n == 1 && method == HTTP_POST) { + cJSON *body = api_body_opt(req); + if (!body) { + *ret = ESP_OK; + return true; + } + bool scoped = cJSON_IsTrue(cJSON_GetObjectItem(body, "profile_scoped")); + cJSON_DeleteItemFromObject(body, "profile_scoped"); + sanitize(body); + cJSON *g = cJSON_Parse(DEFAULTS); + api_merge(g, body); + cJSON_Delete(body); + const char *cur = api_current_profile(); + if (scoped && cur) { + api_set(g, "profile_id", cJSON_CreateString(cur)); + } + normalize_devices(g); + char id[16]; + api_add("group", g, id, sizeof(id)); + store_save("group"); + engine_groups_changed(); + *ret = api_json(req, "201 Created", g, false); + return true; + } + if (n < 2) { + return false; + } + cJSON *g = find(seg[1]); + if (!g) { + *ret = api_error(req, "404 Not Found", "Group not found"); + return true; + } + if (n == 3 && method == HTTP_POST) { + *ret = !strcmp(seg[2], "driver-config") ? driver_config(req, g) + : !strcmp(seg[2], "brightness") ? brightness(req, g) + : !strcmp(seg[2], "identify") ? identify(req, seg[1], g) + : api_error(req, "404 Not Found", "unknown action"); + return true; + } + if (n != 2) { + return false; + } + switch (method) { + case HTTP_GET: + *ret = api_json(req, "200 OK", g, false); + return true; + case HTTP_PUT: { + cJSON *body = api_body(req); + if (!body) { + *ret = ESP_OK; + return true; + } + sanitize(body); + api_merge(g, body); + cJSON_Delete(body); + normalize_devices(g); + store_save("group"); + engine_groups_changed(); + *ret = api_json(req, "200 OK", g, false); + return true; + } + case HTTP_DELETE: + cJSON_DeleteItemFromObject(all, seg[1]); + store_save("group"); + engine_groups_changed(); + *ret = api_message(req, "200 OK", "Group deleted successfully"); + return true; + default: + return false; + } +} diff --git a/main/res_misc.c b/main/res_misc.c index b8e3269..08476a4 100644 --- a/main/res_misc.c +++ b/main/res_misc.c @@ -5,6 +5,7 @@ #include #include "api_util.h" #include "engine.h" +#include "seqplay.h" #include "store.h" /* --------------------------------------------------------------- palettes */ @@ -87,166 +88,274 @@ bool palettes_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) /* -------------------------------------------------------------- sequences */ -#define DURATION_MIN_S 0.5 -#define DURATION_MAX_S 600.0 -#define DURATION_DEFAULT_S 5.0 +// main's models/sequence.py: lanes of {preset_id, beats} steps, each lane with its own groups +static const char SEQ_DEFAULTS[] = "{\"name\":\"\",\"group_ids\":[],\"lanes\":[[]],\"lanes_group_ids\":[[]]," + "\"advance_mode\":\"beats\",\"steps\":[],\"step_duration_ms\":3000," + "\"sequence_transition\":500,\"loop\":true}"; -static bool truthy(const cJSON *v, bool dflt) +static bool has_steps(const cJSON *lanes) { - if (!v || cJSON_IsNull(v)) { - return dflt; + const cJSON *l; + cJSON_ArrayForEach(l, lanes) + { + if (cJSON_IsArray(l) && cJSON_GetArraySize(l) > 0) { + return true; + } } - if (cJSON_IsString(v)) { - return v->valuestring[0] != 0; - } - return cJSON_IsTrue(v) || (cJSON_IsNumber(v) && v->valuedouble != 0); + return false; } -// Bring a sequence record into shape: {name, zone_id, loop, repeat_count, steps: [{preset_id, -// duration_s}], active}. Returns an error message, or NULL when doc is valid. -static const char *normalize_seq(cJSON *doc) +// Fill what older records lack (main's Sequence._migrate_after_load). True when doc changed. +static bool migrate_seq(cJSON *doc, const char *default_profile) { - char buf[64]; - const cJSON *name = cJSON_GetObjectItem(doc, "name"); - const char *s = cJSON_IsString(name) ? name->valuestring : ""; - while (isspace((unsigned char)*s)) { - s++; - } - snprintf(buf, sizeof(buf), "%s", s); - for (int i = strlen(buf) - 1; i >= 0 && isspace((unsigned char)buf[i]); i--) { - buf[i] = 0; - } - api_set(doc, "name", cJSON_CreateString(buf)); - - api_set(doc, "zone_id", api_id(cJSON_GetObjectItem(doc, "zone_id"), buf, sizeof(buf)) ? cJSON_CreateString(buf) - : cJSON_CreateNull()); - api_set(doc, "loop", cJSON_CreateBool(truthy(cJSON_GetObjectItem(doc, "loop"), true))); - - const cJSON *rc = cJSON_GetObjectItem(doc, "repeat_count"); - int repeat = 0; - if (cJSON_IsNumber(rc)) { - repeat = (int)rc->valuedouble; - } else if (rc && !cJSON_IsNull(rc) && !cJSON_IsFalse(rc)) { - return "repeat_count must be an integer"; - } - api_set(doc, "repeat_count", cJSON_CreateNumber(repeat < 0 ? 0 : repeat)); - - const cJSON *steps = cJSON_GetObjectItem(doc, "steps"); - if (steps && !cJSON_IsNull(steps) && !cJSON_IsArray(steps)) { - return "steps must be a list"; - } - cJSON *out = cJSON_CreateArray(); - const cJSON *st; - cJSON_ArrayForEach(st, steps) - { - const cJSON *pid = cJSON_IsObject(st) ? cJSON_GetObjectItem(st, "preset_id") : st; - if (!api_id(pid, buf, sizeof(buf))) { - cJSON_Delete(out); - return "each step needs a preset_id"; + bool changed = false; + if (!cJSON_IsArray(cJSON_GetObjectItem(doc, "steps"))) { + cJSON *steps = cJSON_CreateArray(), *p; + cJSON_ArrayForEach(p, cJSON_GetObjectItem(doc, "presets")) + { + char id[24]; + if (api_id(p, id, sizeof(id))) { + cJSON *st = cJSON_CreateObject(); + cJSON_AddStringToObject(st, "preset_id", id); + cJSON_AddArrayToObject(st, "group_ids"); + cJSON_AddItemToArray(steps, st); + } } - const cJSON *dv = cJSON_IsObject(st) ? cJSON_GetObjectItem(st, "duration_s") : NULL; - double d = cJSON_IsNumber(dv) ? dv->valuedouble : DURATION_DEFAULT_S; - d = d < DURATION_MIN_S ? DURATION_MIN_S : (d > DURATION_MAX_S ? DURATION_MAX_S : d); - cJSON *step = cJSON_CreateObject(); - cJSON_AddStringToObject(step, "preset_id", buf); - cJSON_AddNumberToObject(step, "duration_s", d); - cJSON_AddItemToArray(out, step); + api_set(doc, "steps", steps); + changed = true; } - api_set(doc, "steps", out); - api_set(doc, "active", cJSON_CreateBool(truthy(cJSON_GetObjectItem(doc, "active"), false))); - return NULL; + static const char *const DEFAULT_KEYS[] = { "step_duration_ms", "loop", "name", "advance_mode", + "sequence_transition", "group_ids" }; + cJSON *defs = cJSON_Parse(SEQ_DEFAULTS); + for (size_t i = 0; i < sizeof(DEFAULT_KEYS) / sizeof(DEFAULT_KEYS[0]); i++) { + const cJSON *v = cJSON_GetObjectItem(doc, DEFAULT_KEYS[i]); + bool bad = !v || (!strcmp(DEFAULT_KEYS[i], "group_ids") && !cJSON_IsArray(v)) || + (!strcmp(DEFAULT_KEYS[i], "advance_mode") && !(cJSON_IsString(v) && !strcmp(v->valuestring, "beats"))); + if (bad) { + api_set(doc, DEFAULT_KEYS[i], cJSON_Duplicate(cJSON_GetObjectItem(defs, DEFAULT_KEYS[i]), true)); + changed = true; + } + } + cJSON_Delete(defs); + if (!cJSON_GetObjectItem(doc, "profile_id") && default_profile) { + cJSON_AddStringToObject(doc, "profile_id", default_profile); + changed = true; + } + cJSON *lanes = cJSON_GetObjectItem(doc, "lanes"); + if (!cJSON_IsArray(lanes)) { + lanes = cJSON_CreateArray(); + const cJSON *steps = cJSON_GetObjectItem(doc, "steps"); + cJSON_AddItemToArray(lanes, cJSON_GetArraySize(steps) ? cJSON_Duplicate(steps, true) : cJSON_CreateArray()); + api_set(doc, "lanes", lanes); + changed = true; + } + int n_lanes = 0; + cJSON *lane, *step; + cJSON_ArrayForEach(lane, lanes) + { + if (!cJSON_IsArray(lane)) { + continue; + } + n_lanes++; + cJSON_ArrayForEach(step, lane) + { + if (cJSON_IsObject(step) && !cJSON_GetObjectItem(step, "beats")) { + cJSON_AddNumberToObject(step, "beats", 1); + changed = true; + } + } + } + const cJSON *lg = cJSON_GetObjectItem(doc, "lanes_group_ids"); + if (n_lanes && (!cJSON_IsArray(lg) || cJSON_GetArraySize(lg) != n_lanes)) { + const cJSON *shared = cJSON_GetObjectItem(doc, "group_ids"); + cJSON *out = cJSON_CreateArray(); + const cJSON *first_step = cJSON_GetArrayItem(cJSON_GetArrayItem(lanes, 0), 0); + const cJSON *step_g = cJSON_GetObjectItem(first_step, "group_ids"); + for (int i = 0; i < n_lanes; i++) { + bool own = n_lanes == 1 && cJSON_GetArraySize(step_g) > 0; + const cJSON *src = own ? step_g : shared; + cJSON_AddItemToArray(out, cJSON_IsArray(src) ? cJSON_Duplicate(src, true) : cJSON_CreateArray()); + } + api_set(doc, "lanes_group_ids", out); + changed = true; + } + return changed; +} + +void api_migrate_sequences(void) +{ + const char *first = store_coll("profile")->child ? store_coll("profile")->child->string : NULL; + bool changed = false; + cJSON *it; + cJSON_ArrayForEach(it, store_coll("sequence")) + { + if (cJSON_IsObject(it)) { + changed |= migrate_seq(it, first); + } + } + if (changed) { + store_save("sequence"); + } +} + +static bool in_profile(const cJSON *seq) +{ + const char *cur = api_current_profile(); + char pid[24]; + return cur && api_id(cJSON_GetObjectItem(seq, "profile_id"), pid, sizeof(pid)) && !strcmp(pid, cur); +} + +// main's Sequence.update: a steps list with no usable lanes becomes lane 0 +static void apply_update(cJSON *doc, cJSON *data) +{ + const cJSON *steps = cJSON_GetObjectItem(data, "steps"); + if (cJSON_GetArraySize(steps) && !has_steps(cJSON_GetObjectItem(data, "lanes"))) { + cJSON *lanes = cJSON_CreateArray(); + cJSON_AddItemToArray(lanes, cJSON_Duplicate(steps, true)); + api_set(data, "lanes", lanes); + } + api_merge(doc, data); } static esp_err_t play_sequence(httpd_req_t *req, const char *id) { - const cJSON *rec = cJSON_GetObjectItem(store_coll("sequence"), id); - if (!rec) { - return api_error(req, "404 Not Found", "Sequence not found"); + const char *profile = api_current_profile(); + if (!profile) { + return api_error(req, "404 Not Found", "No profile available"); + } + cJSON *body = api_body_opt(req); + if (!body) { + return ESP_OK; } char zone[24]; - if (!api_id(cJSON_GetObjectItem(rec, "zone_id"), zone, sizeof(zone))) { - return api_error(req, "400 Bad Request", "Sequence has no zone_id"); - } - if (!cJSON_GetArraySize(cJSON_GetObjectItem(rec, "steps"))) { - return api_error(req, "400 Bad Request", "Sequence has no steps"); - } - if (!cJSON_GetObjectItem(store_coll("zone"), zone)) { - return api_error(req, "404 Not Found", "Zone not found"); - } - esp_err_t err = engine_seq_play(id); - if (err == ESP_ERR_NO_MEM) { - return api_error(req, "503 Service Unavailable", "too many sequences running"); + const cJSON *z = cJSON_GetObjectItem(body, "zone_id"); + bool have = api_id(z ? z : cJSON_GetObjectItem(body, "zoneId"), zone, sizeof(zone)); + cJSON_Delete(body); + if (!have) { + return api_error(req, "400 Bad Request", "zone_id required"); } + const char *msg; + esp_err_t err = seqplay_start(id, zone, profile, &msg); if (err != ESP_OK) { - return api_result(req, err, ""); + return api_error(req, "400 Bad Request", msg ? msg : "sequence not found"); } - cJSON *all = engine_seq_status(); - cJSON *state = cJSON_DetachItemFromObject(all, id); - cJSON_Delete(all); - return api_json(req, "200 OK", state ? state : cJSON_CreateObject(), true); + cJSON *o = seqplay_pending(); + cJSON_AddTrueToObject(o, "ok"); + return api_json(req, "200 OK", o, true); } bool sequences_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) { cJSON *all = store_coll("sequence"); const int method = req->method; + const char *profile = api_current_profile(); if (n == 2 && method == HTTP_GET && !strcmp(seg[1], "status")) { - *ret = api_json(req, "200 OK", engine_seq_status(), true); + *ret = api_json(req, "200 OK", seqplay_status(), true); + return true; + } + if (n == 2 && method == HTTP_POST && !strcmp(seg[1], "stop")) { + seqplay_stop(true); + cJSON *o = cJSON_CreateObject(); + cJSON_AddTrueToObject(o, "ok"); + *ret = api_json(req, "200 OK", o, true); + return true; + } + if (n == 2 && method == HTTP_POST && !strcmp(seg[1], "sync-phase")) { + cJSON *body = api_body_opt(req); + if (!body) { + *ret = ESP_OK; + return true; + } + const cJSON *m = cJSON_GetObjectItem(body, "mode"); + if (!cJSON_IsString(m)) { + m = cJSON_GetObjectItem(body, "align"); + } + char mode[16]; + snprintf(mode, sizeof(mode), "%s", cJSON_IsString(m) ? m->valuestring : "step"); + for (char *c = mode; *c; c++) { + *c = tolower((unsigned char)*c); + } + cJSON_Delete(body); + if (!seqplay_sync(mode)) { + *ret = api_error(req, "409 Conflict", "No sequence is playing"); + return true; + } + cJSON *o = cJSON_CreateObject(); + cJSON_AddTrueToObject(o, "ok"); + cJSON_AddStringToObject(o, "mode", mode); + *ret = api_json(req, "200 OK", o, true); return true; } if (n == 3 && method == HTTP_POST && !strcmp(seg[2], "play")) { *ret = play_sequence(req, seg[1]); return true; } - if (n == 3 && method == HTTP_POST && !strcmp(seg[2], "stop")) { - bool stopped = engine_seq_stop(seg[1]) == ESP_OK; - cJSON *o = cJSON_CreateObject(); - cJSON_AddBoolToObject(o, "stopped", stopped); + if (n == 1 && method == HTTP_GET) { + cJSON *o = cJSON_CreateObject(), *it; + cJSON_ArrayForEach(it, all) + { + if (cJSON_IsObject(it) && in_profile(it)) { + cJSON_AddItemReferenceToObject(o, it->string, it); + } + } *ret = api_json(req, "200 OK", o, true); return true; } - if ((n == 1 && method == HTTP_POST) || (n == 2 && method == HTTP_PUT)) { - cJSON *old = n == 2 ? cJSON_GetObjectItem(all, seg[1]) : NULL; - if (n == 2 && !old) { - *ret = api_error(req, "404 Not Found", "Sequence not found"); + if (n == 1 && method == HTTP_POST) { + if (!profile) { + *ret = api_error(req, "404 Not Found", "No profile available"); return true; } + cJSON *body = api_body_opt(req); + if (!body) { + *ret = ESP_OK; + return true; + } + cJSON *doc = cJSON_Parse(SEQ_DEFAULTS); + api_set(body, "profile_id", cJSON_CreateString(profile)); + apply_update(doc, body); + cJSON_Delete(body); + char id[16]; + api_add("sequence", doc, id, sizeof(id)); + store_save("sequence"); + cJSON *o = cJSON_CreateObject(); + cJSON_AddItemReferenceToObject(o, id, doc); + *ret = api_json(req, "201 Created", o, true); + return true; + } + if (n != 2) { + return false; + } + cJSON *rec = cJSON_GetObjectItem(all, seg[1]); + if (!rec || !in_profile(rec)) { + *ret = api_error(req, "404 Not Found", "Sequence not found"); + return true; + } + switch (method) { + case HTTP_GET: + *ret = api_json(req, "200 OK", rec, false); + return true; + case HTTP_PUT: { cJSON *body = api_body(req); if (!body) { *ret = ESP_OK; return true; } - cJSON *doc = old ? cJSON_Duplicate(old, true) : cJSON_CreateObject(); - api_merge(doc, body); + api_set(body, "profile_id", cJSON_CreateString(profile)); + apply_update(rec, body); cJSON_Delete(body); - const char *bad = normalize_seq(doc); - if (bad) { - cJSON_Delete(doc); - *ret = api_error(req, "400 Bad Request", bad); - return true; - } - char id[16]; - if (old) { - snprintf(id, sizeof(id), "%s", seg[1]); - api_set(doc, "id", cJSON_CreateString(id)); - cJSON_ReplaceItemInObject(all, id, doc); - } else { - api_add("sequence", doc, id, sizeof(id)); - } store_save("sequence"); - *ret = api_json(req, old ? "200 OK" : "201 Created", doc, false); + seqplay_stop_if(seg[1]); + *ret = api_json(req, "200 OK", rec, false); return true; } - if (n == 2 && method == HTTP_DELETE) { - if (!cJSON_GetObjectItem(all, seg[1])) { - *ret = api_error(req, "404 Not Found", "Sequence not found"); - return true; - } - engine_seq_stop(seg[1]); + case HTTP_DELETE: + seqplay_stop_if(seg[1]); cJSON_DeleteItemFromObject(all, seg[1]); store_save("sequence"); *ret = api_message(req, "200 OK", "Sequence deleted successfully"); return true; + default: + return false; } - return false; } diff --git a/main/res_profile.c b/main/res_profile.c index 30afdc6..1329980 100644 --- a/main/res_profile.c +++ b/main/res_profile.c @@ -5,6 +5,7 @@ #include #include "api_util.h" #include "engine.h" +#include "seqplay.h" #include "store.h" #include "web.h" @@ -710,7 +711,7 @@ bool zones_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) return false; } if (!strcmp(seg[1], "engine") && !strcmp(seg[2], "status")) { - *ret = api_json(req, "200 OK", engine_status(), true); + *ret = api_json(req, "200 OK", seqplay_status(), true); return true; } if (method == HTTP_GET && !strcmp(seg[2], "content-fragment")) { diff --git a/main/seqplay.c b/main/seqplay.c new file mode 100644 index 0000000..ba8662f --- /dev/null +++ b/main/seqplay.c @@ -0,0 +1,684 @@ +#include "seqplay.h" + +#include +#include +#include +#include "api_util.h" +#include "beat.h" +#include "engine.h" +#include "esp_heap_caps.h" +#include "esp_log.h" +#include "esp_timer.h" +#include "freertos/FreeRTOS.h" +#include "freertos/queue.h" +#include "freertos/task.h" +#include "store.h" + +static const char *TAG = "seqplay"; + +#define LANES_MAX 8 +#define STEPS_MAX 64 +#define ID_MAX 24 +#define BPM_MIN 60 +#define BPM_MAX 200 +#define BEATS_PER_BAR 4 + +typedef struct { + char preset[ID_MAX]; + int beats; + char group_ids[4][GROUP_ID_MAX]; // a single lane's step may carry its own groups + int ngroups; +} step_t; + +typedef struct { + step_t step[STEPS_MAX]; + int n, idx, count; + bool done; + char last[ID_MAX]; // preset last uploaded for this lane +} lane_t; + +// Everything below is guarded by the store lock (the beat task and the HTTP handlers both take it). +// The lanes (about 57 KB) live in PSRAM, allocated by seqplay_init. +static struct { + bool active; + char seq[ID_MAX], zone[ID_MAX], profile[ID_MAX]; + lane_t *lane; + int nlanes; + bool loop; + int loop_beat; + bool anchor_on_pass_start; + bool pending_switch; // a queued start takes over on the next beat; stop advancing meanwhile +} s_run; + +static struct { + bool set; + char seq[ID_MAX], zone[ID_MAX], profile[ID_MAX]; +} s_pend; + +static char s_done_readout[24]; // "6/6" kept after a sequence ran to its end +static bool s_audio = true; +static uint32_t s_sim_beats; // simulated clock beats, for its bar phase +static int64_t s_last_beat_us; + +/* ------------------------------------------------------------- settings */ + +static int simulated_bpm(void) +{ + const cJSON *v = cJSON_GetObjectItem(store_settings(), "audio_simulated_bpm"); + int bpm = cJSON_IsNumber(v) ? (int)v->valuedouble : 120; + return bpm < BPM_MIN ? BPM_MIN : (bpm > BPM_MAX ? BPM_MAX : bpm); +} + +static bool audio_drives(void) +{ + beat_info_t bi; + beat_get_info(&bi); + return s_audio && bi.locked; +} + +// "downbeat" only while the mic is timing (the clock's bar is a guess); otherwise "beat" +static bool wait_for_downbeat(void) +{ + const cJSON *v = cJSON_GetObjectItem(store_settings(), "sequence_switch_wait"); + return audio_drives() && cJSON_IsString(v) && !strcasecmp(v->valuestring, "downbeat"); +} + +/* ---------------------------------------------------------------- targets */ + +static void add_id(cJSON *arr, const char *id) +{ + const cJSON *it; + cJSON_ArrayForEach(it, arr) + { + if (!strcmp(it->valuestring, id)) { + return; + } + } + cJSON_AddItemToArray(arr, cJSON_CreateString(id)); +} + +static void add_list(cJSON *arr, const cJSON *list) +{ + const cJSON *it; + cJSON_ArrayForEach(it, list) + { + char id[GROUP_ID_MAX]; + if (api_id(it, id, sizeof(id))) { + add_id(arr, id); + } + } +} + +// Groups a lane's step plays to (main's _group_ids_for_lane_step), falling back to the zone's groups +static cJSON *lane_groups(int lane, const step_t *st) +{ + cJSON *out = cJSON_CreateArray(); + const cJSON *seq = cJSON_GetObjectItem(store_coll("sequence"), s_run.seq); + const cJSON *lgs = cJSON_GetObjectItem(seq, "lanes_group_ids"); + if (cJSON_IsArray(lgs) && lane < cJSON_GetArraySize(lgs)) { + add_list(out, cJSON_GetArrayItem(lgs, lane)); + } else if (!(s_run.nlanes > 1 && cJSON_IsArray(lgs))) { + add_list(out, cJSON_GetObjectItem(seq, "group_ids")); + for (int i = 0; !out->child && s_run.nlanes == 1 && i < st->ngroups; i++) { + add_id(out, st->group_ids[i]); + } + } + if (!out->child) { + char t[ZONE_TARGETS_MAX][GROUP_ID_MAX]; + int n = engine_zone_targets(s_run.zone, t, ZONE_TARGETS_MAX); + for (int i = 0; i < n; i++) { + add_id(out, t[i]); + } + } + return out; +} + +static void send(cJSON *msg) +{ + cJSON *messages = cJSON_CreateArray(); + cJSON_AddItemToArray(messages, msg); + engine_push(messages, NULL); + cJSON_Delete(messages); +} + +static cJSON *message(cJSON *groups) +{ + cJSON *m = cJSON_CreateObject(); + cJSON_AddStringToObject(m, "v", "1"); + if (groups && groups->child) { + cJSON_AddItemToObject(m, "groups", groups); + } else { + cJSON_Delete(groups); + } + return m; +} + +// Upload presets [from, to) of a lane (each once) to the lane's groups +static void send_presets(int lane, int from, int to) +{ + lane_t *l = &s_run.lane[lane]; + cJSON *presets = cJSON_CreateObject(); + for (int i = from; i < to && i < l->n; i++) { + const char *id = l->step[i].preset; + cJSON *p = cJSON_GetObjectItem(presets, id) ? NULL : engine_preset_payload(id); + if (p) { + cJSON_AddItemToObject(presets, id, p); + } + } + if (!presets->child) { + cJSON_Delete(presets); + return; + } + cJSON *m = message(lane_groups(lane, &l->step[from])); + cJSON_AddItemToObject(m, "presets", presets); + send(m); +} + +static void send_select(int lane) +{ + lane_t *l = &s_run.lane[lane]; + const step_t *st = &l->step[l->idx]; + cJSON *m = message(lane_groups(lane, st)); + cJSON *sel = cJSON_AddArrayToObject(m, "select"); + cJSON_AddItemToArray(sel, cJSON_CreateString(st->preset)); + send(m); +} + +// Step change: upload the new step's preset unless it is already there, then select it +static void send_lane(int lane) +{ + lane_t *l = &s_run.lane[lane]; + if (l->done || l->idx >= l->n || !l->step[l->idx].preset[0]) { + return; + } + if (strcmp(l->last, l->step[l->idx].preset)) { + send_presets(lane, l->idx, l->idx + 1); + memcpy(l->last, l->step[l->idx].preset, ID_MAX); + } + send_select(lane); +} + +// Every driver the zone reaches gets its combined brightness with the zone's slider value +static void zone_brightness(void) +{ + const cJSON *zone = cJSON_GetObjectItem(store_coll("zone"), s_run.zone); + const cJSON *zb = cJSON_GetObjectItem(zone, "brightness"); + int zone_b = cJSON_IsNumber(zb) ? (int)zb->valuedouble : 255; + zone_b = zone_b < 0 ? 0 : (zone_b > 255 ? 255 : zone_b); + cJSON *macs = cJSON_CreateArray(); + char t[ZONE_TARGETS_MAX][GROUP_ID_MAX]; + int n = engine_zone_targets(s_run.zone, t, ZONE_TARGETS_MAX); + for (int i = 0; i < n; i++) { + const cJSON *it; + if (t[i][0] == 'z') { // drivers named by the zone + const cJSON *d; + cJSON_ArrayForEach(d, store_coll("device")) + { + const cJSON *name = cJSON_GetObjectItem(d, "name"); + cJSON_ArrayForEach(it, cJSON_GetObjectItem(zone, "names")) + { + if (cJSON_IsString(name) && cJSON_IsString(it) && !strcmp(name->valuestring, it->valuestring)) { + add_id(macs, d->string); + } + } + } + continue; + } + cJSON_ArrayForEach(it, cJSON_GetObjectItem(cJSON_GetObjectItem(store_coll("group"), t[i]), "devices")) + { + char mac[13]; + if (api_mac(it, mac)) { + add_id(macs, mac); + } + } + } + const cJSON *mac; + cJSON_ArrayForEach(mac, macs) + { + cJSON *m = message(NULL); + cJSON_AddNumberToObject(m, "b", api_effective_brightness(mac->valuestring, zone_b)); + cJSON_AddTrueToObject(m, "save"); + cJSON *messages = cJSON_CreateArray(), *targets = cJSON_CreateArray(); + cJSON_AddItemToArray(messages, m); + cJSON_AddItemToArray(targets, cJSON_CreateString(mac->valuestring)); + engine_push(messages, targets); + cJSON_Delete(messages); + cJSON_Delete(targets); + } + cJSON_Delete(macs); +} + +/* --------------------------------------------------------------- playback */ + +// The sequence's lanes as steps (main's _normalize_sequence_lanes); empty lanes are dropped +static int load_lanes(const cJSON *seq) +{ + const cJSON *lanes = cJSON_GetObjectItem(seq, "lanes"); + bool any = false; + const cJSON *l; + cJSON_ArrayForEach(l, lanes) + { + any = any || cJSON_GetArraySize(l) > 0; + } + cJSON *one = NULL; + if (!any && cJSON_GetArraySize(cJSON_GetObjectItem(seq, "steps"))) { + one = cJSON_CreateArray(); + cJSON_AddItemReferenceToArray(one, cJSON_GetObjectItem(seq, "steps")); + lanes = one; + } + int n = 0; + cJSON_ArrayForEach(l, lanes) + { + if (n == LANES_MAX || !cJSON_IsArray(l) || !cJSON_GetArraySize(l)) { + continue; + } + lane_t *lane = &s_run.lane[n]; + memset(lane, 0, sizeof(*lane)); + const cJSON *s; + cJSON_ArrayForEach(s, l) + { + if (lane->n == STEPS_MAX || !cJSON_IsObject(s)) { + continue; + } + step_t *st = &lane->step[lane->n++]; + const cJSON *pid = cJSON_GetObjectItem(s, "preset_id"); + api_id(pid ? pid : cJSON_GetObjectItem(s, "presetId"), st->preset, sizeof(st->preset)); + const cJSON *b = cJSON_GetObjectItem(s, "beats"); + st->beats = cJSON_IsNumber(b) && b->valuedouble >= 1 ? (int)b->valuedouble : 1; + const cJSON *g; + cJSON_ArrayForEach(g, cJSON_GetObjectItem(s, "group_ids")) + { + if (st->ngroups < 4 && api_id(g, st->group_ids[st->ngroups], GROUP_ID_MAX)) { + st->ngroups++; + } + } + } + n += lane->n > 0; + } + cJSON_Delete(one); + return n; +} + +static void anchor_bar(void) +{ + s_sim_beats = 0; // the next clock beat is a downbeat + if (audio_drives()) { + beat_tap(); // the beat just counted is beat 1 of the bar + } +} + +static void clear_drivers(void) +{ + cJSON *groups = cJSON_CreateArray(); + char t[ZONE_TARGETS_MAX][GROUP_ID_MAX]; + int n = engine_zone_targets(s_run.zone, t, ZONE_TARGETS_MAX); + for (int i = 0; i < n; i++) { + add_id(groups, t[i]); + } + if (!groups->child) { // never clear every driver in range + cJSON_Delete(groups); + return; + } + cJSON *m = message(groups); + cJSON_AddTrueToObject(m, "clear_presets"); + cJSON_AddTrueToObject(m, "save"); + send(m); +} + +static esp_err_t start_now(const char *seq_id, const char *zone_id, const char *profile_id, bool handoff, + bool downbeat, const char **msg) +{ + const cJSON *seq = cJSON_GetObjectItem(store_coll("sequence"), seq_id); + if (!seq) { + return ESP_ERR_NOT_FOUND; + } + if (!cJSON_GetObjectItem(store_coll("zone"), zone_id)) { + *msg = "zone not found"; + return ESP_ERR_INVALID_ARG; + } + s_pend.set = false; + s_run.active = false; + s_done_readout[0] = 0; + snprintf(s_run.seq, sizeof(s_run.seq), "%s", seq_id); + snprintf(s_run.zone, sizeof(s_run.zone), "%s", zone_id); + snprintf(s_run.profile, sizeof(s_run.profile), "%s", profile_id); + s_run.nlanes = load_lanes(seq); + if (!s_run.nlanes) { + *msg = "sequence has no steps"; + return ESP_ERR_INVALID_SIZE; + } + const cJSON *loop = cJSON_GetObjectItem(seq, "loop"); + s_run.loop = !loop || cJSON_IsTrue(loop) || (cJSON_IsNumber(loop) && loop->valuedouble != 0); + s_run.loop_beat = 0; + s_run.pending_switch = false; + s_run.anchor_on_pass_start = handoff ? downbeat : true; + // Step-0 presets, the selects, then the rest of each lane's presets (main's _prime_all_lanes) + for (int i = 0; i < s_run.nlanes; i++) { + send_presets(i, 0, 1); + memcpy(s_run.lane[i].last, s_run.lane[i].step[0].preset, ID_MAX); + } + for (int i = 0; i < s_run.nlanes; i++) { + send_select(i); + } + for (int i = 0; i < s_run.nlanes; i++) { + send_presets(i, 1, s_run.lane[i].n); + } + zone_brightness(); + s_run.active = true; + ESP_LOGI(TAG, "sequence %s in zone %s: %d lane(s)", seq_id, zone_id, s_run.nlanes); + return ESP_OK; +} + +static bool pass_start(void) +{ + const lane_t *l = &s_run.lane[0]; + return !l->done && l->idx == 0 && l->count == 0; +} + +static int readout(char *buf, size_t len); // forward + +static void advance(void) +{ + if (!s_run.active || s_run.pending_switch) { + return; + } + if (pass_start() && s_run.anchor_on_pass_start) { + anchor_bar(); + } + s_run.anchor_on_pass_start = true; + bool lane0_looped = false; + for (int i = 0; i < s_run.nlanes; i++) { + lane_t *l = &s_run.lane[i]; + if (l->done || !l->n) { + continue; + } + int need = l->step[l->idx].beats; + if (++l->count < need) { + continue; + } + if (l->idx + 1 >= l->n) { + if (s_run.loop) { + lane0_looped = lane0_looped || i == 0; + l->count = 0; + l->idx = 0; + l->last[0] = 0; // step 0 goes up again on each wrap + send_lane(i); + } else { + l->count = need; + l->done = true; + } + } else { + l->count = 0; + l->idx++; + send_lane(i); + } + } + s_run.loop_beat = lane0_looped ? 1 : s_run.loop_beat + 1; + bool all_done = true; + for (int i = 0; i < s_run.nlanes; i++) { + all_done = all_done && s_run.lane[i].done; + } + if (all_done) { + readout(s_done_readout, sizeof(s_done_readout)); + clear_drivers(); + s_run.active = false; + ESP_LOGI(TAG, "sequence %s finished", s_run.seq); + } +} + +static void on_beat(bool downbeat) +{ + int64_t now = esp_timer_get_time(); + if (now - s_last_beat_us < 60LL * 1000000 / BPM_MAX) { // never faster than BPM_MAX + return; + } + s_last_beat_us = now; + store_lock(); + if (s_pend.set && (downbeat || !wait_for_downbeat())) { + const char *msg = NULL; + char seq[ID_MAX], zone[ID_MAX], profile[ID_MAX]; + snprintf(seq, sizeof(seq), "%s", s_pend.seq); + snprintf(zone, sizeof(zone), "%s", s_pend.zone); + snprintf(profile, sizeof(profile), "%s", s_pend.profile); + if (start_now(seq, zone, profile, true, downbeat, &msg) != ESP_OK) { + ESP_LOGW(TAG, "queued sequence %s did not start: %s", seq, msg ? msg : "not found"); + } + } else { + advance(); + } + store_unlock(); +} + +static void beat_task(void *arg) +{ + QueueHandle_t q = xQueueCreate(8, sizeof(beat_event_t)); + if (!q || beat_subscribe(q) != ESP_OK) { + ESP_LOGE(TAG, "no beat subscription; the clock alone times sequences"); + } + int64_t next = esp_timer_get_time(); + for (;;) { + store_lock(); + int64_t interval = 60LL * 1000000 / simulated_bpm(); + store_unlock(); + int64_t now = esp_timer_get_time(); + if (next <= now) { // clock beat, counted only while the mic is not timing + next = (next + interval > now) ? next + interval : now + interval; + if (!audio_drives()) { + bool down = s_sim_beats % BEATS_PER_BAR == 0; + s_sim_beats++; + on_beat(down); + } + continue; + } + beat_event_t ev; + if (q && xQueueReceive(q, &ev, pdMS_TO_TICKS((next - now) / 1000) + 1) == pdTRUE && ev == BEAT_EVENT_BEAT && + audio_drives()) { + beat_info_t bi; + beat_get_info(&bi); + on_beat(bi.bar_beat == 1); + } + } +} + +/* --------------------------------------------------------------------- API */ + +esp_err_t seqplay_init(void) +{ + s_run.lane = heap_caps_calloc(LANES_MAX, sizeof(lane_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (!s_run.lane) { + return ESP_ERR_NO_MEM; + } + store_lock(); + const cJSON *a = cJSON_GetObjectItem(store_settings(), "audio_timing"); + s_audio = !cJSON_IsFalse(a); + store_unlock(); + return xTaskCreate(beat_task, "seqplay", 6144, NULL, 4, NULL) == pdPASS ? ESP_OK : ESP_ERR_NO_MEM; +} + +esp_err_t seqplay_start(const char *seq_id, const char *zone_id, const char *profile_id, const char **msg) +{ + *msg = NULL; + const cJSON *seq = cJSON_GetObjectItem(store_coll("sequence"), seq_id); + char owner[ID_MAX]; + if (!seq || !api_id(cJSON_GetObjectItem(seq, "profile_id"), owner, sizeof(owner)) || strcmp(owner, profile_id)) { + *msg = "sequence not found"; + return ESP_ERR_NOT_FOUND; + } + if (!s_run.active) { + return start_now(seq_id, zone_id, profile_id, false, false, msg); + } + // Another sequence plays: switch on the next beat (or downbeat) + s_pend.set = true; + snprintf(s_pend.seq, sizeof(s_pend.seq), "%s", seq_id); + snprintf(s_pend.zone, sizeof(s_pend.zone), "%s", zone_id); + snprintf(s_pend.profile, sizeof(s_pend.profile), "%s", profile_id); + s_run.pending_switch = true; + return ESP_OK; +} + +void seqplay_stop(bool clear) +{ + store_lock(); + bool was = s_run.active; + s_pend.set = false; + s_run.active = false; + bool finished = true; + for (int i = 0; i < s_run.nlanes; i++) { + finished = finished && s_run.lane[i].done; + } + if (!finished) { + s_done_readout[0] = 0; + } + if (was && clear) { + clear_drivers(); + } + store_unlock(); +} + +void seqplay_stop_if(const char *seq_id) +{ + store_lock(); + bool playing = s_run.active && !strcmp(s_run.seq, seq_id); + store_unlock(); + if (playing) { + seqplay_stop(true); + } +} + +bool seqplay_sync(const char *mode) +{ + store_lock(); + bool ok = s_run.active; + if (ok && (!strcasecmp(mode, "pass") || !strcasecmp(mode, "sequence") || !strcasecmp(mode, "restart"))) { + for (int i = 0; i < s_run.nlanes; i++) { + s_run.lane[i].idx = s_run.lane[i].count = 0; + s_run.lane[i].done = false; + } + s_run.loop_beat = 0; + for (int i = 0; i < s_run.nlanes; i++) { + send_lane(i); + } + } else if (ok) { + for (int i = 0; i < s_run.nlanes; i++) { + if (!s_run.lane[i].done) { + s_run.lane[i].count = 0; + } + } + } + if (ok) { + anchor_bar(); + } + store_unlock(); + return ok; +} + +// Lane 0's position in the pass: beats so far and per pass +static void pass_position(int *at, int *per_pass) +{ + const lane_t *l = &s_run.lane[0]; + *at = *per_pass = 0; + for (int i = 0; i < l->n; i++) { + *per_pass += l->step[i].beats; + } + if (l->done) { + *at = *per_pass; + return; + } + for (int i = 0; i < l->idx && i < l->n; i++) { + *at += l->step[i].beats; + } + int bt = l->idx < l->n ? l->step[l->idx].beats : 1; + *at += l->count < 0 ? 0 : (l->count > bt ? bt : l->count); +} + +static int readout(char *buf, size_t len) +{ + int at, tot; + pass_position(&at, &tot); + buf[0] = 0; + if (tot > 0 && s_run.lane[0].done) { + return snprintf(buf, len, "%d/%d", tot, tot); + } + if (tot > 0 && at > 0) { // on the last beat of the pass show n/n + return snprintf(buf, len, "%d/%d", at == tot - 1 ? tot : (at < tot ? at : tot), tot); + } + return 0; +} + +cJSON *seqplay_status(void) +{ + cJSON *o = cJSON_CreateObject(); + store_lock(); + if (!s_run.active) { + cJSON_AddFalseToObject(o, "active"); + cJSON_AddStringToObject(o, "beat_readout", ""); + store_unlock(); + return o; + } + const lane_t *l = &s_run.lane[0]; + int total = 0; + for (int i = 0; i < s_run.nlanes; i++) { + total += s_run.lane[i].n; + } + int at, per_pass; + pass_position(&at, &per_pass); + int bps = !l->done && l->idx < l->n ? l->step[l->idx].beats : 1; + int beat_in = l->done ? 0 : (l->count > bps ? bps : l->count); + const char *pid = !l->done && l->idx < l->n ? l->step[l->idx].preset : ""; + const cJSON *pdoc = pid[0] ? cJSON_GetObjectItem(store_coll("preset"), pid) : NULL; + const cJSON *pname = cJSON_GetObjectItem(pdoc, "name"); + char ro[24]; + readout(ro, sizeof(ro)); + cJSON_AddTrueToObject(o, "active"); + cJSON_AddStringToObject(o, "advance_mode", "beats"); + cJSON_AddStringToObject(o, "sequence_id", s_run.seq); + cJSON_AddStringToObject(o, "zone_id", s_run.zone); + cJSON_AddNumberToObject(o, "num_lanes", s_run.nlanes); + cJSON_AddNumberToObject(o, "total_sequence_steps", total); + cJSON_AddNumberToObject(o, "lane0_current_step", l->done ? l->n : l->idx + 1); + cJSON_AddNumberToObject(o, "lane0_lane_length", l->n); + cJSON_AddNumberToObject(o, "lane0_beat_in_step", beat_in); + cJSON_AddNumberToObject(o, "lane0_beats_per_step", bps); + cJSON_AddStringToObject(o, "lane0_preset_id", pid); + cJSON_AddStringToObject(o, "lane0_preset_name", + cJSON_IsString(pname) && pname->valuestring[0] ? pname->valuestring : pid); + cJSON_AddNumberToObject(o, "sequence_beat_at", at); + cJSON_AddNumberToObject(o, "sequence_beats_per_pass", per_pass); + cJSON_AddNumberToObject(o, "sequence_loop_beat", s_run.loop_beat); + cJSON_AddStringToObject(o, "beat_readout", ro); + store_unlock(); + return o; +} + +cJSON *seqplay_pending(void) +{ + cJSON *o = cJSON_CreateObject(); + store_lock(); + cJSON_AddBoolToObject(o, "pending", s_pend.set); + if (s_pend.set) { + cJSON_AddStringToObject(o, "wait_for", wait_for_downbeat() ? "downbeat" : "beat"); + cJSON_AddStringToObject(o, "sequence_id", s_pend.seq); + cJSON_AddStringToObject(o, "zone_id", s_pend.zone); + } + store_unlock(); + return o; +} + +const char *seqplay_done_readout(void) +{ + return s_done_readout; +} + +void seqplay_set_audio(bool on) +{ + store_lock(); + s_audio = on; + api_set(store_settings(), "audio_timing", cJSON_CreateBool(on)); + store_save("settings"); + store_unlock(); +} + +bool seqplay_audio(void) +{ + return s_audio; +} diff --git a/main/seqplay.h b/main/seqplay.h new file mode 100644 index 0000000..6c6b55d --- /dev/null +++ b/main/seqplay.h @@ -0,0 +1,39 @@ +#pragma once + +#include +#include "cJSON.h" +#include "esp_err.h" + +// Sequence playback, as main's util/sequence_playback.py: one sequence plays at a time in a zone. +// Each lane is a list of {preset_id, beats} steps sent to the lane's groups; a step lasts its number +// of beats. Beats come from the mic's beat detector while audio timing is on and the tempo is locked, +// otherwise from a clock at settings.audio_simulated_bpm (default 120). + +// Start the beat task (after beat_start) +esp_err_t seqplay_init(void); + +// Start sequence seq_id in zone_id. While another sequence plays, the switch waits for the next beat +// (or downbeat, settings.sequence_switch_wait) and *queued is set. ESP_ERR_NOT_FOUND: no such sequence +// in the profile; ESP_ERR_INVALID_ARG: no zone (msg says which); ESP_ERR_INVALID_SIZE: no steps. +// Call with the store locked. +esp_err_t seqplay_start(const char *seq_id, const char *zone_id, const char *profile_id, const char **msg); + +// Stop; with clear, the zone's drivers drop their presets +void seqplay_stop(bool clear); +// Stop when seq_id is the one playing (it was edited or deleted) +void seqplay_stop_if(const char *seq_id); + +// Align beat counters: "step" restarts the current step's beat count, "pass" restarts the sequence. +// False when nothing plays. +bool seqplay_sync(const char *mode); + +// Playback snapshot (main's playback_status) and the queued start (pending_play_status); caller owns them +cJSON *seqplay_status(void); +cJSON *seqplay_pending(void); + +// "6/6" from the last sequence that ran to its end ("" otherwise) +const char *seqplay_done_readout(void); + +// Use the mic's beats for timing (main's audio start/stop); off falls back to the clock +void seqplay_set_audio(bool on); +bool seqplay_audio(void);