Files
led-controller/main/res_group.c
T
jimmyandClaude Opus 5.5 2f0c26e9b8 feat: default IP, reset reason in /status, seeded default group
With no DHCP answer in 15 seconds the controller takes 192.168.4.1/24, for a cable straight to a PC with a static IP. /status reports why the board last restarted. First boot also seeds a default group that the default zone plays to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:25:22 +13:00

419 lines
13 KiB
C

// 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 <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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}";
void api_add_group(const char *name, char *id, size_t len)
{
cJSON *g = cJSON_Parse(DEFAULTS);
api_set(g, "name", cJSON_CreateString(name));
api_add("group", g, id, len);
store_save("group");
}
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/<id>/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/<id>/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/<id>/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);
}
// main's Group.load: every group gets the newer fields
void api_migrate_groups(void)
{
bool changed = false;
cJSON *defs = cJSON_Parse(DEFAULTS), *g;
static const char *const KEYS[] = { "devices", "wifi_driver_display_name", "wifi_driver_num_leds", "wifi_color_order",
"wifi_startup_mode", "output_brightness", "bridge_id" };
cJSON_ArrayForEach(g, store_coll("group"))
{
if (!cJSON_IsObject(g)) {
continue;
}
for (size_t i = 0; i < sizeof(KEYS) / sizeof(KEYS[0]); i++) {
if (!cJSON_GetObjectItem(g, KEYS[i])) {
cJSON_AddItemToObject(g, KEYS[i], cJSON_Duplicate(cJSON_GetObjectItem(defs, KEYS[i]), true));
changed = true;
}
}
normalize_devices(g);
}
cJSON_Delete(defs);
if (changed) {
store_save("group");
}
}
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;
}
}