// 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 #include #include #include #include "api_util.h" #include "engine.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "rel.h" #include "store.h" #define IDENTIFY_OFF_MS 2000 // "aa:bb:cc:dd:ee:ff", "AA-BB-..." or "aabbccddeeff" -> "aabbccddeeff"; false when not a MAC static bool normalize_mac(const cJSON *v, char out[13]) { if (!cJSON_IsString(v)) { return false; } int n = 0; for (const char *s = v->valuestring; *s; s++) { if (*s == ':' || *s == '-') { continue; } if (!isxdigit((unsigned char)*s) || n == 12) { return false; } out[n++] = tolower((unsigned char)*s); } out[n] = 0; return n == 12; } // Trimmed copy of a string field; false when missing or blank static bool trimmed(const cJSON *v, char *buf, size_t len) { 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); if (!cJSON_GetObjectItem(dev, "default_pattern")) { cJSON_AddNullToObject(dev, "default_pattern"); } api_set(dev, "id", cJSON_CreateString(mac)); cJSON_DeleteItemFromObject(dev, "mac"); return NULL; } // Copy of a device with "connected": null for ESP-NOW (no link state), false for Wi-Fi (the // controller keeps no Wi-Fi driver connections) static cJSON *with_connected(const cJSON *dev) { cJSON *o = cJSON_Duplicate(dev, true); api_set(o, "connected", is_espnow(dev) ? cJSON_CreateNull() : cJSON_CreateFalse()); return o; } static cJSON *find(const char *id, char mac[13]) { cJSON *v = cJSON_CreateString(id); bool ok = normalize_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 (!normalize_mac(cJSON_GetObjectItem(body, "mac"), mac) && (wifi || !normalize_mac(cJSON_GetObjectItem(body, "address"), mac))) { err = "mac is required (12 hex digits); for Wi-Fi include mac plus IP in address"; } cJSON_DeleteItemFromObject(body, "id"); cJSON_DeleteItemFromObject(body, "connected"); cJSON_DeleteItemFromObject(body, "addresses"); if (!err) { err = normalize_device(body, mac); } 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[] = { "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; } // 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; } // 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 (!is_espnow(dev) || !cJSON_IsString(addr)) { cJSON_Delete(dc); return ESP_ERR_INVALID_ARG; } 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) && !(normalize_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); } typedef struct { char mac[13]; char name[64]; } identify_t; static void identify_off_task(void *arg) { identify_t *id = arg; vTaskDelay(pdMS_TO_TICKS(IDENTIFY_OFF_MS)); cJSON *msg = cJSON_CreateObject(); cJSON_AddStringToObject(msg, "v", "1"); cJSON *sel = cJSON_AddObjectToObject(msg, "select"), *off = cJSON_AddArrayToObject(sel, id->name); cJSON_AddItemToArray(off, cJSON_CreateString("off")); push_to(id->mac, msg); free(id); vTaskDelete(NULL); } // Blink the driver red at 10 Hz for two seconds, then select "off" static esp_err_t identify(httpd_req_t *req, const cJSON *dev, const char *mac) { const cJSON *name = cJSON_GetObjectItem(dev, "name"); if (!cJSON_IsString(name) || !name->valuestring[0]) { return api_error(req, "400 Bad Request", "Device has no name"); } if (!is_espnow(dev)) { return api_error(req, "503 Service Unavailable", "Wi-Fi driver not connected"); } cJSON *msg = cJSON_Parse("{\"v\":\"1\",\"presets\":{\"__identify\":{\"p\":\"blink\",\"c\":[\"#ff0000\"],\"d\":50," "\"b\":128,\"a\":true,\"n1\":0,\"n2\":0,\"n3\":0,\"n4\":0,\"n5\":0,\"n6\":0}}}"); cJSON *sel = cJSON_AddObjectToObject(msg, "select"), *pick = cJSON_AddArrayToObject(sel, name->valuestring); cJSON_AddItemToArray(pick, cJSON_CreateString("__identify")); esp_err_t err = push_to(mac, msg); if (err != ESP_OK) { return api_error(req, "503 Service Unavailable", "Identify send failed"); } identify_t *id = malloc(sizeof(*id)); if (id) { snprintf(id->mac, sizeof(id->mac), "%s", mac); snprintf(id->name, sizeof(id->name), "%s", name->valuestring); if (xTaskCreate(identify_off_task, "identify", 6144, id, 3, NULL) != pdPASS) { free(id); } } return api_message(req, "200 OK", "Identify sent"); } // 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); } 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 == 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], "patterns")) { *ret = api_error(req, "404 Not Found", "use POST /patterns//send with device_id"); } 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; } }