/* * SPDX-License-Identifier: Apache-2.0 */ #include "ctrl_msg.h" #include #include #include #include "esp_log.h" #include "esp_mac.h" #include "nvs.h" #include "nvs_flash.h" #include "patterns.h" #include "presets.h" #include "settings.h" static const char *TAG = "ctrl_msg"; namespace { constexpr uint8_t kMagic = 0x4C; constexpr uint8_t kGroups = 0x02; constexpr uint8_t kCmd = 0x03; constexpr uint8_t kGroupCmd = 0x04; constexpr size_t kGroupsMax = 16; constexpr size_t kGroupIdMax = 24; constexpr size_t kEnvHdr = 5; char s_groups[kGroupsMax][kGroupIdMax]; size_t s_ngroups; char s_pending[32]; // a select for a preset not saved yet: applied when that preset arrives // Copy n bytes as a NUL-terminated string void cstr(char *dst, size_t cap, const uint8_t *src, size_t n) { size_t k = n < cap - 1 ? n : cap - 1; memcpy(dst, src, k); dst[k] = '\0'; } // Bounds-checked reader over an envelope blob struct Rd { const uint8_t *p; size_t n; size_t off; bool ok; bool bytes(size_t k, const uint8_t **out) { if (!ok || k > n - off) { ok = false; return false; } *out = p + off; off += k; return true; } bool u8(uint8_t *v) { const uint8_t *b; if (!bytes(1, &b)) return false; *v = b[0]; return true; } bool u16(uint16_t *v) { const uint8_t *b; if (!bytes(2, &b)) return false; *v = (uint16_t)(b[0] | (b[1] << 8)); return true; } }; // Presets blob: count, then per record name, pattern, colours, delay, brightness, auto, n1..n6 and (v3) an // extension block with fade (key 1) and beat timing (key 2) cJSON *decode_presets(Rd &r, bool v3) { uint8_t count; if (!r.u8(&count)) return nullptr; cJSON *o = cJSON_CreateObject(); for (int i = 0; i < count; i++) { uint8_t nl, pl, nc; const uint8_t *name, *pat; if (!r.u8(&nl) || !r.bytes(nl, &name) || !r.u8(&pl) || !r.bytes(pl, &pat) || !r.u8(&nc)) { goto fail; } { char nm[64], pn[64]; cstr(nm, sizeof(nm), name, nl); cstr(pn, sizeof(pn), pat, pl); cJSON *rec = cJSON_CreateObject(); cJSON_AddStringToObject(rec, "pattern", pn); cJSON *cols = cJSON_AddArrayToObject(rec, "colors"); for (int c = 0; c < nc; c++) { const uint8_t *rgb; if (!r.bytes(3, &rgb)) { cJSON_Delete(rec); goto fail; } int v[3] = { rgb[0], rgb[1], rgb[2] }; cJSON_AddItemToArray(cols, cJSON_CreateIntArray(v, 3)); } uint16_t delay, nn[6]; uint8_t br, au; bool ok = r.u16(&delay) && r.u8(&br) && r.u8(&au); for (int k = 0; ok && k < 6; k++) { ok = r.u16(&nn[k]); } if (!ok) { cJSON_Delete(rec); goto fail; } cJSON_AddNumberToObject(rec, "delay", delay); cJSON_AddNumberToObject(rec, "brightness", br); cJSON_AddBoolToObject(rec, "auto", au != 0); for (int k = 0; k < 6; k++) { char key[4] = { 'n', (char)('1' + k), '\0' }; cJSON_AddNumberToObject(rec, key, (int16_t)nn[k]); } if (v3) { uint8_t ext_len; const uint8_t *ext; if (!r.u8(&ext_len) || !r.bytes(ext_len, &ext)) { cJSON_Delete(rec); goto fail; } Rd e = { ext, ext_len, 0, true }; while (e.off < e.n) { uint8_t key, len; const uint8_t *val; if (!e.u8(&key) || !e.u8(&len) || !e.bytes(len, &val)) { break; } if (key == 1 && len == 2) { cJSON_AddNumberToObject(rec, "fade", val[0] | (val[1] << 8)); } else if (key == 2 && len == 1) { cJSON_AddBoolToObject(rec, "beat_time", val[0] != 0); } } } cJSON_AddItemToObject(o, nm, rec); } } return o; fail: cJSON_Delete(o); return nullptr; } // Select blob: per device, its preset name and an optional step cJSON *decode_select(Rd &r) { uint8_t count; if (!r.u8(&count)) return nullptr; cJSON *o = cJSON_CreateObject(); for (int i = 0; i < count; i++) { uint8_t dl, pl, has; const uint8_t *dev, *pname; if (!r.u8(&dl) || !r.bytes(dl, &dev) || !r.u8(&pl) || !r.bytes(pl, &pname) || !r.u8(&has)) { cJSON_Delete(o); return nullptr; } char dn[64], pn[64]; cstr(dn, sizeof(dn), dev, dl); cstr(pn, sizeof(pn), pname, pl); cJSON *arr = cJSON_CreateArray(); cJSON_AddItemToArray(arr, cJSON_CreateString(pn)); if (has) { uint16_t step; if (!r.u16(&step)) { cJSON_Delete(arr); cJSON_Delete(o); return nullptr; } cJSON_AddItemToArray(arr, cJSON_CreateNumber(step)); } cJSON_AddItemToObject(o, dn, arr); } return o; } // Default blob: the startup preset name and the devices it applies to bool decode_default(Rd &r, cJSON *o) { uint8_t nl, nt; const uint8_t *name; if (!r.u8(&nl) || !r.bytes(nl, &name)) return false; char dn[64]; cstr(dn, sizeof(dn), name, nl); cJSON_AddStringToObject(o, "default", dn); if (!r.u8(&nt)) return false; cJSON *targets = cJSON_AddArrayToObject(o, "targets"); for (int i = 0; i < nt; i++) { uint8_t tl; const uint8_t *t; if (!r.u8(&tl) || !r.bytes(tl, &t)) return false; char tn[64]; cstr(tn, sizeof(tn), t, tl); cJSON_AddItemToArray(targets, cJSON_CreateString(tn)); } return true; } // A v2/v3 envelope as the v1 JSON object the MicroPython driver works from cJSON *env_to_json(const uint8_t *b, size_t n) { if (n < kEnvHdr || (b[0] != 2 && b[0] != 3)) return nullptr; size_t lp = b[2], ls = b[3], ld = b[4]; // CMD and GROUP_CMD frames may end with the controller's save byte after the envelope: ignored, as settings // are saved on every change size_t want = kEnvHdr + lp + ls + ld; if (n != want && n != want + 1) return nullptr; cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "v", "1"); uint8_t w = b[1]; if (w < 128) { // device brightness, 0-127 on the wire int v = (w * 255) / 127; cJSON_AddNumberToObject(o, "b", v > 255 ? 255 : v); } Rd p = { b + kEnvHdr, lp, 0, true }; Rd s = { b + kEnvHdr + lp, ls, 0, true }; Rd d = { b + kEnvHdr + lp + ls, ld, 0, true }; if (lp) { cJSON *pr = decode_presets(p, b[0] == 3); if (!pr) goto fail; cJSON_AddItemToObject(o, "presets", pr); } if (ls) { cJSON *sel = decode_select(s); if (!sel) goto fail; cJSON_AddItemToObject(o, "select", sel); } if (ld && !decode_default(d, o)) goto fail; return o; fail: cJSON_Delete(o); return nullptr; } // This driver's MAC as 12 lowercase hex digits, the way the controller names a device void own_mac_hex(char out[13]) { uint8_t mac[6]; esp_read_mac(mac, ESP_MAC_WIFI_STA); snprintf(out, 13, "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); } // A select or default names this driver if it names its hostname or its MAC (any separators), or "*" bool names_me(const char *name) { if (strcmp(name, "*") == 0) { return true; } net_cfg_t n; settings_load_net(&n); if (strcmp(name, n.hostname) == 0) { return true; } char mine[13], hex[13]; own_mac_hex(mine); size_t k = 0; for (const char *c = name; *c; c++) { if (isxdigit((unsigned char)*c)) { if (k < 12) hex[k] = (char)tolower((unsigned char)*c); k++; } else if (*c != ':' && *c != '-') { return false; } } hex[12] = '\0'; return k == 12 && strcmp(hex, mine) == 0; } bool in_group(const char *gid) { for (size_t i = 0; i < s_ngroups; i++) { if (strcmp(s_groups[i], gid) == 0) return true; } return false; } void save_groups(void) { char buf[kGroupsMax * (kGroupIdMax + 1)] = ""; for (size_t i = 0; i < s_ngroups; i++) { if (i) strncat(buf, "\n", sizeof(buf) - strlen(buf) - 1); strncat(buf, s_groups[i], sizeof(buf) - strlen(buf) - 1); } nvs_handle_t h; if (nvs_open("espnow", NVS_READWRITE, &h) == ESP_OK) { nvs_set_str(h, "groups", buf); nvs_commit(h); nvs_close(h); } } // GROUPS: [4C][02][count] then per id [len][id]. The list replaces the stored one. void set_groups(const uint8_t *data, size_t len) { if (len < 3) return; size_t count = data[2], off = 3; s_ngroups = 0; for (size_t i = 0; i < count && off < len; i++) { size_t gl = data[off++]; if (gl == 0 || off + gl > len) break; if (gl < kGroupIdMax && s_ngroups < kGroupsMax) { cstr(s_groups[s_ngroups], kGroupIdMax, data + off, gl); s_ngroups++; } off += gl; } save_groups(); } // The device settings in a device_config object, applied to the strip and the saved network settings void apply_device_config(const cJSON *dc) { if (!cJSON_IsObject(dc)) return; const cJSON *v = cJSON_GetObjectItem(dc, "name"); if (cJSON_IsString(v) && v->valuestring[0]) { net_cfg_t n; settings_load_net(&n); cstr(n.hostname, sizeof(n.hostname), (const uint8_t *)v->valuestring, strlen(v->valuestring)); settings_save_net(&n); } hw_cfg_t hw; settings_load_hw(&hw); bool changed = false; v = cJSON_GetObjectItem(dc, "num_leds"); if (cJSON_IsNumber(v) && v->valueint >= 1 && v->valueint <= 512) { hw.num_leds = v->valueint; changed = true; } v = cJSON_GetObjectItem(dc, "max_brightness"); if (cJSON_IsNumber(v) && v->valueint >= 0 && v->valueint <= 255) { hw.max_brightness = (uint8_t)v->valueint; changed = true; } v = cJSON_GetObjectItem(dc, "color_order"); if (cJSON_IsString(v)) { static const char *orders[] = { "rgb", "rbg", "grb", "gbr", "brg", "bgr" }; for (const char *o : orders) { if (strcmp(v->valuestring, o) == 0) { strncpy(hw.order, o, sizeof(hw.order) - 1); changed = true; } } } if (changed) { settings_save_hw(&hw); patterns_set_hardware(hw); } v = cJSON_GetObjectItem(dc, "startup_mode"); if (cJSON_IsString(v) && strcmp(v->valuestring, "off") == 0) { presets_set_startup(""); } // "reversed" is accepted and ignored: the C++ driver does not reverse its strip yet } void clear_all_presets(void) { while (presets_count() > 0) { char name[32]; snprintf(name, sizeof(name), "%s", presets_at(0)->name); presets_delete(name); } } // Save each preset by name. Missing fields keep the pattern's defaults. void apply_presets(const cJSON *presets) { const cJSON *rec; cJSON_ArrayForEach(rec, presets) { const cJSON *pat = cJSON_GetObjectItem(rec, "pattern"); int idx = cJSON_IsString(pat) ? patterns_index(pat->valuestring) : -1; if (idx < 0) { ESP_LOGW(TAG, "preset %s: unknown pattern", rec->string); continue; } preset_t p; preset_defaults(&p, idx); snprintf(p.name, sizeof(p.name), "%s", rec->string); if (preset_from_json(rec, &p)) { presets_save(&p); } } if (s_pending[0] && presets_select(s_pending) == ESP_OK) { s_pending[0] = '\0'; } } // The select entry for this driver: a device key that names it, else the only entry const cJSON *pick_select(const cJSON *sel) { if (cJSON_IsString(sel)) { return sel; } if (cJSON_IsArray(sel)) { return cJSON_GetArrayItem(sel, 0); } if (!cJSON_IsObject(sel)) { return nullptr; } const cJSON *e; cJSON_ArrayForEach(e, sel) { if (names_me(e->string)) { return e; } } return cJSON_GetArraySize(sel) == 1 ? sel->child : nullptr; } void apply_select(const cJSON *sel) { const cJSON *e = pick_select(sel); if (!e) return; // an entry is [name, step] or a bare name; step is not used by this driver const cJSON *name = cJSON_IsArray(e) ? cJSON_GetArrayItem(e, 0) : e; if (!cJSON_IsString(name) || !name->valuestring[0]) return; if (presets_select(name->valuestring) == ESP_OK) { return; } // "on" and "off" are the built-in patterns (the controller's identify ends with "off"): select them if (strcmp(name->valuestring, "on") == 0 || strcmp(name->valuestring, "off") == 0) { preset_t p; preset_defaults(&p, patterns_index(name->valuestring)); snprintf(p.name, sizeof(p.name), "%s", name->valuestring); patterns_select(p); return; } snprintf(s_pending, sizeof(s_pending), "%s", name->valuestring); // preset not here yet } // A default applies when there are no targets or this driver is one of them void apply_default(const cJSON *d) { const cJSON *def = cJSON_GetObjectItem(d, "default"); if (!cJSON_IsString(def)) return; const cJSON *targets = cJSON_GetObjectItem(d, "targets"); if (cJSON_IsArray(targets) && cJSON_GetArraySize(targets) > 0) { bool hit = false; const cJSON *t; cJSON_ArrayForEach(t, targets) { if (cJSON_IsString(t) && names_me(t->valuestring)) hit = true; } if (!hit) return; } presets_set_startup(def->valuestring); } // The controller's JSON path shortens keys (engine.c compact()); these map them back to the long names struct KeyName { const char *shortk; const char *longk; }; constexpr KeyName kTopKeys[] = { {"p", "presets"}, {"s", "select"}, {"g", "groups"}, {"sg", "set_groups"}, {"sv", "save"}, {"df", "default"}, {"dc", "device_config"}, {"cp", "clear_presets"}, {"mf", "manifest"}, }; constexpr KeyName kPresetKeys[] = { {"p", "pattern"}, {"c", "colors"}, {"d", "delay"}, {"b", "brightness"}, {"a", "auto"}, {"bg", "background"}, {"f", "fade"}, {"tb", "beat_time"}, }; const char *long_name(const KeyName *map, size_t n, const char *k) { for (size_t i = 0; i < n; i++) { if (strcmp(map[i].shortk, k) == 0) return map[i].longk; } return k; } // A copy of one preset object with long key names cJSON *expand_preset(const cJSON *src) { cJSON *out = cJSON_CreateObject(); const cJSON *it; cJSON_ArrayForEach(it, src) { const char *k = long_name(kPresetKeys, sizeof(kPresetKeys) / sizeof(kPresetKeys[0]), it->string); if (!cJSON_HasObjectItem(out, k)) cJSON_AddItemToObject(out, k, cJSON_Duplicate(it, true)); } return out; } // A copy of a v1 message with long key names (its presets too) cJSON *expand_v1(const cJSON *src) { cJSON *out = cJSON_CreateObject(); const cJSON *it; cJSON_ArrayForEach(it, src) { const char *k = long_name(kTopKeys, sizeof(kTopKeys) / sizeof(kTopKeys[0]), it->string); if (cJSON_HasObjectItem(out, k)) continue; if (strcmp(k, "presets") == 0 && cJSON_IsObject(it)) { cJSON *ps = cJSON_AddObjectToObject(out, "presets"); const cJSON *p; cJSON_ArrayForEach(p, it) { cJSON_AddItemToObject(ps, p->string, expand_preset(p)); } } else { cJSON_AddItemToObject(out, k, cJSON_Duplicate(it, true)); } } return out; } // A JSON message with groups applies only when this driver is in one of them (no groups: everyone) bool json_for_me(const cJSON *o) { const cJSON *groups = cJSON_GetObjectItem(o, "groups"); if (!cJSON_IsArray(groups) || cJSON_GetArraySize(groups) == 0) return true; const cJSON *g; cJSON_ArrayForEach(g, groups) { if (cJSON_IsString(g) && in_group(g->valuestring)) return true; } return false; } // One v1 object, in the order controller_messages.py applies them void apply_v1(const cJSON *d) { const cJSON *v = cJSON_GetObjectItem(d, "v"); if (!cJSON_IsString(v) || strcmp(v->valuestring, "1") != 0) { return; } apply_device_config(cJSON_GetObjectItem(d, "device_config")); v = cJSON_GetObjectItem(d, "b"); if (cJSON_IsNumber(v)) { int b = v->valueint < 0 ? 0 : (v->valueint > 255 ? 255 : v->valueint); patterns_set_global((uint8_t)b); } if (cJSON_HasObjectItem(d, "clear_presets")) { clear_all_presets(); } const cJSON *presets = cJSON_GetObjectItem(d, "presets"); if (cJSON_IsObject(presets)) { apply_presets(presets); } const cJSON *sel = cJSON_GetObjectItem(d, "select"); if (sel) { apply_select(sel); } apply_default(d); } // A v2/v3 envelope: applied as a v1 object void handle_env(const uint8_t *env, size_t n) { cJSON *o = env_to_json(env, n); if (!o) { ESP_LOGW(TAG, "bad envelope, %u bytes", (unsigned)n); return; } apply_v1(o); cJSON_Delete(o); } } // namespace void ctrl_init(void) { nvs_handle_t h; if (nvs_open("espnow", NVS_READONLY, &h) != ESP_OK) { return; } char buf[kGroupsMax * (kGroupIdMax + 1)]; size_t len = sizeof(buf); if (nvs_get_str(h, "groups", buf, &len) == ESP_OK) { s_ngroups = 0; char *save = nullptr; for (char *tok = strtok_r(buf, "\n", &save); tok && s_ngroups < kGroupsMax; tok = strtok_r(nullptr, "\n", &save)) { snprintf(s_groups[s_ngroups], kGroupIdMax, "%s", tok); s_ngroups++; } } nvs_close(h); } void ctrl_handle(const uint8_t mac[6], const uint8_t *data, size_t len) { (void)mac; if (len < 1) return; if (data[0] == '{') { cJSON *raw = cJSON_ParseWithLength((const char *)data, len); if (raw) { cJSON *o = expand_v1(raw); cJSON_Delete(raw); if (json_for_me(o)) apply_v1(o); cJSON_Delete(o); } else { ESP_LOGW(TAG, "bad JSON"); } return; } if (len < 2 || data[0] != kMagic) return; switch (data[1]) { case kGroups: set_groups(data, len); break; case kCmd: handle_env(data + 2, len - 2); // a trailing save byte is ignored: settings are saved on every change break; case kGroupCmd: { if (len < 3) return; size_t gl = data[2]; if (len < 3 + gl) return; char gid[kGroupIdMax]; cstr(gid, sizeof(gid), data + 3, gl); if (!in_group(gid)) return; size_t off = 3 + gl; handle_env(data + off, len - off); break; } default: break; } } size_t ctrl_build_announce(uint8_t *out, size_t cap) { net_cfg_t n; settings_load_net(&n); hw_cfg_t hw; settings_load_hw(&hw); size_t nl = strlen(n.hostname); if (nl > 47) nl = 47; static const char *orders[] = { "rgb", "rbg", "grb", "gbr", "brg", "bgr" }; int co = 0; for (int i = 0; i < 6; i++) { if (strcmp(hw.order, orders[i]) == 0) co = i; } char cfg[160]; snprintf(cfg, sizeof(cfg), "{\"max_brightness\":%u,\"num_leds\":%d,\"color_order\":\"%s\",\"startup_mode\":\"default\",\"reversed\":false}", (unsigned)hw.max_brightness, hw.num_leds, hw.order); size_t cl = strlen(cfg); size_t need = 3 + nl + 6 + 1 + cl; if (need > cap || need > 250) return 0; size_t off = 0; out[off++] = kMagic; out[off++] = 0x01; // ANNOUNCE out[off++] = (uint8_t)nl; memcpy(out + off, n.hostname, nl); off += nl; out[off++] = hw.num_leds & 0xFF; out[off++] = (hw.num_leds >> 8) & 0xFF; out[off++] = (uint8_t)co; out[off++] = 0; // startup mode: default out[off++] = patterns_get_global(); out[off++] = 0; // device type: LED strip out[off++] = (uint8_t)cl; memcpy(out + off, cfg, cl); off += cl; return off; } cJSON *ctrl_groups_json(void) { cJSON *arr = cJSON_CreateArray(); for (size_t i = 0; i < s_ngroups; i++) { cJSON_AddItemToArray(arr, cJSON_CreateString(s_groups[i])); } return arr; }