Groups (registry of driver MACs, optionally scoped to a profile) become
the drivers' group membership, alongside z<zone id> for zones that still
name drivers. Zones play to their group_ids. Group and device routes for
driver config, brightness (global x groups x device x zone) and identify.
The push path takes main's message shape: select as a list, groups as a
filter (one GROUP_CMD per group, or JSON when a preset has a background),
short keys so JSON fits a frame.
Sequences follow main: lanes of {preset_id, beats} steps played to each
lane's groups, advanced by the mic's beats or a clock at
audio_simulated_bpm; a switch waits for the next beat or downbeat; sync-
phase, stop (clears the zone's drivers) and status. This replaces the
time-based per-zone sequencer and scene playback, as in main.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1007 lines
33 KiB
C
1007 lines
33 KiB
C
#include "engine.h"
|
|
|
|
#include <ctype.h>
|
|
#include <strings.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include "envelope.h"
|
|
#include "esp_log.h"
|
|
#include "esp_timer.h"
|
|
#include "espnow_tx.h"
|
|
#include "rel.h"
|
|
#include "freertos/FreeRTOS.h"
|
|
#include "freertos/task.h"
|
|
#include "store.h"
|
|
|
|
static const char *TAG = "engine";
|
|
|
|
#define FRAME_REPEAT 2 // every state frame goes out twice; messages are idempotent
|
|
#define JSON_MAX 232
|
|
|
|
/* ---------------------------------------------------------------- sending */
|
|
|
|
static esp_err_t tx(const uint8_t *mac, const void *data, size_t len, bool commit, int repeat)
|
|
{
|
|
// The bulk queue is bounded; wait for room instead of dropping state
|
|
for (int i = 0; i < 400; i++) {
|
|
esp_err_t err = rel_send(mac, data, len, commit, repeat);
|
|
if (err != ESP_ERR_NO_MEM) {
|
|
return err;
|
|
}
|
|
vTaskDelay(pdMS_TO_TICKS(5));
|
|
}
|
|
return ESP_ERR_TIMEOUT;
|
|
}
|
|
|
|
static bool parse_mac(const char *s, uint8_t mac[6])
|
|
{
|
|
if (strlen(s) != 12) {
|
|
return false;
|
|
}
|
|
for (int i = 0; i < 6; i++) {
|
|
if (!isxdigit((unsigned char)s[2 * i]) || !isxdigit((unsigned char)s[2 * i + 1])) {
|
|
return false;
|
|
}
|
|
char b[3] = { s[2 * i], s[2 * i + 1], 0 };
|
|
mac[i] = strtoul(b, NULL, 16);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// Broadcast (no targets): sent `repeat` times under one sequence number, never acked; the
|
|
// state version digest covers losses. With targets: unicast per MAC, acked and retransmitted.
|
|
// commit (broadcast only) tells drivers this frame completes a state change.
|
|
static char s_gid[24]; // group being addressed; "" = plain CMD (all addressed drivers apply it)
|
|
static bool s_save; // append the CMD save byte (driver persists presets / brightness)
|
|
|
|
// Envelopes travel as 0x4C CMD (4C 03 env) or, for a zone, GROUP_CMD (4C 04 <len><group> env) so only
|
|
// drivers in that group apply them. JSON messages go as they are.
|
|
static size_t wrap_wire(uint8_t *out, const uint8_t *frame, size_t len)
|
|
{
|
|
if (len == 0 || frame[0] != 2) { // not a v2 envelope
|
|
memcpy(out, frame, len);
|
|
return len;
|
|
}
|
|
size_t off = 0;
|
|
out[off++] = 0x4C;
|
|
if (s_gid[0]) {
|
|
size_t gl = strlen(s_gid);
|
|
out[off++] = 0x04;
|
|
out[off++] = gl;
|
|
memcpy(out + off, s_gid, gl);
|
|
off += gl;
|
|
} else {
|
|
out[off++] = 0x03;
|
|
}
|
|
memcpy(out + off, frame, len);
|
|
off += len;
|
|
if (s_save) {
|
|
out[off++] = 1; // 4C 03 / 4C 04 carry an optional trailing save flag after the envelope
|
|
}
|
|
return off;
|
|
}
|
|
|
|
static esp_err_t emit_c(const cJSON *targets, const uint8_t *frame, size_t len, int repeat, bool commit)
|
|
{
|
|
uint8_t wire[REL_FRAG_MAX];
|
|
if (len + 3 + strlen(s_gid) + 1 > sizeof(wire)) {
|
|
return ESP_ERR_INVALID_SIZE;
|
|
}
|
|
len = wrap_wire(wire, frame, len);
|
|
frame = wire;
|
|
esp_err_t ret = ESP_OK;
|
|
int n = cJSON_IsArray(targets) ? cJSON_GetArraySize(targets) : 0;
|
|
if (n == 0) {
|
|
return tx(NULL, frame, len, commit, repeat);
|
|
}
|
|
for (int i = 0; i < n; i++) {
|
|
const cJSON *t = cJSON_GetArrayItem(targets, i);
|
|
uint8_t mac[6];
|
|
if (cJSON_IsString(t) && parse_mac(t->valuestring, mac)) {
|
|
esp_err_t e = tx(mac, frame, len, false, 1);
|
|
if (e != ESP_OK) {
|
|
ret = e;
|
|
}
|
|
}
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
/* --------------------------------------------------------------- presets */
|
|
|
|
static bool id_text(const cJSON *v, char *buf, size_t len)
|
|
{
|
|
buf[0] = 0;
|
|
if (cJSON_IsString(v) && v->valuestring[0]) {
|
|
snprintf(buf, len, "%s", v->valuestring);
|
|
} else if (cJSON_IsNumber(v)) {
|
|
snprintf(buf, len, "%d", (int)v->valuedouble);
|
|
}
|
|
return buf[0] != 0;
|
|
}
|
|
|
|
|
|
// Palette colour idx of a profile, or NULL
|
|
static const cJSON *palette_color(const cJSON *profile_id, int idx)
|
|
{
|
|
char pidbuf[24], palbuf[24];
|
|
if (!id_text(profile_id, pidbuf, sizeof(pidbuf))) {
|
|
return NULL;
|
|
}
|
|
cJSON *profile = cJSON_GetObjectItem(store_coll("profile"), pidbuf);
|
|
if (!id_text(cJSON_GetObjectItem(profile, "palette_id"), palbuf, sizeof(palbuf))) {
|
|
return NULL;
|
|
}
|
|
cJSON *pal = cJSON_GetObjectItem(store_coll("palette"), palbuf);
|
|
if (cJSON_IsObject(pal)) { // older records hold {"colors": [...]}
|
|
pal = cJSON_GetObjectItem(pal, "colors");
|
|
}
|
|
const cJSON *c = idx >= 0 ? cJSON_GetArrayItem(pal, idx) : NULL;
|
|
return cJSON_IsString(c) && c->valuestring[0] ? c : NULL;
|
|
}
|
|
|
|
cJSON *engine_preset_payload(const char *preset_id)
|
|
{
|
|
cJSON *rec = cJSON_GetObjectItem(store_coll("preset"), preset_id);
|
|
if (!rec) {
|
|
return NULL;
|
|
}
|
|
cJSON *out = cJSON_Duplicate(rec, true);
|
|
const cJSON *pid = cJSON_GetObjectItem(out, "profile_id");
|
|
cJSON *refs = cJSON_GetObjectItem(out, "palette_refs");
|
|
cJSON *colors = cJSON_GetObjectItem(out, "colors");
|
|
int n = cJSON_IsArray(refs) && cJSON_IsArray(colors) ? cJSON_GetArraySize(colors) : 0;
|
|
for (int i = 0; i < n; i++) {
|
|
const cJSON *ref = cJSON_GetArrayItem(refs, i);
|
|
const cJSON *c = cJSON_IsNumber(ref) ? palette_color(pid, (int)ref->valuedouble) : NULL;
|
|
if (c) {
|
|
cJSON_ReplaceItemInArray(colors, i, cJSON_Duplicate(c, true));
|
|
}
|
|
}
|
|
const cJSON *bref = cJSON_GetObjectItem(out, "background_palette_ref");
|
|
const cJSON *bg = cJSON_IsNumber(bref) ? palette_color(pid, (int)bref->valuedouble) : NULL;
|
|
if (bg) {
|
|
cJSON_DeleteItemFromObject(out, "bg");
|
|
cJSON_DeleteItemFromObject(out, "background");
|
|
cJSON_AddItemToObject(out, "background", cJSON_Duplicate(bg, true));
|
|
}
|
|
const cJSON *mode = cJSON_GetObjectItem(out, "mode");
|
|
if (cJSON_IsNumber(mode) || (cJSON_IsString(mode) && mode->valuestring[0])) { // style mode travels as n6
|
|
int m = cJSON_IsNumber(mode) ? (int)mode->valuedouble : atoi(mode->valuestring);
|
|
cJSON_DeleteItemFromObject(out, "n6");
|
|
cJSON_AddNumberToObject(out, "n6", m < 0 ? 0 : m);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
static cJSON *preset_payload(const char *preset_id)
|
|
{
|
|
return engine_preset_payload(preset_id);
|
|
}
|
|
|
|
/* ------------------------------------------------------------ zone play */
|
|
|
|
static const cJSON *zone_names(const char *zone_id)
|
|
{
|
|
cJSON *z = cJSON_GetObjectItem(store_coll("zone"), zone_id);
|
|
cJSON *names = cJSON_GetObjectItem(z, "names");
|
|
return cJSON_IsArray(names) ? names : NULL;
|
|
}
|
|
|
|
static bool name_seen(const cJSON *names, int upto, const char *name)
|
|
{
|
|
for (int i = 0; i < upto; i++) {
|
|
const cJSON *o = cJSON_GetArrayItem(names, i);
|
|
if (cJSON_IsString(o) && strcmp(o->valuestring, name) == 0) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/* Driver groups. A driver's group list holds the ids of the registry groups ("group" collection)
|
|
whose devices list its MAC, plus "z<zone id>" for every zone that names the driver directly (zones
|
|
from before groups). A zone plays to its group_ids and, when it names drivers, to "z<zone id>". */
|
|
|
|
|
|
int engine_zone_targets(const char *zone_id, char out[][GROUP_ID_MAX], int max)
|
|
{
|
|
const cJSON *z = cJSON_GetObjectItem(store_coll("zone"), zone_id);
|
|
if (!z) {
|
|
return -1;
|
|
}
|
|
int n = 0;
|
|
const cJSON *g;
|
|
cJSON_ArrayForEach(g, cJSON_GetObjectItem(z, "group_ids"))
|
|
{
|
|
if (n < max && id_text(g, out[n], GROUP_ID_MAX)) {
|
|
n++;
|
|
}
|
|
}
|
|
const cJSON *names = zone_names(zone_id);
|
|
if (n < max && names && cJSON_GetArraySize(names) > 0) {
|
|
snprintf(out[n++], GROUP_ID_MAX, "z%s", zone_id);
|
|
}
|
|
return n;
|
|
}
|
|
|
|
static bool mac_listed(const cJSON *list, const char *hex)
|
|
{
|
|
const cJSON *it;
|
|
cJSON_ArrayForEach(it, list)
|
|
{
|
|
if (!cJSON_IsString(it)) {
|
|
continue;
|
|
}
|
|
char m[13];
|
|
int k = 0;
|
|
for (const char *c = it->valuestring; *c && k < 12; c++) {
|
|
if (*c != ':' && *c != '-') {
|
|
m[k++] = tolower((unsigned char)*c);
|
|
}
|
|
}
|
|
m[k] = 0;
|
|
if (k == 12 && !strcmp(m, hex)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// Is the driver (mac, name) a member of group gid?
|
|
static bool in_group(const uint8_t mac[6], const char *name, const char *gid)
|
|
{
|
|
if (gid[0] == 'z') {
|
|
return name && name_seen(zone_names(gid + 1), cJSON_GetArraySize(zone_names(gid + 1)), name);
|
|
}
|
|
char hex[13];
|
|
snprintf(hex, sizeof(hex), "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
|
return mac_listed(cJSON_GetObjectItem(cJSON_GetObjectItem(store_coll("group"), gid), "devices"), hex);
|
|
}
|
|
|
|
static bool driver_in_zone(const uint8_t mac[6], const char *name, const char *zone_id)
|
|
{
|
|
char t[ZONE_TARGETS_MAX][GROUP_ID_MAX];
|
|
int n = engine_zone_targets(zone_id, t, ZONE_TARGETS_MAX);
|
|
for (int i = 0; i < n; i++) {
|
|
if (in_group(mac, name, t[i])) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// Send one envelope frame to every group the zone plays to, as GROUP_CMDs
|
|
static esp_err_t emit_zone(const char *zone_id, const uint8_t *frame, size_t len, bool commit)
|
|
{
|
|
char t[ZONE_TARGETS_MAX][GROUP_ID_MAX];
|
|
int n = engine_zone_targets(zone_id, t, ZONE_TARGETS_MAX);
|
|
esp_err_t ret = n < 0 ? ESP_ERR_NOT_FOUND : ESP_OK;
|
|
for (int i = 0; i < n; i++) {
|
|
snprintf(s_gid, sizeof(s_gid), "%s", t[i]);
|
|
esp_err_t e = emit_c(NULL, frame, len, FRAME_REPEAT, commit);
|
|
if (e != ESP_OK) {
|
|
ret = e;
|
|
}
|
|
}
|
|
s_gid[0] = 0;
|
|
return ret;
|
|
}
|
|
|
|
// Select a preset for the whole zone. The select entry's key is ignored by drivers when it is the
|
|
// only entry.
|
|
static esp_err_t select_zone(const char *zone_id, const char *preset_name)
|
|
{
|
|
uint8_t frame[ENV_FRAME_MAX];
|
|
env_blob_t sel;
|
|
env_blob_init(&sel);
|
|
env_add_select(&sel, "*", preset_name, -1);
|
|
return emit_zone(zone_id, frame, env_frame(frame, -1, NULL, &sel), true);
|
|
}
|
|
|
|
/* What each zone last played, so a driver that missed it can be brought back in step */
|
|
typedef struct {
|
|
char zone[16];
|
|
char preset[24];
|
|
uint16_t ver;
|
|
} zone_cur_t;
|
|
static zone_cur_t s_cur[16];
|
|
|
|
static void zone_cur_set(const char *zone_id, const char *preset_id)
|
|
{
|
|
zone_cur_t *slot = NULL;
|
|
for (int i = 0; i < 16; i++) {
|
|
if (strcmp(s_cur[i].zone, zone_id) == 0) {
|
|
slot = &s_cur[i];
|
|
break;
|
|
}
|
|
if (!slot && !s_cur[i].zone[0]) {
|
|
slot = &s_cur[i];
|
|
}
|
|
}
|
|
if (slot) {
|
|
snprintf(slot->zone, sizeof(slot->zone), "%s", zone_id);
|
|
snprintf(slot->preset, sizeof(slot->preset), "%s", preset_id);
|
|
slot->ver = rel_ver();
|
|
}
|
|
}
|
|
|
|
static esp_err_t play_locked(const char *zone_id, const char *preset_id)
|
|
{
|
|
if (!cJSON_GetObjectItem(store_coll("zone"), zone_id)) {
|
|
return ESP_ERR_NOT_FOUND;
|
|
}
|
|
cJSON *payload = preset_payload(preset_id);
|
|
if (!payload) {
|
|
return ESP_ERR_NOT_FOUND;
|
|
}
|
|
uint8_t frame[ENV_FRAME_MAX];
|
|
env_blob_t pb;
|
|
env_blob_init(&pb);
|
|
rel_bump_ver();
|
|
bool fit = env_add_preset(&pb, preset_id, payload);
|
|
cJSON_Delete(payload);
|
|
if (!fit) {
|
|
return ESP_ERR_INVALID_SIZE;
|
|
}
|
|
esp_err_t ret = emit_zone(zone_id, frame, env_frame(frame, -1, &pb, NULL), false);
|
|
if (ret == ESP_OK) {
|
|
ret = select_zone(zone_id, preset_id);
|
|
}
|
|
if (ret == ESP_OK) {
|
|
zone_cur_set(zone_id, preset_id);
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
esp_err_t engine_play(const char *zone_id, const char *preset_id)
|
|
{
|
|
store_lock();
|
|
esp_err_t ret = play_locked(zone_id, preset_id);
|
|
store_unlock();
|
|
return ret;
|
|
}
|
|
|
|
esp_err_t engine_stop(const char *zone_id)
|
|
{
|
|
store_lock();
|
|
rel_bump_ver();
|
|
esp_err_t ret = select_zone(zone_id, "off");
|
|
if (ret == ESP_OK) {
|
|
zone_cur_set(zone_id, "off");
|
|
}
|
|
store_unlock();
|
|
return ret;
|
|
}
|
|
|
|
static const char *device_name_for(const uint8_t mac[6]);
|
|
|
|
/* ------------------------------------------------------------ push/send */
|
|
|
|
static bool only_binary_keys(const cJSON *m)
|
|
{
|
|
const cJSON *it;
|
|
cJSON_ArrayForEach(it, m)
|
|
{
|
|
const char *k = it->string;
|
|
if (strcmp(k, "v") && strcmp(k, "presets") && strcmp(k, "select") && strcmp(k, "b") && strcmp(k, "save") &&
|
|
strcmp(k, "groups")) {
|
|
return false;
|
|
}
|
|
}
|
|
// A background colour has no place in the binary preset record
|
|
const cJSON *p;
|
|
cJSON_ArrayForEach(p, cJSON_GetObjectItem(m, "presets"))
|
|
{
|
|
if (cJSON_GetObjectItem(p, "bg") || cJSON_GetObjectItem(p, "background")) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static esp_err_t push_binary(const cJSON *m, const cJSON *targets)
|
|
{
|
|
uint8_t frame[ENV_FRAME_MAX];
|
|
esp_err_t ret = ESP_OK;
|
|
const cJSON *b = cJSON_GetObjectItem(m, "b");
|
|
int brightness = cJSON_IsNumber(b) ? (int)b->valuedouble : -1;
|
|
const cJSON *sv = cJSON_GetObjectItem(m, "save");
|
|
const bool save = cJSON_IsTrue(sv) || (cJSON_IsNumber(sv) && sv->valuedouble != 0);
|
|
bool sent_any = false;
|
|
|
|
const cJSON *presets = cJSON_GetObjectItem(m, "presets"), *it;
|
|
const cJSON *select_obj = cJSON_GetObjectItem(m, "select");
|
|
const bool has_select = (cJSON_IsObject(select_obj) || cJSON_IsArray(select_obj)) && select_obj->child;
|
|
env_blob_t pb;
|
|
env_blob_init(&pb);
|
|
cJSON_ArrayForEach(it, presets)
|
|
{
|
|
if (!env_add_preset(&pb, it->string, it)) {
|
|
size_t len = env_frame(frame, sent_any ? -1 : brightness, &pb, NULL);
|
|
ret = emit_c(targets, frame, len, FRAME_REPEAT, false);
|
|
sent_any = true;
|
|
env_blob_init(&pb);
|
|
if (!env_add_preset(&pb, it->string, it)) {
|
|
ESP_LOGW(TAG, "preset %s too large for one frame", it->string);
|
|
}
|
|
}
|
|
}
|
|
if (pb.data[0]) {
|
|
size_t len = env_frame(frame, sent_any ? -1 : brightness, &pb, NULL);
|
|
s_save = save; // only the last presets frame asks the driver to persist
|
|
ret = emit_c(targets, frame, len, FRAME_REPEAT, !has_select);
|
|
s_save = false;
|
|
sent_any = true;
|
|
}
|
|
|
|
const cJSON *select = cJSON_GetObjectItem(m, "select");
|
|
env_blob_t sb;
|
|
env_blob_init(&sb);
|
|
if (cJSON_IsArray(select) && select->child) { // ["preset", step?]: every addressed driver
|
|
const cJSON *p0 = cJSON_GetArrayItem(select, 0), *s1 = cJSON_GetArrayItem(select, 1);
|
|
char pname[32];
|
|
if (id_text(p0, pname, sizeof(pname))) {
|
|
env_add_select(&sb, "*", pname, cJSON_IsNumber(s1) ? (int)s1->valuedouble : -1);
|
|
}
|
|
select = NULL;
|
|
}
|
|
cJSON_ArrayForEach(it, select)
|
|
{
|
|
const char *pname = NULL;
|
|
int step = -1;
|
|
if (cJSON_IsArray(it) && cJSON_GetArraySize(it) > 0) {
|
|
const cJSON *p0 = cJSON_GetArrayItem(it, 0), *s1 = cJSON_GetArrayItem(it, 1);
|
|
pname = cJSON_IsString(p0) ? p0->valuestring : NULL;
|
|
if (cJSON_IsNumber(s1)) {
|
|
step = (int)s1->valuedouble;
|
|
}
|
|
} else if (cJSON_IsString(it)) {
|
|
pname = it->valuestring;
|
|
}
|
|
if (!pname) {
|
|
continue;
|
|
}
|
|
if (!env_add_select(&sb, it->string, pname, step)) {
|
|
size_t len = env_frame(frame, sent_any ? -1 : brightness, NULL, &sb);
|
|
ret = emit_c(targets, frame, len, FRAME_REPEAT, true);
|
|
sent_any = true;
|
|
env_blob_init(&sb);
|
|
env_add_select(&sb, it->string, pname, step);
|
|
}
|
|
}
|
|
if (sb.data[0]) {
|
|
size_t len = env_frame(frame, sent_any ? -1 : brightness, NULL, &sb);
|
|
ret = emit_c(targets, frame, len, FRAME_REPEAT, true);
|
|
sent_any = true;
|
|
}
|
|
if (!sent_any && brightness >= 0) { // brightness-only message
|
|
size_t len = env_frame(frame, brightness, NULL, NULL);
|
|
s_save = save;
|
|
ret = emit_c(targets, frame, len, FRAME_REPEAT, true);
|
|
s_save = false;
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
// Long v1 keys and their wire short forms (led-driver/src/v1_wire.py, preset.py)
|
|
static const char *const TOP_SHORT[][2] = {
|
|
{ "presets", "p" }, { "select", "s" }, { "groups", "g" }, { "set_groups", "sg" },
|
|
{ "save", "sv" }, { "default", "df" }, { "device_config", "dc" }, { "clear_presets", "cp" },
|
|
{ "manifest", "mf" },
|
|
};
|
|
static const char *const PRESET_SHORT[][2] = {
|
|
{ "pattern", "p" }, { "colors", "c" }, { "delay", "d" }, { "brightness", "b" }, { "auto", "a" }, { "background", "bg" },
|
|
};
|
|
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)
|
|
{
|
|
for (size_t i = 0; i < n; i++) {
|
|
if (!strcmp(map[i][0], k)) {
|
|
return map[i][1];
|
|
}
|
|
}
|
|
return k;
|
|
}
|
|
|
|
// Copy of a preset with short keys and only the fields drivers store
|
|
static cJSON *compact_preset(const cJSON *p)
|
|
{
|
|
cJSON *o = cJSON_CreateObject();
|
|
const cJSON *it;
|
|
cJSON_ArrayForEach(it, p)
|
|
{
|
|
const char *k = short_key(PRESET_SHORT, sizeof(PRESET_SHORT) / sizeof(PRESET_SHORT[0]), it->string);
|
|
bool keep = false;
|
|
for (size_t i = 0; i < sizeof(PRESET_KEYS) / sizeof(PRESET_KEYS[0]) && !keep; i++) {
|
|
keep = !strcmp(k, PRESET_KEYS[i]);
|
|
}
|
|
if (keep && !cJSON_GetObjectItem(o, k)) {
|
|
cJSON_AddItemToObject(o, k, cJSON_Duplicate(it, true));
|
|
}
|
|
}
|
|
return o;
|
|
}
|
|
|
|
// Copy of a v1 message in its short wire form
|
|
static cJSON *compact(const cJSON *m)
|
|
{
|
|
cJSON *o = cJSON_CreateObject();
|
|
const cJSON *it;
|
|
cJSON_ArrayForEach(it, m)
|
|
{
|
|
const char *k = short_key(TOP_SHORT, sizeof(TOP_SHORT) / sizeof(TOP_SHORT[0]), it->string);
|
|
if (cJSON_GetObjectItem(o, k)) {
|
|
continue;
|
|
}
|
|
if (!strcmp(k, "p") && cJSON_IsObject(it)) {
|
|
cJSON *ps = cJSON_AddObjectToObject(o, "p");
|
|
const cJSON *p;
|
|
cJSON_ArrayForEach(p, it)
|
|
{
|
|
cJSON_AddItemToObject(ps, p->string, compact_preset(p));
|
|
}
|
|
} else {
|
|
cJSON_AddItemToObject(o, k, cJSON_Duplicate(it, true));
|
|
}
|
|
}
|
|
return o;
|
|
}
|
|
|
|
static esp_err_t emit_json(const cJSON *targets, const cJSON *msg, bool commit)
|
|
{
|
|
char *s = cJSON_PrintUnformatted(msg);
|
|
if (!s) {
|
|
return ESP_ERR_NO_MEM;
|
|
}
|
|
esp_err_t ret = strlen(s) <= JSON_MAX ? emit_c(targets, (const uint8_t *)s, strlen(s), 1, commit)
|
|
: ESP_ERR_INVALID_SIZE;
|
|
free(s);
|
|
return ret;
|
|
}
|
|
|
|
// JSON text path for keys the binary envelope cannot carry (default, manifest, bg, ...)
|
|
static esp_err_t push_json(const cJSON *m_long, const cJSON *targets)
|
|
{
|
|
cJSON *m = compact(m_long);
|
|
esp_err_t ret = emit_json(targets, m, true);
|
|
if (ret != ESP_ERR_INVALID_SIZE) {
|
|
cJSON_Delete(m);
|
|
return ret;
|
|
}
|
|
|
|
// Too big: the presets go over several messages (each with the group filter, so drivers outside
|
|
// the groups ignore them); the other keys ride on the last one
|
|
const cJSON *presets = cJSON_GetObjectItem(m, "p"), *groups = cJSON_GetObjectItem(m, "g");
|
|
if (!cJSON_IsObject(presets)) {
|
|
cJSON_Delete(m);
|
|
return ESP_ERR_INVALID_SIZE;
|
|
}
|
|
ret = ESP_OK;
|
|
cJSON *batch = NULL;
|
|
const cJSON *it = presets->child;
|
|
while (it) {
|
|
batch = cJSON_CreateObject();
|
|
cJSON_AddStringToObject(batch, "v", "1");
|
|
cJSON *bp = cJSON_AddObjectToObject(batch, "p");
|
|
if (groups) {
|
|
cJSON_AddItemReferenceToObject(batch, "g", (cJSON *)groups);
|
|
}
|
|
do {
|
|
cJSON_AddItemReferenceToObject(bp, it->string, (cJSON *)it);
|
|
char *out = cJSON_PrintUnformatted(batch);
|
|
size_t len = out ? strlen(out) : 0;
|
|
free(out);
|
|
if (len > JSON_MAX - 48 && cJSON_GetArraySize(bp) > 1) { // room for the last message's other keys
|
|
cJSON_DeleteItemFromObject(bp, it->string);
|
|
break;
|
|
}
|
|
it = it->next;
|
|
} while (it);
|
|
if (it) { // more to come: this part goes now
|
|
esp_err_t e = emit_json(targets, batch, false);
|
|
ret = e != ESP_OK ? e : ret;
|
|
cJSON_Delete(batch);
|
|
batch = NULL;
|
|
}
|
|
}
|
|
if (!batch) {
|
|
batch = cJSON_CreateObject();
|
|
cJSON_AddStringToObject(batch, "v", "1");
|
|
}
|
|
const cJSON *k;
|
|
cJSON_ArrayForEach(k, m)
|
|
{
|
|
if (strcmp(k->string, "v") && strcmp(k->string, "p") && !cJSON_GetObjectItem(batch, k->string)) {
|
|
cJSON_AddItemReferenceToObject(batch, k->string, (cJSON *)k);
|
|
}
|
|
}
|
|
esp_err_t e = emit_json(targets, batch, true);
|
|
ret = e != ESP_OK ? e : ret;
|
|
cJSON_Delete(batch);
|
|
cJSON_Delete(m);
|
|
return ret;
|
|
}
|
|
|
|
esp_err_t engine_push(const cJSON *messages, const cJSON *targets)
|
|
{
|
|
esp_err_t ret = ESP_OK;
|
|
const cJSON *m;
|
|
store_lock();
|
|
cJSON_ArrayForEach(m, messages)
|
|
{
|
|
if (!cJSON_IsObject(m)) {
|
|
continue;
|
|
}
|
|
if (!cJSON_IsArray(targets) || cJSON_GetArraySize(targets) == 0) {
|
|
rel_bump_ver(); // a broadcast state change: drivers that miss it resync from the digest
|
|
}
|
|
const cJSON *groups = cJSON_GetObjectItem(m, "groups");
|
|
esp_err_t e = ESP_OK;
|
|
if (!only_binary_keys(m)) {
|
|
e = push_json(m, targets);
|
|
} else if (cJSON_IsArray(groups) && groups->child) {
|
|
// One GROUP_CMD per group: only its members apply the presets and the select
|
|
const cJSON *g;
|
|
cJSON_ArrayForEach(g, groups)
|
|
{
|
|
if (id_text(g, s_gid, sizeof(s_gid))) {
|
|
esp_err_t r = push_binary(m, targets);
|
|
e = r != ESP_OK ? r : e;
|
|
}
|
|
}
|
|
s_gid[0] = 0;
|
|
} else {
|
|
e = push_binary(m, targets);
|
|
}
|
|
if (e != ESP_OK) {
|
|
ret = e;
|
|
}
|
|
}
|
|
store_unlock();
|
|
return ret;
|
|
}
|
|
|
|
esp_err_t engine_send_presets(const cJSON *ids, bool save, const char *def, const cJSON *targets, int *sent)
|
|
{
|
|
cJSON *msg = cJSON_CreateObject();
|
|
cJSON_AddStringToObject(msg, "v", "1");
|
|
cJSON *presets = cJSON_AddObjectToObject(msg, "presets");
|
|
int count = 0;
|
|
store_lock();
|
|
const cJSON *id;
|
|
cJSON_ArrayForEach(id, ids)
|
|
{
|
|
char key[24];
|
|
if (cJSON_IsNumber(id)) {
|
|
snprintf(key, sizeof(key), "%d", (int)id->valuedouble);
|
|
} else if (cJSON_IsString(id)) {
|
|
snprintf(key, sizeof(key), "%s", id->valuestring);
|
|
} else {
|
|
continue;
|
|
}
|
|
cJSON *p = preset_payload(key);
|
|
if (!p) {
|
|
continue;
|
|
}
|
|
cJSON_AddItemToObject(presets, key, p);
|
|
count++;
|
|
}
|
|
if (sent) {
|
|
*sent = count;
|
|
}
|
|
esp_err_t ret = ESP_ERR_NOT_FOUND;
|
|
if (count) {
|
|
if (save) {
|
|
cJSON_AddTrueToObject(msg, "save");
|
|
}
|
|
if (!cJSON_IsArray(targets) || cJSON_GetArraySize(targets) == 0) {
|
|
rel_bump_ver();
|
|
}
|
|
ret = push_binary(msg, targets);
|
|
// The startup preset needs the driver names (the driver checks it is addressed); targeted sends only
|
|
if (ret == ESP_OK && def && cJSON_GetObjectItem(presets, def) && cJSON_IsArray(targets)) {
|
|
cJSON *names = cJSON_CreateArray();
|
|
const cJSON *t;
|
|
cJSON_ArrayForEach(t, targets)
|
|
{
|
|
uint8_t mac[6];
|
|
const char *n = cJSON_IsString(t) && parse_mac(t->valuestring, mac) ? device_name_for(mac) : NULL;
|
|
if (n) {
|
|
cJSON_AddItemToArray(names, cJSON_CreateString(n));
|
|
}
|
|
}
|
|
if (cJSON_GetArraySize(names)) {
|
|
cJSON *d = cJSON_CreateObject();
|
|
cJSON_AddStringToObject(d, "v", "1");
|
|
cJSON_AddStringToObject(d, "default", def);
|
|
cJSON_AddItemToObject(d, "targets", names);
|
|
names = NULL;
|
|
ret = push_json(d, targets);
|
|
cJSON_Delete(d);
|
|
}
|
|
cJSON_Delete(names);
|
|
}
|
|
}
|
|
store_unlock();
|
|
cJSON_Delete(msg);
|
|
return ret;
|
|
}
|
|
|
|
static const char *device_name_for(const uint8_t mac[6])
|
|
{
|
|
char hex[13];
|
|
snprintf(hex, sizeof(hex), "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
|
const cJSON *d;
|
|
cJSON_ArrayForEach(d, store_coll("device"))
|
|
{
|
|
const cJSON *addr = cJSON_GetObjectItem(d, "address"), *name = cJSON_GetObjectItem(d, "name");
|
|
if (cJSON_IsString(name) && (strcasecmp(d->string, hex) == 0 || (cJSON_IsString(addr) && strcasecmp(addr->valuestring, hex) == 0))) {
|
|
return name->valuestring;
|
|
}
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
/* Unicast helpers: acked and retransmitted by the link */
|
|
static esp_err_t send_cmd(const uint8_t mac[6], const uint8_t *env, size_t len, bool commit)
|
|
{
|
|
uint8_t wire[REL_FRAG_MAX];
|
|
if (len + 2 > sizeof(wire)) {
|
|
return ESP_ERR_INVALID_SIZE;
|
|
}
|
|
wire[0] = 0x4C;
|
|
wire[1] = 0x03; // CMD
|
|
memcpy(wire + 2, env, len);
|
|
return rel_send(mac, wire, len + 2, commit, 1);
|
|
}
|
|
|
|
// GROUPS packet: the ids of every zone whose driver names include `name`. An empty list replaces
|
|
// whatever the driver stored, so it is only sent when allow_empty is set (a zone or device was edited);
|
|
// a driver that merely announced itself and is in no zone keeps the groups it already has.
|
|
// 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 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");
|
|
snprintf(gid, sizeof(gid), "z%s", z->string);
|
|
size_t gl = strlen(gid);
|
|
if (cJSON_IsArray(names) && name_seen(names, cJSON_GetArraySize(names), name) && off + 1 + gl <= REL_FRAG_MAX &&
|
|
gl < GROUP_ID_MAX - 1) {
|
|
pkt[off++] = gl;
|
|
memcpy(pkt + off, gid, gl);
|
|
off += gl;
|
|
(*count)++;
|
|
}
|
|
}
|
|
pkt[0] = 0x4C;
|
|
pkt[1] = 0x02; // GROUPS
|
|
pkt[2] = *count;
|
|
return off;
|
|
}
|
|
|
|
static void send_groups(const uint8_t mac[6], const char *name, bool allow_empty)
|
|
{
|
|
uint8_t pkt[REL_FRAG_MAX];
|
|
int count;
|
|
size_t len = build_groups(pkt, mac, name, &count);
|
|
if (count == 0 && !allow_empty) {
|
|
return;
|
|
}
|
|
rel_send(mac, pkt, len, false, 1);
|
|
}
|
|
|
|
static bool hex_mac(const char *s, uint8_t mac[6])
|
|
{
|
|
return parse_mac(s, mac);
|
|
}
|
|
|
|
/* Drivers that stopped acking (switched off, out of range). Every unicast to one holds a pending slot
|
|
for its whole retry run, so a few zone edits would fill the link and starve the next zone play.
|
|
Group updates go to such a driver at most once per DEAD_RETRY_US; a driver that comes back gets its
|
|
groups when it announces (boot) or resyncs (missed state). */
|
|
#define DEAD_FAILS 3
|
|
#define DEAD_RETRY_US (30LL * 1000000)
|
|
static struct {
|
|
uint8_t mac[6];
|
|
int64_t tried_us;
|
|
} s_dead[16];
|
|
|
|
static bool skip_unresponsive(const uint8_t mac[6])
|
|
{
|
|
int fails;
|
|
rel_peer_status(mac, &fails);
|
|
if (fails < DEAD_FAILS) {
|
|
return false;
|
|
}
|
|
int slot = 0;
|
|
for (int i = 0; i < 16; i++) {
|
|
if (!memcmp(s_dead[i].mac, mac, 6)) {
|
|
slot = i;
|
|
break;
|
|
}
|
|
if (s_dead[i].tried_us < s_dead[slot].tried_us) {
|
|
slot = i; // oldest entry, if this driver has none
|
|
}
|
|
}
|
|
int64_t now = esp_timer_get_time();
|
|
if (!memcmp(s_dead[slot].mac, mac, 6) && now - s_dead[slot].tried_us < DEAD_RETRY_US) {
|
|
return true;
|
|
}
|
|
memcpy(s_dead[slot].mac, mac, 6);
|
|
s_dead[slot].tried_us = now;
|
|
return false;
|
|
}
|
|
|
|
// Re-send group membership to every registered ESP-NOW driver (zones or devices changed)
|
|
void engine_groups_changed(void)
|
|
{
|
|
store_lock();
|
|
const cJSON *d;
|
|
cJSON_ArrayForEach(d, store_coll("device"))
|
|
{
|
|
const cJSON *name = cJSON_GetObjectItem(d, "name"), *addr = cJSON_GetObjectItem(d, "address");
|
|
const cJSON *tr = cJSON_GetObjectItem(d, "transport");
|
|
uint8_t mac[6];
|
|
const char *hex = cJSON_IsString(addr) ? addr->valuestring : d->string;
|
|
if (cJSON_IsString(name) && cJSON_IsString(tr) && !strcmp(tr->valuestring, "espnow") && hex_mac(hex, mac) &&
|
|
!skip_unresponsive(mac)) {
|
|
send_groups(mac, name->valuestring, true);
|
|
}
|
|
}
|
|
store_unlock();
|
|
}
|
|
|
|
#define PUSH_MAX 32
|
|
|
|
void engine_groups_push_all(int *total, int *sent, int *failed)
|
|
{
|
|
struct {
|
|
uint8_t mac[6];
|
|
uint16_t seq;
|
|
bool queued;
|
|
} out[PUSH_MAX];
|
|
int n = 0;
|
|
store_lock();
|
|
const cJSON *d;
|
|
cJSON_ArrayForEach(d, store_coll("device"))
|
|
{
|
|
const cJSON *name = cJSON_GetObjectItem(d, "name"), *addr = cJSON_GetObjectItem(d, "address");
|
|
const cJSON *tr = cJSON_GetObjectItem(d, "transport");
|
|
const char *hex = cJSON_IsString(addr) ? addr->valuestring : d->string;
|
|
if (n < PUSH_MAX && cJSON_IsString(name) && cJSON_IsString(tr) && !strcmp(tr->valuestring, "espnow") &&
|
|
hex_mac(hex, out[n].mac)) {
|
|
uint8_t pkt[REL_FRAG_MAX];
|
|
int count;
|
|
size_t len = build_groups(pkt, out[n].mac, name->valuestring, &count);
|
|
out[n].queued = false;
|
|
for (int i = 0; i < 400 && !out[n].queued; i++) { // wait for room, as tx() does
|
|
esp_err_t err = rel_send_seq(out[n].mac, pkt, len, false, 1, &out[n].seq);
|
|
out[n].queued = err == ESP_OK;
|
|
if (err != ESP_ERR_NO_MEM) {
|
|
break;
|
|
}
|
|
vTaskDelay(pdMS_TO_TICKS(5));
|
|
}
|
|
n++;
|
|
}
|
|
}
|
|
store_unlock();
|
|
// All are in flight at once; then collect each outcome (rel gives up after about 2 s)
|
|
*total = n;
|
|
*sent = *failed = 0;
|
|
for (int i = 0; i < n; i++) {
|
|
bool ok = out[i].queued && rel_wait(out[i].mac, out[i].seq, 3000) == ESP_OK;
|
|
if (ok) {
|
|
(*sent)++;
|
|
} else {
|
|
(*failed)++;
|
|
}
|
|
}
|
|
}
|
|
|
|
// A driver said hello at boot: register it, then tell it which zones it belongs to
|
|
static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len)
|
|
{
|
|
char name[48] = "";
|
|
if (pkt[0] == '{') {
|
|
cJSON *j = cJSON_ParseWithLength((const char *)pkt, len);
|
|
const cJSON *n = cJSON_GetObjectItem(j, "name");
|
|
if (cJSON_IsString(n)) {
|
|
snprintf(name, sizeof(name), "%s", n->valuestring);
|
|
}
|
|
cJSON_Delete(j);
|
|
} else if (len > 3 && pkt[2] > 0 && 3 + pkt[2] <= len) { // 4C 01 <len><name> ...
|
|
snprintf(name, sizeof(name), "%.*s", pkt[2] < sizeof(name) - 1 ? pkt[2] : (int)sizeof(name) - 1, pkt + 3);
|
|
}
|
|
if (!name[0]) {
|
|
return;
|
|
}
|
|
char hex[13];
|
|
snprintf(hex, sizeof(hex), "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
|
store_lock();
|
|
cJSON *devs = store_coll("device");
|
|
cJSON *rec = cJSON_GetObjectItem(devs, hex);
|
|
const cJSON *old = cJSON_GetObjectItem(rec, "name");
|
|
if (!rec) {
|
|
rec = cJSON_AddObjectToObject(devs, hex);
|
|
cJSON_AddStringToObject(rec, "id", hex);
|
|
cJSON_AddStringToObject(rec, "name", name);
|
|
cJSON_AddStringToObject(rec, "type", "led");
|
|
cJSON_AddStringToObject(rec, "transport", "espnow");
|
|
cJSON_AddStringToObject(rec, "address", hex);
|
|
store_save("device");
|
|
ESP_LOGI(TAG, "new driver %s (%s)", name, hex);
|
|
} else if (!cJSON_IsString(old) || strcmp(old->valuestring, name) != 0) {
|
|
cJSON_ReplaceItemInObject(rec, "name", cJSON_CreateString(name));
|
|
store_save("device");
|
|
}
|
|
send_groups(mac, name, false);
|
|
store_unlock();
|
|
}
|
|
|
|
/* A driver reported a stale state version: replay what its zone is playing, then commit the version */
|
|
static void resync_driver(const uint8_t mac[6])
|
|
{
|
|
uint8_t frame[ENV_FRAME_MAX];
|
|
store_lock();
|
|
const char *name = device_name_for(mac);
|
|
if (name) {
|
|
send_groups(mac, name, false); // membership first, in case the driver lost it
|
|
}
|
|
const zone_cur_t *best = NULL;
|
|
for (int i = 0; name && i < 16; i++) {
|
|
if (s_cur[i].zone[0] && driver_in_zone(mac, name, s_cur[i].zone) &&
|
|
(!best || (int16_t)(s_cur[i].ver - best->ver) > 0)) {
|
|
best = &s_cur[i];
|
|
}
|
|
}
|
|
bool sent = false;
|
|
if (best) {
|
|
if (strcmp(best->preset, "off") != 0) {
|
|
cJSON *payload = preset_payload(best->preset);
|
|
env_blob_t pb;
|
|
env_blob_init(&pb);
|
|
if (payload && env_add_preset(&pb, best->preset, payload)) {
|
|
send_cmd(mac, frame, env_frame(frame, -1, &pb, NULL), false);
|
|
}
|
|
cJSON_Delete(payload);
|
|
}
|
|
env_blob_t sb;
|
|
env_blob_init(&sb);
|
|
if (env_add_select(&sb, name, best->preset, -1)) {
|
|
sent = send_cmd(mac, frame, env_frame(frame, -1, NULL, &sb), true) == ESP_OK;
|
|
}
|
|
}
|
|
if (!sent) { // nothing to replay: an empty envelope still lets the driver adopt the version
|
|
send_cmd(mac, frame, env_frame(frame, -1, NULL, NULL), true);
|
|
}
|
|
store_unlock();
|
|
}
|
|
|
|
esp_err_t engine_init(void)
|
|
{
|
|
rel_set_resync_cb(resync_driver);
|
|
rel_set_announce_cb(on_announce);
|
|
return ESP_OK;
|
|
}
|