Files
jimmyandClaude Haiku 5.5 a1c8ce853b feat: sequence window, finer timeline, zone brightness to Wi-Fi drivers
- A sequence's length is a fixed window (window_beats / window_seconds), not its presets.
  The timeline is exactly the window long; clips past it are cut on save.
- The ruler adds finer ticks when zoomed in; Snap has Auto (follows the zoom), 0.25 s and 0.05 s.
  Steps and the window go down to 50 ms.
- Ctrl+wheel zooms around the pointer; the zoom buttons zoom around the last pointer position.
- Sequence start and the zone brightness slider reach Wi-Fi drivers (matched by hostname or MAC).
- A preset select with brightness also sends the brightness to Wi-Fi drivers, as ESP-NOW does.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-16 21:22:17 +13:00

997 lines
36 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// LED driver registry: the v1 app's controllers/device.py and models/device.py. Devices are keyed by
// their MAC (12 lowercase hex digits).
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "api_util.h"
#include "esp_log.h"
#include "engine.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_random.h"
#include "esp_timer.h"
#include "espnow_tx.h"
#include "rel.h"
#include "store.h"
#include "wifi_drv.h"
#define IDENTIFY_OFF_MS 2000
// Trimmed copy of a string field; false when missing or blank
static bool trimmed(const cJSON *v, char *buf, size_t len)
{
buf[0] = 0;
if (!cJSON_IsString(v)) {
return false;
}
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;
}
return buf[0] != 0;
}
static bool is_espnow(const cJSON *dev)
{
const cJSON *tr = cJSON_GetObjectItem(dev, "transport");
return !cJSON_IsString(tr) || !strcmp(tr->valuestring, "espnow");
}
// Check and tidy name, type, transport, address and zones in place; returns an error or NULL
static const char *normalize_device(cJSON *dev, const char *mac)
{
char buf[64];
if (!trimmed(cJSON_GetObjectItem(dev, "name"), buf, sizeof(buf))) {
return "name is required";
}
api_set(dev, "name", cJSON_CreateString(buf));
const cJSON *type = cJSON_GetObjectItem(dev, "type");
if (type && !cJSON_IsNull(type) && !(cJSON_IsString(type) && !strcmp(type->valuestring, "led"))) {
return "type must be led";
}
api_set(dev, "type", cJSON_CreateString("led"));
const cJSON *tr = cJSON_GetObjectItem(dev, "transport");
const char *transport = cJSON_IsString(tr) ? tr->valuestring : "espnow";
if (strcmp(transport, "espnow") && strcmp(transport, "wifi")) {
return "transport must be wifi or espnow";
}
api_set(dev, "transport", cJSON_CreateString(transport));
if (!strcmp(transport, "espnow")) {
api_set(dev, "address", cJSON_CreateString(mac));
} else {
trimmed(cJSON_GetObjectItem(dev, "address"), buf, sizeof(buf));
api_set(dev, "address", cJSON_CreateString(buf));
}
const cJSON *zones = cJSON_GetObjectItem(dev, "zones"), *z;
cJSON *out = cJSON_CreateArray();
if (!cJSON_IsArray(zones)) {
zones = out; // empty
}
cJSON_ArrayForEach(z, zones)
{
if (api_id(z, buf, sizeof(buf))) {
cJSON_AddItemToArray(out, cJSON_CreateString(buf));
}
}
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");
}
api_set(dev, "id", cJSON_CreateString(mac));
cJSON_DeleteItemFromObject(dev, "mac");
return NULL;
}
// A Wi-Fi driver's id is its mDNS hostname: the address without ".local", lower case, 12 characters or fewer
static bool wifi_id(const cJSON *body, char id[13])
{
char buf[64];
if (!trimmed(cJSON_GetObjectItem(body, "address"), buf, sizeof(buf))) {
return false;
}
size_t n = strlen(buf);
if (n > 6 && !strcmp(buf + n - 6, ".local")) {
buf[n - 6] = 0;
n -= 6;
}
if (n == 0 || n > 12) {
return false;
}
for (size_t i = 0; i < n; i++) {
if (!isalnum((unsigned char)buf[i]) && buf[i] != '-') {
return false;
}
buf[i] = (char)tolower((unsigned char)buf[i]);
}
memcpy(id, buf, n);
id[n] = 0;
return true;
}
// Copy of a device with "connected": null for ESP-NOW (no link state), and for Wi-Fi whether its
// WebSocket to the driver is up
static cJSON *with_connected(const cJSON *dev)
{
cJSON *o = cJSON_Duplicate(dev, true);
const cJSON *id = cJSON_GetObjectItem(dev, "id");
bool up = cJSON_IsString(id) && wifi_drv_connected(id->valuestring);
api_set(o, "connected", is_espnow(dev) ? cJSON_CreateNull() : cJSON_CreateBool(up));
return o;
}
static cJSON *find(const char *id, char mac[13])
{
cJSON *v = cJSON_CreateString(id);
bool ok = api_mac(v, mac);
cJSON_Delete(v);
if (!ok) {
snprintf(mac, 13, "%.12s", id);
}
return cJSON_GetObjectItem(store_coll("device"), mac);
}
static esp_err_t create_device(httpd_req_t *req)
{
cJSON *body = api_body_opt(req);
if (!body) {
return ESP_OK;
}
char name[64], mac[13];
const char *err = NULL;
const cJSON *tr = cJSON_GetObjectItem(body, "transport");
bool wifi = cJSON_IsString(tr) && !strcmp(tr->valuestring, "wifi");
if (!trimmed(cJSON_GetObjectItem(body, "name"), name, sizeof(name))) {
err = "name is required";
} else if (wifi) {
if (!wifi_id(body, mac)) {
err = "address must be the driver's hostname (letters, digits and '-', 12 characters or fewer)";
}
} else if (!api_mac(cJSON_GetObjectItem(body, "mac"), mac) && !api_mac(cJSON_GetObjectItem(body, "address"), mac)) {
err = "mac is required (12 hex digits)";
}
cJSON_DeleteItemFromObject(body, "id");
cJSON_DeleteItemFromObject(body, "connected");
cJSON_DeleteItemFromObject(body, "addresses");
if (!err) {
err = normalize_device(body, mac);
}
if (!err && wifi) {
char addr[WIFI_DRV_ID_MAX + 8];
snprintf(addr, sizeof(addr), "%s.local", mac);
api_set(body, "address", cJSON_CreateString(addr));
}
if (err) {
cJSON_Delete(body);
return api_error(req, "400 Bad Request", err);
}
cJSON *all = store_coll("device");
if (cJSON_GetObjectItem(all, mac)) {
cJSON_Delete(body);
return api_error(req, "409 Conflict", "device with this mac already exists");
}
cJSON_AddItemToObject(all, mac, body);
store_save("device");
engine_groups_changed();
cJSON *o = cJSON_CreateObject();
cJSON_AddItemReferenceToObject(o, mac, body);
return api_json(req, "201 Created", o, true);
}
// Settings a driver keeps in its own settings.json and takes from a device_config message
static const char *const DEVICE_CONFIG_KEYS[] = { "name", "max_brightness", "num_leds", "color_order", "startup_mode", "reversed" };
// The driver settings present in a device update, or NULL when it has none. Caller deletes the result.
static cJSON *device_config_from(const cJSON *body)
{
cJSON *dc = NULL;
for (size_t i = 0; i < sizeof(DEVICE_CONFIG_KEYS) / sizeof(DEVICE_CONFIG_KEYS[0]); i++) {
const cJSON *v = cJSON_GetObjectItem(body, DEVICE_CONFIG_KEYS[i]);
if (!v || cJSON_IsNull(v)) {
continue;
}
if (!dc) {
dc = cJSON_CreateObject();
}
cJSON_AddItemToObject(dc, DEVICE_CONFIG_KEYS[i], cJSON_Duplicate(v, true));
}
return dc;
}
bool api_apply_driver_cfg(cJSON *rec, const char *cfg, int len)
{
cJSON *j = cfg && len > 0 ? cJSON_ParseWithLength(cfg, len) : NULL;
bool changed = false;
// "name" is handled by the callers
for (size_t i = 1; j && rec && i < sizeof(DEVICE_CONFIG_KEYS) / sizeof(DEVICE_CONFIG_KEYS[0]); i++) {
const cJSON *v = cJSON_GetObjectItem(j, DEVICE_CONFIG_KEYS[i]);
if (!v || !(cJSON_IsNumber(v) || cJSON_IsString(v) || cJSON_IsBool(v))) {
continue;
}
const cJSON *old = cJSON_GetObjectItem(rec, DEVICE_CONFIG_KEYS[i]);
if (!old || !cJSON_Compare(old, v, true)) {
api_set(rec, DEVICE_CONFIG_KEYS[i], cJSON_Duplicate(v, true));
changed = true;
}
}
cJSON_Delete(j);
return changed;
}
// v1 messages to one driver by its MAC
static esp_err_t push_to(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;
}
// Settings a Wi-Fi driver takes at /api/hardware. Its name is its hostname and its id, so it is not sent.
static esp_err_t push_wifi_hw(const char *address, cJSON *dc)
{
char host[64];
snprintf(host, sizeof(host), "%s", address);
size_t n = strlen(host);
if (n > 6 && !strcmp(host + n - 6, ".local")) {
host[n - 6] = 0;
}
cJSON *body = cJSON_CreateObject();
const cJSON *v = cJSON_GetObjectItem(dc, "color_order");
if (cJSON_IsString(v)) {
cJSON_AddStringToObject(body, "rgb_order", v->valuestring);
}
v = cJSON_GetObjectItem(dc, "max_brightness");
if (cJSON_IsNumber(v)) {
cJSON_AddNumberToObject(body, "max_brightness", v->valuedouble);
}
v = cJSON_GetObjectItem(dc, "num_leds");
if (cJSON_IsNumber(v)) {
cJSON_AddNumberToObject(body, "num_leds", v->valuedouble);
}
cJSON_Delete(dc);
if (!body->child) {
cJSON_Delete(body);
return ESP_OK;
}
wifi_drv_post(host, "/api/hardware", body); // takes ownership of body
return ESP_OK;
}
// Send changed settings to an ESP-NOW driver; takes ownership of dc
static esp_err_t push_device_config(const cJSON *dev, cJSON *dc)
{
const cJSON *addr = cJSON_GetObjectItem(dev, "address");
if (!cJSON_IsString(addr)) {
cJSON_Delete(dc);
return ESP_ERR_INVALID_ARG;
}
if (!is_espnow(dev)) {
return push_wifi_hw(addr->valuestring, dc);
}
cJSON *msg = cJSON_CreateObject();
cJSON_AddStringToObject(msg, "v", "1");
cJSON_AddItemToObject(msg, "device_config", dc);
cJSON_AddTrueToObject(msg, "save");
return push_to(addr->valuestring, msg);
}
static esp_err_t update_device(httpd_req_t *req, cJSON *dev, const char *mac)
{
cJSON *body = api_body(req);
if (!body) {
return ESP_OK;
}
char other[13];
const cJSON *bm = cJSON_GetObjectItem(body, "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");
}
cJSON_DeleteItemFromObject(body, "connected");
cJSON_DeleteItemFromObject(body, "addresses");
cJSON *merged = cJSON_Duplicate(dev, true);
api_merge(merged, body);
const char *err = normalize_device(merged, mac);
if (err) {
cJSON_Delete(merged);
cJSON_Delete(body);
return api_error(req, "400 Bad Request", err);
}
cJSON *dev_cfg = device_config_from(body);
cJSON_Delete(body);
cJSON_ReplaceItemInObject(store_coll("device"), mac, merged);
store_save("device");
if (dev_cfg) {
push_device_config(merged, dev_cfg); // before the group resend: a second message right behind another may not be delivered
}
engine_groups_changed();
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]; // "" 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));
identify_send(id, false);
free(id);
vTaskDelete(NULL);
}
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)
{
if (!is_espnow(dev)) { // a Wi-Fi driver is identified over its own link (its id is mac)
wifi_drv_identify(mac);
return api_message(req, "200 OK", "Identify sent");
}
if (identify_start(mac, NULL) != ESP_OK) {
return api_error(req, "503 Service Unavailable", "Identify send failed");
}
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), capped at the lowest group max_brightness.
// 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;
double cap = 1.0; // lowest max_brightness of the groups listing the MAC
const cJSON *g;
cJSON_ArrayForEach(g, store_coll("group"))
{
const cJSON *it;
cJSON_ArrayForEach(it, cJSON_GetObjectItem(g, "devices"))
{
char m[13];
// A Wi-Fi driver is listed by its hostname, not a MAC
bool same = (api_mac(it, m) && !strcmp(m, mac)) || (cJSON_IsString(it) && !strcmp(it->valuestring, mac));
if (same) {
v *= clamp255(cJSON_GetObjectItem(g, "output_brightness"), 255) / 255.0;
double c = clamp255(cJSON_GetObjectItem(g, "max_brightness"), 255) / 255.0;
if (c < cap) {
cap = c;
}
break;
}
}
}
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;
}
if (v > cap) {
v = cap;
}
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/<id>/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/<id>/driver-config {name, num_leds, color_order, startup_mode}
static esp_err_t device_driver_config(httpd_req_t *req, const cJSON *dev, 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");
}
if (!is_espnow(dev)) {
const cJSON *addr = cJSON_GetObjectItem(dev, "address");
if (!cJSON_IsString(addr)) {
cJSON_Delete(dc);
return api_error(req, "500 Internal Server Error", "device has no address");
}
push_wifi_hw(addr->valuestring, dc);
return api_message(req, "200 OK", "driver-config sent");
}
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 */
#define PING_MAX 32
typedef struct {
uint8_t mac[6];
char name[33];
char cfg[200]; // the driver's settings as JSON, "" when it sent none
int rtt_ms;
} ping_rsp_t;
static struct {
uint32_t id; // 0 = no ping running
int64_t sent_us;
int count;
ping_rsp_t rsp[PING_MAX];
} s_ping;
static portMUX_TYPE s_ping_mux = portMUX_INITIALIZER_UNLOCKED;
// Rel task: [4C][06][ping_id u32 LE][len][name]
static void on_ping_rsp(const uint8_t mac[6], const uint8_t *pkt, int len)
{
if (len < 7) {
return;
}
uint32_t id = pkt[2] | (pkt[3] << 8) | (pkt[4] << 16) | ((uint32_t)pkt[5] << 24);
int nl = pkt[6] < len - 7 ? pkt[6] : len - 7;
int64_t now = esp_timer_get_time();
portENTER_CRITICAL(&s_ping_mux);
if (id && id == s_ping.id && s_ping.count < PING_MAX) {
bool seen = false;
for (int i = 0; i < s_ping.count && !seen; i++) {
seen = !memcmp(s_ping.rsp[i].mac, mac, 6);
}
if (!seen) {
ping_rsp_t *r = &s_ping.rsp[s_ping.count++];
memcpy(r->mac, mac, 6);
nl = nl < (int)sizeof(r->name) - 1 ? nl : (int)sizeof(r->name) - 1;
memcpy(r->name, pkt + 7, nl);
r->name[nl] = 0;
r->cfg[0] = 0;
int co = 7 + pkt[6]; // then [len][json]
if (co < len && pkt[co] > 0 && co + 1 + pkt[co] <= len && pkt[co] < sizeof(r->cfg)) {
memcpy(r->cfg, pkt + co + 1, pkt[co]);
r->cfg[pkt[co]] = 0;
}
r->rtt_ms = (int)((now - s_ping.sent_us) / 1000);
}
}
portEXIT_CRITICAL(&s_ping_mux);
}
// Add a driver that answered but is not registered yet, or take its new name. True when stored.
static bool register_from_ping(const char *hex, const char *name, const char *cfg)
{
char label[48];
snprintf(label, sizeof(label), "%s", name);
if (!label[0]) {
snprintf(label, sizeof(label), "led-%s", hex);
}
cJSON *devs = store_coll("device");
cJSON *rec = cJSON_GetObjectItem(devs, hex);
if (!rec) {
rec = cJSON_AddObjectToObject(devs, hex);
cJSON_AddStringToObject(rec, "id", hex);
cJSON_AddStringToObject(rec, "name", label);
cJSON_AddStringToObject(rec, "type", "led");
cJSON_AddStringToObject(rec, "transport", "espnow");
cJSON_AddStringToObject(rec, "address", hex);
api_apply_driver_cfg(rec, cfg, strlen(cfg));
return true;
}
bool changed = false;
const cJSON *old = cJSON_GetObjectItem(rec, "name");
if (is_espnow(rec) && (!cJSON_IsString(old) || strcmp(old->valuestring, label))) {
api_set(rec, "name", cJSON_CreateString(label));
changed = true;
}
if (is_espnow(rec) && api_apply_driver_cfg(rec, cfg, strlen(cfg))) {
changed = true;
}
return changed;
}
// POST /devices/ping {timeout_s, broadcast}: PING_REQ to each known device, or a broadcast when broadcast is true or none are known and collect replies for timeout_s (0.5-30, default 3)
static esp_err_t ping_devices(httpd_req_t *req)
{
static bool hooked; // replies only matter while a ping runs, so the callback is set on first use
if (!hooked) {
rel_set_ping_cb(on_ping_rsp);
hooked = true;
}
cJSON *body = api_body_opt(req);
if (!body) {
return ESP_OK;
}
const cJSON *t = cJSON_GetObjectItem(body, "timeout_s");
if (t && !cJSON_IsNull(t) && !cJSON_IsNumber(t)) {
cJSON_Delete(body);
return api_error(req, "400 Bad Request", "Invalid timeout_s");
}
double timeout_s = cJSON_IsNumber(t) ? t->valuedouble : 3.0;
timeout_s = timeout_s < 0.5 ? 0.5 : (timeout_s > 30 ? 30 : timeout_s);
bool unicast = !cJSON_IsTrue(cJSON_GetObjectItem(body, "broadcast")) && store_coll("device")->child; // no known devices: broadcast to discover them
cJSON_Delete(body);
portENTER_CRITICAL(&s_ping_mux);
bool busy = s_ping.id != 0;
uint32_t id = (esp_random() | 1);
if (!busy) {
s_ping.id = id;
s_ping.count = 0;
s_ping.sent_us = esp_timer_get_time();
}
portEXIT_CRITICAL(&s_ping_mux);
if (busy) {
return api_error(req, "409 Conflict", "a ping is already running");
}
uint8_t pkt[6] = { 0x4C, 0x05, id & 255, (id >> 8) & 255, (id >> 16) & 255, id >> 24 };
esp_err_t err = ESP_OK;
if (unicast) { // one acked frame to each known device
cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
unsigned m[6];
const cJSON *tr = cJSON_GetObjectItem(d, "transport");
bool wifi = cJSON_IsString(tr) && !strcmp(tr->valuestring, "wifi"); // ids are hostnames, not MACs
if (!wifi && d->string && sscanf(d->string, "%2x%2x%2x%2x%2x%2x", &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) == 6) {
uint8_t mac[6] = { m[0], m[1], m[2], m[3], m[4], m[5] };
esp_err_t e = espnow_tx_send(mac, pkt, sizeof(pkt));
err = e != ESP_OK ? e : err;
}
}
} else {
err = espnow_tx_send(NULL, pkt, sizeof(pkt));
vTaskDelay(pdMS_TO_TICKS(20));
espnow_tx_send(NULL, pkt, sizeof(pkt)); // a second copy against a lost broadcast; replies are deduplicated
}
if (err == ESP_OK) {
store_unlock(); // replies take up to timeout_s; HTTP and the sequencer keep going
vTaskDelay(pdMS_TO_TICKS((int)(timeout_s * 1000)));
store_lock();
}
static ping_rsp_t got[PING_MAX];
portENTER_CRITICAL(&s_ping_mux);
int n = s_ping.count;
memcpy(got, s_ping.rsp, n * sizeof(got[0]));
s_ping.id = 0;
portEXIT_CRITICAL(&s_ping_mux);
if (err != ESP_OK) {
return api_error(req, "503 Service Unavailable", "Send failed");
}
wifi_drv_ping_t wr[WIFI_DRV_PING_MAX];
store_unlock(); // Wi-Fi drivers answer over their own links; this waits up to timeout_s
int wn = wifi_drv_ping_all((int)(timeout_s * 1000), wr, WIFI_DRV_PING_MAX);
store_lock();
cJSON *o = cJSON_CreateObject(), *responses;
cJSON_AddTrueToObject(o, "ok");
cJSON_AddNumberToObject(o, "ping_id", id);
cJSON_AddNumberToObject(o, "timeout_s", timeout_s);
responses = cJSON_AddObjectToObject(o, "responses");
int registered = 0;
for (int i = 0; i < n; i++) {
char hex[13];
const uint8_t *m = got[i].mac;
snprintf(hex, sizeof(hex), "%02x%02x%02x%02x%02x%02x", m[0], m[1], m[2], m[3], m[4], m[5]);
cJSON *r = cJSON_AddObjectToObject(responses, hex);
cJSON_AddStringToObject(r, "mac", hex);
cJSON_AddStringToObject(r, "name", got[i].name);
cJSON_AddNumberToObject(r, "rtt_ms", got[i].rtt_ms);
if (got[i].cfg[0]) {
cJSON *cj = cJSON_Parse(got[i].cfg);
if (cj) {
cJSON_AddItemToObject(r, "config", cj);
}
}
registered += register_from_ping(hex, got[i].name, got[i].cfg);
}
for (int i = 0; i < wn; i++) {
if (wr[i].rtt_ms < 0) {
continue;
}
const cJSON *dev = cJSON_GetObjectItem(store_coll("device"), wr[i].id);
const cJSON *name = dev ? cJSON_GetObjectItem(dev, "name") : NULL;
cJSON *r = cJSON_AddObjectToObject(responses, wr[i].id);
cJSON_AddStringToObject(r, "mac", wr[i].id);
cJSON_AddStringToObject(r, "name", cJSON_IsString(name) ? name->valuestring : wr[i].id);
cJSON_AddNumberToObject(r, "rtt_ms", wr[i].rtt_ms);
cJSON_AddStringToObject(r, "transport", "wifi");
}
cJSON_AddNumberToObject(o, "registered", registered);
if (registered) {
store_save("device");
engine_groups_changed();
}
return api_json(req, "200 OK", o, true);
}
// POST /devices/groups: push group membership to every ESP-NOW driver and report the acks
static esp_err_t push_groups(httpd_req_t *req)
{
int total, sent, failed;
store_unlock(); // waits up to a few seconds for acks
engine_groups_push_all(&total, &sent, &failed);
store_lock();
if (!total) {
cJSON *o = cJSON_CreateObject();
cJSON_AddFalseToObject(o, "ok");
cJSON_AddStringToObject(o, "error", "No ESP-NOW devices in registry");
return api_json(req, "400 Bad Request", o, true);
}
cJSON *o = cJSON_CreateObject();
cJSON_AddBoolToObject(o, "ok", failed == 0);
cJSON_AddNumberToObject(o, "total", total);
cJSON_AddNumberToObject(o, "sent", sent);
cJSON_AddNumberToObject(o, "failed", failed);
return api_json(req, failed ? "503 Service Unavailable" : "200 OK", o, true);
}
// Per-driver delivery health from the acked link
static esp_err_t device_status(httpd_req_t *req)
{
cJSON *o = cJSON_CreateObject(), *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
const cJSON *addr = cJSON_GetObjectItem(d, "address");
const char *hex = (cJSON_IsString(addr) && strlen(addr->valuestring) == 12) ? addr->valuestring
: (strlen(d->string) == 12 ? d->string : NULL);
uint8_t mac[6];
unsigned v[6];
if (hex && sscanf(hex, "%2x%2x%2x%2x%2x%2x", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5]) == 6) {
for (int i = 0; i < 6; i++) {
mac[i] = v[i];
}
int fails;
int age = rel_peer_status(mac, &fails);
cJSON *e = cJSON_AddObjectToObject(o, d->string);
cJSON_AddNumberToObject(e, "last_ack_ms_ago", age);
cJSON_AddNumberToObject(e, "failed_messages", fails);
}
}
return api_json(req, "200 OK", o, true);
}
/* ------------------------------------------------------------- rig layout */
static bool placement_of(const cJSON *pl, double v[4])
{
static const char *const K[4] = { "x0", "y0", "x1", "y1" };
for (int i = 0; i < 4; i++) {
const cJSON *x = cJSON_GetObjectItem(pl, K[i]);
if (!cJSON_IsNumber(x)) {
return false;
}
v[i] = x->valuedouble;
}
return true;
}
// Send every placed ESP-NOW driver its strip ends in rig coordinates: centred on settings.rig_center
// (else the layout's bounding box) and scaled so the furthest end is 1 from the centre. *sent / *failed
// count the drivers.
static void push_layout(int *sent, int *failed)
{
double lo[2] = { 1e9, 1e9 }, hi[2] = { -1e9, -1e9 }, v[4];
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
if (placement_of(cJSON_GetObjectItem(d, "placement"), v)) {
for (int i = 0; i < 4; i++) {
lo[i & 1] = v[i] < lo[i & 1] ? v[i] : lo[i & 1];
hi[i & 1] = v[i] > hi[i & 1] ? v[i] : hi[i & 1];
}
}
}
double cx = (lo[0] + hi[0]) / 2, cy = (lo[1] + hi[1]) / 2, far = 0;
const cJSON *rc = cJSON_GetObjectItem(store_settings(), "rig_center");
if (cJSON_IsNumber(cJSON_GetObjectItem(rc, "x")) && cJSON_IsNumber(cJSON_GetObjectItem(rc, "y"))) {
cx = cJSON_GetObjectItem(rc, "x")->valuedouble;
cy = cJSON_GetObjectItem(rc, "y")->valuedouble;
}
cJSON_ArrayForEach(d, store_coll("device"))
{
if (placement_of(cJSON_GetObjectItem(d, "placement"), v)) {
for (int i = 0; i < 4; i += 2) {
double dx = v[i] - cx, dy = v[i + 1] - cy, r2 = dx * dx + dy * dy;
far = r2 > far ? r2 : far;
}
}
}
double scale = far > 0 ? 1.0 / sqrt(far) : 1.0;
*sent = *failed = 0;
cJSON_ArrayForEach(d, store_coll("device"))
{
if (!is_espnow(d) || !placement_of(cJSON_GetObjectItem(d, "placement"), v)) {
continue;
}
cJSON *dc = cJSON_CreateObject(), *place = cJSON_AddArrayToObject(dc, "place");
for (int i = 0; i < 4; i++) {
double c = (v[i] - (i & 1 ? cy : cx)) * scale;
cJSON_AddItemToArray(place, cJSON_CreateNumber(round(c * 1000) / 1000));
}
if (push_device_config(d, dc) == ESP_OK) {
(*sent)++;
} else {
(*failed)++;
}
}
}
// POST /devices/layout {"placements": {mac: {x0, y0, x1, y1} | null}, "center"?: {x, y}}: where each bar
// sits (x0,y0 is the data-in end, LED 1), in any units, and the rig's centre (ripples start there, spins
// turn round it). Saved on the devices and in settings.rig_center, then sent to the drivers normalised.
static esp_err_t set_layout(httpd_req_t *req)
{
cJSON *body = api_body(req);
if (!body) {
return ESP_OK;
}
const cJSON *pls = cJSON_GetObjectItem(body, "placements"), *it;
if (!cJSON_IsObject(pls)) {
cJSON_Delete(body);
return api_error(req, "400 Bad Request", "placements required");
}
int changed = 0;
cJSON_ArrayForEach(it, pls)
{
char mac[13];
cJSON *key = cJSON_CreateString(it->string);
bool ok = api_mac(key, mac);
cJSON_Delete(key);
cJSON *dev = ok ? cJSON_GetObjectItem(store_coll("device"), mac) : NULL;
double v[4];
if (!dev) {
continue;
}
if (cJSON_IsNull(it)) {
cJSON_DeleteItemFromObject(dev, "placement");
} else if (placement_of(it, v)) {
cJSON *pl = cJSON_CreateObject();
cJSON_AddNumberToObject(pl, "x0", v[0]);
cJSON_AddNumberToObject(pl, "y0", v[1]);
cJSON_AddNumberToObject(pl, "x1", v[2]);
cJSON_AddNumberToObject(pl, "y1", v[3]);
api_set(dev, "placement", pl);
} else {
continue;
}
changed++;
}
const cJSON *center = cJSON_GetObjectItem(body, "center");
if (cJSON_IsNumber(cJSON_GetObjectItem(center, "x")) && cJSON_IsNumber(cJSON_GetObjectItem(center, "y"))) {
cJSON *rc = cJSON_CreateObject();
cJSON_AddNumberToObject(rc, "x", cJSON_GetObjectItem(center, "x")->valuedouble);
cJSON_AddNumberToObject(rc, "y", cJSON_GetObjectItem(center, "y")->valuedouble);
api_set(store_settings(), "rig_center", rc);
store_save("settings");
}
cJSON_Delete(body);
if (changed) {
store_save("device");
}
int sent, failed;
push_layout(&sent, &failed);
cJSON *o = cJSON_CreateObject();
cJSON_AddNumberToObject(o, "updated", changed);
cJSON_AddNumberToObject(o, "sent", sent);
cJSON_AddNumberToObject(o, "failed", failed);
return api_json(req, "200 OK", o, true);
}
bool devices_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret)
{
const int method = req->method;
if (n == 2 && method == HTTP_GET && !strcmp(seg[1], "status")) {
*ret = device_status(req);
return true;
}
if (n == 2 && method == HTTP_POST && !strcmp(seg[1], "ping")) {
*ret = ping_devices(req);
return true;
}
if (n == 2 && method == HTTP_POST && !strcmp(seg[1], "groups")) {
*ret = push_groups(req);
return true;
}
if (n == 2 && method == HTTP_POST && !strcmp(seg[1], "layout")) {
*ret = set_layout(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;
cJSON_ArrayForEach(d, store_coll("device"))
{
cJSON_AddItemToObject(o, d->string, with_connected(d));
}
*ret = api_json(req, "200 OK", o, true);
return true;
}
if (method == HTTP_POST) {
*ret = create_device(req);
return true;
}
return false;
}
char mac[13];
cJSON *dev = find(seg[1], mac);
if (!dev) {
*ret = api_error(req, "404 Not Found", "Device not found");
return true;
}
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, dev, mac);
} else if (method == HTTP_POST && !strcmp(seg[2], "patterns")) {
*ret = api_error(req, "400 Bad Request", "Pattern OTA push is not supported for ESP-NOW devices");
} else {
*ret = api_error(req, "404 Not Found", "unknown action");
}
return true;
}
switch (method) {
case HTTP_GET:
*ret = api_json(req, "200 OK", with_connected(dev), true);
return true;
case HTTP_PUT:
*ret = update_device(req, dev, mac);
return true;
case HTTP_DELETE:
cJSON_DeleteItemFromObject(store_coll("device"), mac);
store_save("device");
engine_groups_changed();
*ret = api_message(req, "200 OK", "Device deleted successfully");
return true;
default:
return false;
}
}