diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index 74428cd..693a574 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -1,8 +1,9 @@ idf_component_register(SRCS "main.c" "mic.c" "beat.c" "beat_dsp.c" "espnow_tx.c" "store.c" "api.c" "web.c" "envelope.c" "engine.c" "rel.c" "bench.c" "audio.c" "ota.c" "drv_ota.c" + "res_profile.c" "res_misc.c" "res_device.c" "patterns.c" "outputs.c" "ws.c" INCLUDE_DIRS "." REQUIRES esp_eth esp_netif esp_event esp_driver_spi esp_driver_gpio nvs_flash app_update esp_app_format esp_http_server esp_timer esp_driver_i2s esp_wifi esp_rom json esp_driver_gpio - PRIV_REQUIRES littlefs mdns) + PRIV_REQUIRES littlefs mdns mbedtls lwip) # The gzipped web UI is embedded in the app image (run tools/build_web.sh first) if(NOT EXISTS ${PROJECT_DIR}/www_dist/www.pack) diff --git a/main/api.c b/main/api.c index 84b8f9c..297375e 100644 --- a/main/api.c +++ b/main/api.c @@ -3,12 +3,13 @@ #include #include #include +#include "api_util.h" #include "cJSON.h" #include "esp_log.h" #include "bench.h" #include "engine.h" #include "espnow_tx.h" -#include "rel.h" +#include "sdkconfig.h" #include "store.h" #include "web.h" @@ -27,7 +28,9 @@ static const struct { { "outputs", "output" }, }; -static esp_err_t send_json(httpd_req_t *req, const char *status, cJSON *obj, bool own) +/* ---------------------------------------------------------------- helpers */ + +esp_err_t api_json(httpd_req_t *req, const char *status, cJSON *obj, bool own) { char *s = cJSON_PrintUnformatted(obj); if (own) { @@ -43,18 +46,41 @@ static esp_err_t send_json(httpd_req_t *req, const char *status, cJSON *obj, boo return ret; } -static esp_err_t send_error(httpd_req_t *req, const char *status, const char *msg) +esp_err_t api_error(httpd_req_t *req, const char *status, const char *msg) { cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "error", msg); - return send_json(req, status, o, true); + return api_json(req, status, o, true); } -// Parsed JSON object body, or NULL after an error response has been sent -static cJSON *read_body(httpd_req_t *req) +esp_err_t api_message(httpd_req_t *req, const char *status, const char *msg) { + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "message", msg); + return api_json(req, status, o, true); +} + +esp_err_t api_result(httpd_req_t *req, esp_err_t err, const char *ok_msg) +{ + switch (err) { + case ESP_OK: + return api_message(req, "200 OK", ok_msg); + case ESP_ERR_NOT_FOUND: + return api_error(req, "404 Not Found", "not found"); + case ESP_ERR_INVALID_SIZE: + return api_error(req, "413 Payload Too Large", "preset too large for one ESP-NOW frame"); + default: + return api_error(req, "503 Service Unavailable", "send failed"); + } +} + +static cJSON *body_impl(httpd_req_t *req, bool optional) +{ + if (req->content_len == 0 && optional) { + return cJSON_CreateObject(); + } if (req->content_len == 0 || req->content_len > BODY_MAX) { - send_error(req, "400 Bad Request", req->content_len ? "body too large" : "body required"); + api_error(req, "400 Bad Request", req->content_len ? "body too large" : "body required"); return NULL; } char *buf = malloc(req->content_len + 1); @@ -77,14 +103,16 @@ static cJSON *read_body(httpd_req_t *req) free(buf); if (!cJSON_IsObject(obj)) { cJSON_Delete(obj); - send_error(req, "400 Bad Request", "JSON object required"); + api_error(req, "400 Bad Request", "JSON object required"); return NULL; } return obj; } -// Split "/res/id/action?query" into up to three segments -static int split_path(const char *uri, char seg[3][64]) +cJSON *api_body(httpd_req_t *req) { return body_impl(req, false); } +cJSON *api_body_opt(httpd_req_t *req) { return body_impl(req, true); } + +int api_split(const char *uri, api_seg_t seg) { int n = 0; const char *p = uri; @@ -112,7 +140,18 @@ static const char *coll_for(const char *res) return NULL; } -static const char *current_profile(void) +bool api_id(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; +} + +const char *api_current_profile(void) { cJSON *v = cJSON_GetObjectItem(store_settings(), "current_profile_id"); if (cJSON_IsString(v) && cJSON_GetObjectItem(store_coll("profile"), v->valuestring)) { @@ -122,291 +161,107 @@ static const char *current_profile(void) return first ? first->string : NULL; } -static bool preset_in_profile(cJSON *rec) +bool api_preset_in_profile(const cJSON *rec) { - const char *cur = current_profile(); - cJSON *pid = cJSON_GetObjectItem(rec, "profile_id"); + const char *cur = api_current_profile(); if (!cur) { return true; } - char num[24] = ""; - if (cJSON_IsNumber(pid)) { - snprintf(num, sizeof(num), "%d", (int)pid->valuedouble); - } - return (cJSON_IsString(pid) && strcmp(pid->valuestring, cur) == 0) || strcmp(num, cur) == 0; + char pid[24]; + return api_id(cJSON_GetObjectItem(rec, "profile_id"), pid, sizeof(pid)) && strcmp(pid, cur) == 0; } -static void merge(cJSON *dst, cJSON *src) +void api_set(cJSON *obj, const char *key, cJSON *val) { - cJSON *it; + if (cJSON_GetObjectItem(obj, key)) { + cJSON_ReplaceItemInObject(obj, key, val); + } else { + cJSON_AddItemToObject(obj, key, val); + } +} + +void api_merge(cJSON *dst, const cJSON *src) +{ + const cJSON *it; cJSON_ArrayForEach(it, src) { - if (strcmp(it->string, "id") == 0) { - continue; - } - cJSON *copy = cJSON_Duplicate(it, true); - if (cJSON_GetObjectItem(dst, it->string)) { - cJSON_ReplaceItemInObject(dst, it->string, copy); - } else { - cJSON_AddItemToObject(dst, it->string, copy); + if (strcmp(it->string, "id") != 0) { + api_set(dst, it->string, cJSON_Duplicate(it, true)); } } } -static esp_err_t send_message(httpd_req_t *req, const char *status, const char *msg) +void api_add(const char *coll, cJSON *rec, char *id, size_t len) { - cJSON *o = cJSON_CreateObject(); - cJSON_AddStringToObject(o, "message", msg); - return send_json(req, status, o, true); -} - -static esp_err_t result(httpd_req_t *req, esp_err_t err, const char *ok_msg) -{ - switch (err) { - case ESP_OK: - return send_message(req, "200 OK", ok_msg); - case ESP_ERR_NOT_FOUND: - return send_error(req, "404 Not Found", "not found"); - case ESP_ERR_INVALID_SIZE: - return send_error(req, "413 Payload Too Large", "preset too large for one ESP-NOW frame"); - default: - return send_error(req, "503 Service Unavailable", "send failed"); + store_next_id(coll, id, len); + if (cJSON_IsObject(rec)) { + api_set(rec, "id", cJSON_CreateString(id)); } + cJSON_AddItemToObject(store_coll(coll), id, rec); } -static esp_err_t not_implemented(httpd_req_t *req, const char *what) -{ - char msg[96]; - snprintf(msg, sizeof(msg), "%s is not implemented in v2 yet", what); - return send_error(req, "501 Not Implemented", msg); -} +/* ------------------------------------------------------------ collections */ -static esp_err_t handle_profile_action(httpd_req_t *req, const char *id, const char *action) +static bool route(const char *res, httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) { - if (strcmp(action, "apply") == 0) { - if (!cJSON_GetObjectItem(store_coll("profile"), id)) { - return send_error(req, "404 Not Found", "profile not found"); + static const struct { + const char *res; + bool (*fn)(httpd_req_t *, int, api_seg_t, esp_err_t *); + } ROUTERS[] = { + { "profiles", profiles_route }, { "zones", zones_route }, { "presets", presets_route }, + { "palettes", palettes_route }, { "sequences", sequences_route }, { "devices", devices_route }, + { "patterns", patterns_route }, { "outputs", outputs_route }, + }; + for (size_t i = 0; i < sizeof(ROUTERS) / sizeof(ROUTERS[0]); i++) { + if (!strcmp(ROUTERS[i].res, res)) { + return ROUTERS[i].fn(req, n, seg, ret); } - cJSON *st = store_settings(); - cJSON_DeleteItemFromObject(st, "current_profile_id"); - cJSON_AddStringToObject(st, "current_profile_id", id); - store_save("settings"); - cJSON *o = cJSON_CreateObject(); - cJSON_AddStringToObject(o, "message", "Profile applied"); - return send_json(req, "200 OK", o, true); } - return not_implemented(req, action); -} - -// 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; -} - -// 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 *tr = cJSON_GetObjectItem(dev, "transport"), *addr = cJSON_GetObjectItem(dev, "address"); - if (!cJSON_IsString(tr) || strcmp(tr->valuestring, "espnow") || !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"); - cJSON *messages = cJSON_CreateArray(), *targets = cJSON_CreateArray(); - cJSON_AddItemToArray(messages, msg); - cJSON_AddItemToArray(targets, cJSON_CreateString(addr->valuestring)); - esp_err_t err = engine_push(messages, targets); - cJSON_Delete(messages); - cJSON_Delete(targets); - return err; + return false; } static esp_err_t collection_handler_inner(httpd_req_t *req) { - char seg[3][64]; - int n = split_path(req->uri, seg); + api_seg_t seg; + int n = api_split(req->uri, seg); const char *coll = n ? coll_for(seg[0]) : NULL; if (!coll) { - return send_error(req, "404 Not Found", "unknown resource"); + return api_error(req, "404 Not Found", "unknown resource"); + } + esp_err_t ret; + if (route(seg[0], req, n, seg, &ret)) { + return ret; } const bool is_presets = strcmp(coll, "preset") == 0; const bool is_profiles = strcmp(coll, "profile") == 0; + const bool groups_change = !strcmp(coll, "zone") || !strcmp(coll, "device"); cJSON *all = store_coll(coll); const int method = req->method; - // GET /devices/status: per-driver delivery health from the acked link - if (n == 2 && method == HTTP_GET && !strcmp(seg[0], "devices") && !strcmp(seg[1], "status")) { - cJSON *o = cJSON_CreateObject(), *d; - cJSON_ArrayForEach(d, all) - { - 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 send_json(req, "200 OK", o, true); - } - // /// - if (n == 3 && !strcmp(seg[0], "zones") && !strcmp(seg[1], "engine") && !strcmp(seg[2], "status")) { - return send_json(req, "200 OK", engine_status(), true); - } - if (n == 3 && method == HTTP_POST && !strcmp(seg[0], "zones")) { - if (!strcmp(seg[2], "play")) { - cJSON *body = read_body(req); - if (!body) { - return ESP_OK; - } - const cJSON *pid = cJSON_GetObjectItem(body, "preset_id"); - const cJSON *drv = cJSON_GetObjectItem(body, "drivers"); - char key[24] = ""; - if (cJSON_IsString(pid)) { - snprintf(key, sizeof(key), "%s", pid->valuestring); - } else if (cJSON_IsNumber(pid)) { - snprintf(key, sizeof(key), "%d", (int)pid->valuedouble); - } - // The UI sends drivers:false when it pushes to drivers itself; v2 has no pixel outputs - bool skip = cJSON_IsFalse(drv); - cJSON_Delete(body); - if (!key[0]) { - return send_error(req, "400 Bad Request", "preset_id required"); - } - return result(req, skip ? ESP_OK : engine_play(seg[1], key), "Playing"); - } - if (!strcmp(seg[2], "stop")) { - return result(req, engine_stop(seg[1]), "Stopped"); - } - } - if (n == 3 && method == HTTP_POST && !strcmp(seg[0], "sequences")) { - if (!strcmp(seg[2], "play")) { - return result(req, engine_seq_play(seg[1]), "Sequence started"); - } - if (!strcmp(seg[2], "stop")) { - return result(req, engine_seq_stop(seg[1]), "Sequence stopped"); - } - } if (n == 3 && method == HTTP_POST && !strcmp(seg[0], "scenes")) { if (!strcmp(seg[2], "play")) { - return result(req, engine_scene_play(seg[1]), "Scene started"); + return api_result(req, engine_scene_play(seg[1]), "Scene started"); } if (!strcmp(seg[2], "stop")) { - return result(req, engine_scene_stop(seg[1]), "Scene stopped"); + return api_result(req, engine_scene_stop(seg[1]), "Scene stopped"); } } - if (n == 2 && method == HTTP_GET && !strcmp(seg[0], "sequences") && !strcmp(seg[1], "status")) { - return send_json(req, "200 OK", engine_status(), true); - } if (n == 3) { - if (is_profiles && method == HTTP_POST) { - return handle_profile_action(req, seg[1], seg[2]); - } - return not_implemented(req, seg[2]); - } - // /presets/send, /presets/push - if (is_presets && n == 2 && method == HTTP_POST && !strcmp(seg[1], "push")) { - cJSON *body = read_body(req); - if (!body) { - return ESP_OK; - } - const cJSON *seq = cJSON_GetObjectItem(body, "sequence"); - const cJSON *payload = cJSON_GetObjectItem(body, "payload"); - cJSON *one = NULL; - if (!cJSON_IsArray(seq) && payload) { - one = cJSON_CreateArray(); - cJSON_AddItemReferenceToArray(one, (cJSON *)payload); - seq = one; - } - esp_err_t err = ESP_ERR_INVALID_ARG; - if (cJSON_IsArray(seq) && cJSON_GetArraySize(seq)) { - err = engine_push(seq, cJSON_GetObjectItem(body, "targets")); - } - cJSON_Delete(one); - cJSON_Delete(body); - return err == ESP_ERR_INVALID_ARG ? send_error(req, "400 Bad Request", "sequence or payload required") - : result(req, err, "Delivered"); - } - if (is_presets && n == 2 && method == HTTP_POST && !strcmp(seg[1], "send")) { - cJSON *body = read_body(req); - if (!body) { - return ESP_OK; - } - const cJSON *ids = cJSON_GetObjectItem(body, "preset_ids"); - if (!cJSON_IsArray(ids)) { - ids = cJSON_GetObjectItem(body, "ids"); - } - if (!cJSON_IsArray(ids) || !cJSON_GetArraySize(ids)) { - cJSON_Delete(body); - return send_error(req, "400 Bad Request", "preset_ids must be a non-empty list"); - } - const cJSON *save = cJSON_GetObjectItem(body, "save"); - const cJSON *def = cJSON_GetObjectItem(body, "default"); - char defbuf[24] = ""; - if (cJSON_IsString(def)) { - snprintf(defbuf, sizeof(defbuf), "%s", def->valuestring); - } else if (cJSON_IsNumber(def)) { - snprintf(defbuf, sizeof(defbuf), "%d", (int)def->valuedouble); - } - const cJSON *targets = cJSON_GetObjectItem(body, "targets"); - cJSON *single = NULL; - const cJSON *dest = cJSON_GetObjectItem(body, "destination_mac"); - if (!cJSON_IsArray(targets) && cJSON_IsString(dest)) { - single = cJSON_CreateArray(); - cJSON_AddItemToArray(single, cJSON_CreateString(dest->valuestring)); - targets = single; - } - int sent = 0; - esp_err_t err = engine_send_presets(ids, !save || cJSON_IsTrue(save), defbuf[0] ? defbuf : NULL, targets, &sent); - cJSON_Delete(single); - cJSON_Delete(body); - if (err != ESP_OK) { - return result(req, err, ""); - } - cJSON *o = cJSON_CreateObject(); - cJSON_AddStringToObject(o, "message", "Presets sent"); - cJSON_AddNumberToObject(o, "presets_sent", sent); - return send_json(req, "200 OK", o, true); + return api_error(req, "404 Not Found", "unknown action"); } // "current" profile aliases const char *id = n == 2 ? seg[1] : NULL; if (is_profiles && id && strcmp(id, "current") == 0) { - id = current_profile(); + id = api_current_profile(); if (!id) { - return send_error(req, "404 Not Found", "no profiles"); + return api_error(req, "404 Not Found", "No profile available"); } if (method == HTTP_GET) { cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "id", id); cJSON_AddItemReferenceToObject(o, "profile", cJSON_GetObjectItem(all, id)); - return send_json(req, "200 OK", o, true); + return api_json(req, "200 OK", o, true); } } @@ -415,133 +270,174 @@ static esp_err_t collection_handler_inner(httpd_req_t *req) if (is_profiles) { cJSON *o = cJSON_CreateObject(); cJSON_AddItemReferenceToObject(o, "profiles", all); - const char *cur = current_profile(); + const char *cur = api_current_profile(); cJSON_AddStringToObject(o, "current_profile_id", cur ? cur : ""); - return send_json(req, "200 OK", o, true); + return api_json(req, "200 OK", o, true); } if (is_presets) { cJSON *o = cJSON_CreateObject(), *it; cJSON_ArrayForEach(it, all) { - if (preset_in_profile(it)) { + if (api_preset_in_profile(it)) { cJSON_AddItemReferenceToObject(o, it->string, it); } } - return send_json(req, "200 OK", o, true); + return api_json(req, "200 OK", o, true); } - return send_json(req, "200 OK", all, false); + return api_json(req, "200 OK", all, false); } if (method == HTTP_POST) { - cJSON *body = read_body(req); + cJSON *body = api_body(req); if (!body) { return ESP_OK; } char nid[16]; - store_next_id(coll, nid, sizeof(nid)); - cJSON_AddStringToObject(body, "id", nid); - if (is_presets && current_profile() && !cJSON_GetObjectItem(body, "profile_id")) { - cJSON_AddStringToObject(body, "profile_id", current_profile()); - } - cJSON_AddItemToObject(all, nid, body); + api_add(coll, body, nid, sizeof(nid)); store_save(coll); - if (!strcmp(coll, "zone") || !strcmp(coll, "device")) { + if (groups_change) { engine_groups_changed(); } cJSON *o = cJSON_CreateObject(); cJSON_AddItemReferenceToObject(o, nid, body); - return send_json(req, "201 Created", o, true); + return api_json(req, "201 Created", o, true); } - return send_error(req, "405 Method Not Allowed", "method not allowed"); + return api_error(req, "405 Method Not Allowed", "method not allowed"); } cJSON *rec = cJSON_GetObjectItem(all, id); - if (!rec || (is_presets && !preset_in_profile(rec))) { - return send_error(req, "404 Not Found", "not found"); + if (!rec || (is_presets && !api_preset_in_profile(rec))) { + return api_error(req, "404 Not Found", "not found"); } switch (method) { case HTTP_GET: - return send_json(req, "200 OK", rec, false); + return api_json(req, "200 OK", rec, false); case HTTP_PUT: { - cJSON *body = read_body(req); + cJSON *body = api_body(req); if (!body) { return ESP_OK; } - cJSON *dev_cfg = !strcmp(coll, "device") ? device_config_from(body) : NULL; - merge(rec, body); + api_merge(rec, body); cJSON_Delete(body); store_save(coll); - if (dev_cfg) { - push_device_config(rec, dev_cfg); // before the group resend: a second message right behind another may not be delivered - } - if (!strcmp(coll, "zone") || !strcmp(coll, "device")) { + if (groups_change) { engine_groups_changed(); } - return send_json(req, "200 OK", rec, false); + return api_json(req, "200 OK", rec, false); } case HTTP_DELETE: { cJSON_DeleteItemFromObject(all, id); store_save(coll); - if (!strcmp(coll, "zone") || !strcmp(coll, "device")) { + if (groups_change) { engine_groups_changed(); } - cJSON *o = cJSON_CreateObject(); - cJSON_AddStringToObject(o, "message", "Deleted"); - return send_json(req, "200 OK", o, true); + return api_message(req, "200 OK", "Deleted"); } default: - return send_error(req, "405 Method Not Allowed", "method not allowed"); + return api_error(req, "405 Method Not Allowed", "method not allowed"); } } +/* --------------------------------------------------------------- settings */ + +// Defaults the v1 app seeded into settings.json +void api_settings_defaults(void) +{ + cJSON *st = store_settings(); + bool changed = false; + if (!cJSON_IsNumber(cJSON_GetObjectItem(st, "wifi_channel"))) { + api_set(st, "wifi_channel", cJSON_CreateNumber(CONFIG_ESPNOW_CHANNEL)); + changed = true; + } + if (!cJSON_IsNumber(cJSON_GetObjectItem(st, "global_brightness"))) { + api_set(st, "global_brightness", cJSON_CreateNumber(255)); + changed = true; + } + if (changed) { + store_save("settings"); + } +} + +// Integer in [lo, hi], or false +static bool int_in(const cJSON *v, int lo, int hi) +{ + return cJSON_IsNumber(v) && v->valuedouble == (int)v->valuedouble && v->valuedouble >= lo && v->valuedouble <= hi; +} + +static esp_err_t put_settings(httpd_req_t *req) +{ + cJSON *body = api_body(req); + if (!body) { + return ESP_OK; + } + const cJSON *ch = cJSON_GetObjectItem(body, "wifi_channel"); + const cJSON *gb = cJSON_GetObjectItem(body, "global_brightness"); + const char *bad = (ch && !int_in(ch, 1, 11)) ? "wifi_channel must be an integer between 1 and 11" + : (gb && !int_in(gb, 0, 255)) ? "global_brightness must be an integer between 0 and 255" + : NULL; + if (bad) { + cJSON_Delete(body); + return api_error(req, "400 Bad Request", bad); + } + const cJSON *old = cJSON_GetObjectItem(store_settings(), "global_brightness"); + bool push = gb && !(cJSON_IsNumber(old) && old->valuedouble == gb->valuedouble); + int level = gb ? (int)gb->valuedouble : 0; + api_merge(store_settings(), body); + cJSON_Delete(body); + store_save("settings"); + if (push) { + // Server-wide brightness goes to every driver + cJSON *msgs = cJSON_CreateArray(), *m = cJSON_CreateObject(); + cJSON_AddStringToObject(m, "v", "1"); + cJSON_AddNumberToObject(m, "b", level); + cJSON_AddItemToArray(msgs, m); + engine_push(msgs, NULL); + cJSON_Delete(msgs); + } + return api_message(req, "200 OK", "Settings updated successfully"); +} + static esp_err_t settings_handler_inner(httpd_req_t *req) { - char seg[3][64]; - int n = split_path(req->uri, seg); + api_seg_t seg; + int n = api_split(req->uri, seg); if (n == 2 && strcmp(seg[1], "page") == 0 && req->method == HTTP_GET) { return web_send_page(req, "settings.html"); } if (n == 1 && req->method == HTTP_GET) { - return send_json(req, "200 OK", store_settings(), false); + return api_json(req, "200 OK", store_settings(), false); } if (n == 2 && strcmp(seg[1], "settings") == 0 && req->method == HTTP_PUT) { - cJSON *body = read_body(req); - if (!body) { - return ESP_OK; - } - merge(store_settings(), body); - cJSON_Delete(body); - store_save("settings"); - cJSON *o = cJSON_CreateObject(); - cJSON_AddStringToObject(o, "message", "Settings updated successfully"); - return send_json(req, "200 OK", o, true); + return put_settings(req); } - return not_implemented(req, "this settings route"); + return api_error(req, "404 Not Found", "unknown settings route"); } +/* --------------------------------------------------------------------- db */ + // GET /db/ exports a collection, PUT /db/ replaces it (import of the Pi's db/*.json) static esp_err_t db_handler_inner(httpd_req_t *req) { - char seg[3][64]; - int n = split_path(req->uri, seg); + api_seg_t seg; + int n = api_split(req->uri, seg); if (n != 2 || !store_known(seg[1])) { - return send_error(req, "404 Not Found", "unknown collection"); + return api_error(req, "404 Not Found", "unknown collection"); } if (req->method == HTTP_GET) { - return send_json(req, "200 OK", store_coll(seg[1]), false); + return api_json(req, "200 OK", store_coll(seg[1]), false); } if (req->method == HTTP_PUT) { - cJSON *body = read_body(req); + cJSON *body = api_body(req); if (!body) { return ESP_OK; } if (store_replace(seg[1], body) != ESP_OK) { - return send_error(req, "500 Internal Server Error", "save failed"); + return api_error(req, "500 Internal Server Error", "save failed"); } cJSON *o = cJSON_CreateObject(); cJSON_AddNumberToObject(o, "records", cJSON_GetArraySize(store_coll(seg[1]))); - return send_json(req, "200 OK", o, true); + return api_json(req, "200 OK", o, true); } - return send_error(req, "405 Method Not Allowed", "method not allowed"); + return api_error(req, "405 Method Not Allowed", "method not allowed"); } #define LOCKED(name) \ @@ -556,14 +452,16 @@ LOCKED(collection_handler) LOCKED(settings_handler) LOCKED(db_handler) +/* ------------------------------------------------------------------ tests */ + // Bench tests: /test/loss and /test/beats static esp_err_t test_handler_inner(httpd_req_t *req) { - char seg[3][64]; - int n = split_path(req->uri, seg); + api_seg_t seg; + int n = api_split(req->uri, seg); if (n >= 2 && !strcmp(seg[1], "loss")) { if (req->method == HTTP_POST) { - cJSON *b = read_body(req); + cJSON *b = api_body(req); if (!b) { return ESP_OK; } @@ -576,13 +474,13 @@ static esp_err_t test_handler_inner(httpd_req_t *req) cJSON *o = cJSON_CreateObject(); cJSON_AddNumberToObject(o, "percent", pct); cJSON_AddBoolToObject(o, "beats", inc); - return send_json(req, "200 OK", o, true); + return api_json(req, "200 OK", o, true); } if (n >= 2 && !strcmp(seg[1], "beats")) { if (req->method == HTTP_POST && n == 3 && !strcmp(seg[2], "stop")) { bench_stop(); } else if (req->method == HTTP_POST) { - cJSON *b = read_body(req); + cJSON *b = api_body(req); if (!b) { return ESP_OK; } @@ -591,17 +489,18 @@ static esp_err_t test_handler_inner(httpd_req_t *req) cJSON_IsNumber(count) ? (int)count->valuedouble : 100); cJSON_Delete(b); if (err != ESP_OK) { - return send_error(req, "400 Bad Request", "bpm must be 30-300"); + return api_error(req, "400 Bad Request", "bpm must be 30-300"); } } - return send_json(req, "200 OK", bench_results(), true); + return api_json(req, "200 OK", bench_results(), true); } - return send_error(req, "404 Not Found", "unknown test"); + return api_error(req, "404 Not Found", "unknown test"); } LOCKED(test_handler) esp_err_t api_register(httpd_handle_t server) { + api_settings_defaults(); static const char *const ROUTES[] = { "/devices*", "/zones*", "/presets*", "/profiles*", "/palettes*", "/patterns*", "/sequences*", "/scenes*", "/groups*", "/outputs*", diff --git a/main/api_util.h b/main/api_util.h new file mode 100644 index 0000000..af37b2f --- /dev/null +++ b/main/api_util.h @@ -0,0 +1,50 @@ +#pragma once + +#include +#include +#include "cJSON.h" +#include "esp_err.h" +#include "esp_http_server.h" + +// Helpers shared by the REST handlers (api.c and the res_*.c resource modules) + +// Path segments of "/res/id/action?query" (at most three) +typedef char api_seg_t[3][64]; +int api_split(const char *uri, api_seg_t seg); + +// Send obj as JSON; own=true deletes it afterwards +esp_err_t api_json(httpd_req_t *req, const char *status, cJSON *obj, bool own); +esp_err_t api_error(httpd_req_t *req, const char *status, const char *msg); +esp_err_t api_message(httpd_req_t *req, const char *status, const char *msg); +// 200 {message} for ESP_OK, otherwise a matching error status +esp_err_t api_result(httpd_req_t *req, esp_err_t err, const char *ok_msg); + +// Parsed JSON object body, or NULL after an error response has been sent. api_body_opt treats an +// empty body as {}. +cJSON *api_body(httpd_req_t *req); +cJSON *api_body_opt(httpd_req_t *req); + +// Shallow merge of src into dst, skipping "id" +void api_merge(cJSON *dst, const cJSON *src); +// Set (replace or add) one key +void api_set(cJSON *obj, const char *key, cJSON *val); +// Record id as text from a string or number value; false (buf empty) otherwise +bool api_id(const cJSON *v, char *buf, size_t len); + +// Add rec under the collection's next id (with an "id" field when rec is an object); id gets the key +void api_add(const char *coll, cJSON *rec, char *id, size_t len); + +// Current profile id (settings.current_profile_id, else the first profile), or NULL +const char *api_current_profile(void); +bool api_preset_in_profile(const cJSON *rec); + +// Resource handlers, called with the store locked. Each returns true when it answered the request +// (its result in *ret); false hands the request to the generic collection CRUD. +bool profiles_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); +bool zones_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); +bool presets_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); +bool palettes_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); +bool sequences_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); +bool devices_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); +bool patterns_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); +bool outputs_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); diff --git a/main/drv_ota.c b/main/drv_ota.c index c1fca8c..2f52cbb 100644 --- a/main/drv_ota.c +++ b/main/drv_ota.c @@ -6,6 +6,8 @@ #include #include "cJSON.h" #include "esp_log.h" +#include "esp_random.h" +#include "mbedtls/sha256.h" #include "freertos/FreeRTOS.h" #include "freertos/queue.h" #include "freertos/semphr.h" @@ -452,6 +454,43 @@ static esp_err_t ota_post_handler(httpd_req_t *req) return r; } +cJSON *drv_ota_send(const char *macs, const char *path, const uint8_t *data, size_t len, bool commit, esp_err_t *err) +{ + static target_t ts[MAX_MACS]; + if (len > MAX_FILE || strlen(path) > MAX_PATH) { + *err = ESP_ERR_INVALID_SIZE; + return NULL; + } + if (!s_busy || xSemaphoreTake(s_busy, 0) != pdTRUE) { + *err = ESP_ERR_INVALID_STATE; + return NULL; + } + cJSON *out = NULL; + int n = parse_targets(macs, ts); + if (n <= 0) { + *err = n < 0 ? ESP_ERR_INVALID_ARG : ESP_ERR_NOT_FOUND; + } else { + uint8_t sha[32]; + mbedtls_sha256(data, len, sha, 0); + uint16_t sess = (esp_random() % 0xFFFF) + 1; + drain_status(); + ESP_LOGI(TAG, "%s (%u B) to %d driver(s), session %u", path, (unsigned)len, n, sess); + transfer(ts, n, sess, path, sha, data, len); + out = results(ts, n, true); + if (commit) { + uint8_t pkt[4] = { WIRE_MAGIC, OP_COMMIT, sess & 255, sess >> 8 }; + for (int i = 0; i < n; i++) { + if (ts[i].state == C_OK) { + command(ts[i].mac, pkt, sizeof(pkt), sess, OP_COMMIT, BEGIN_MS, NULL); + } + } + } + *err = ESP_OK; + } + xSemaphoreGive(s_busy); + return out; +} + esp_err_t drv_ota_register(httpd_handle_t server) { s_status_q = xQueueCreate(16, sizeof(status_t)); diff --git a/main/drv_ota.h b/main/drv_ota.h index c37b341..10e3487 100644 --- a/main/drv_ota.h +++ b/main/drv_ota.h @@ -1,5 +1,9 @@ #pragma once +#include +#include +#include +#include "cJSON.h" #include "esp_err.h" #include "esp_http_server.h" @@ -15,3 +19,9 @@ // // mac=all means every ESP-NOW device in the devices collection. One request runs at a time. esp_err_t drv_ota_register(httpd_handle_t server); + +// Send one file the same way from C (macs as above). With commit, drivers that wrote it switch to it +// and reset. Returns the per-driver results (caller owns), or NULL with *err: ESP_ERR_INVALID_STATE +// when an update is running, ESP_ERR_NOT_FOUND with no drivers, ESP_ERR_INVALID_ARG for a bad list, +// ESP_ERR_INVALID_SIZE for a file over 64 KB. +cJSON *drv_ota_send(const char *macs, const char *path, const uint8_t *data, size_t len, bool commit, esp_err_t *err); diff --git a/main/engine.c b/main/engine.c index 8bfb08b..2db8f7b 100644 --- a/main/engine.c +++ b/main/engine.c @@ -742,6 +742,29 @@ cJSON *engine_status(void) return o; } +cJSON *engine_seq_status(void) +{ + cJSON *o = cJSON_CreateObject(); + store_lock(); + for (int i = 0; i < MAX_RUNNERS; i++) { + const runner_t *r = &s_run[i]; + if (!r->used) { + continue; + } + cJSON *s = cJSON_AddObjectToObject(o, r->seq); + cJSON_AddStringToObject(s, "sequence_id", r->seq); + cJSON_AddStringToObject(s, "zone_id", r->zone); + cJSON_AddNumberToObject(s, "step_index", r->step); + cJSON_AddNumberToObject(s, "pass", r->rounds); + const cJSON *steps = steps_of(r->seq); + const cJSON *pid = cJSON_GetObjectItem(cJSON_GetArrayItem(steps, r->step), "preset_id"); + cJSON_AddItemToObject(s, "preset_id", pid ? cJSON_Duplicate(pid, false) : cJSON_CreateNull()); + cJSON_AddTrueToObject(s, "running"); + } + store_unlock(); + return o; +} + static void resume_task(void *arg) { vTaskDelay(pdMS_TO_TICKS(2000)); diff --git a/main/engine.h b/main/engine.h index bd5efa4..2ed8c40 100644 --- a/main/engine.h +++ b/main/engine.h @@ -27,6 +27,8 @@ esp_err_t engine_scene_stop(const char *scene_id); // Caller owns the result cJSON *engine_status(void); +// Running sequences: {: {sequence_id, zone_id, step_index, pass, preset_id, running}}; caller owns it +cJSON *engine_seq_status(void); // Zones or devices changed: re-send group membership to every registered ESP-NOW driver void engine_groups_changed(void); diff --git a/main/main.c b/main/main.c index 78a9871..bffb26e 100644 --- a/main/main.c +++ b/main/main.c @@ -16,6 +16,7 @@ #include "driver/spi_master.h" #include "esp_http_server.h" #include "esp_timer.h" +#include "esp_heap_caps.h" #include "esp_system.h" #include "mdns.h" #include "lwip/ip4_addr.h" @@ -28,6 +29,7 @@ #include "beat.h" #include "espnow_tx.h" #include "store.h" +#include "ws.h" #include "api.h" #include "engine.h" #include "rel.h" @@ -59,7 +61,7 @@ static esp_err_t status_get_handler(httpd_req_t *req) snprintf(ip, sizeof(ip), IPSTR, IP2STR(&ip_info.ip)); snprintf(macs, sizeof(macs), MACSTR, MAC2STR(mac)); snprintf(buf, sizeof(buf), - "{\"ip\":\"%s\",\"mac\":\"%s\",\"uptime_s\":%lld,\"free_heap\":%lu," + "{\"ip\":\"%s\",\"mac\":\"%s\",\"uptime_s\":%lld,\"free_heap\":%lu,\"free_internal\":%lu," "\"mic_rms_dbfs\":%.1f,\"mic_peak_dbfs\":%.1f,\"mic_spl_db\":%.1f," "\"bpm\":%.1f,\"beat_confidence\":%.2f,\"beat_locked\":%s,\"beats\":%lu,\"onsets\":%lu," "\"meter\":%d,\"bar_beat\":%d,\"bar_sure\":%s,\"downbeats\":%lu," @@ -67,7 +69,7 @@ static esp_err_t status_get_handler(httpd_req_t *req) "\"bulk_retries\":%lu,\"bulk_failed\":%lu,\"sim_dropped\":%lu}," "\"link\":{\"ver\":%u,\"acked\":%lu,\"ack_timeouts\":%lu,\"retransmits\":%lu,\"resyncs\":%lu,\"digests\":%lu}}", ip, macs, (long long)(esp_timer_get_time() / 1000000), (unsigned long)esp_get_free_heap_size(), - level.rms_dbfs, level.peak_dbfs, level.spl_db, + (unsigned long)heap_caps_get_free_size(MALLOC_CAP_INTERNAL), level.rms_dbfs, level.peak_dbfs, level.spl_db, bi.bpm, bi.confidence, bi.locked ? "true" : "false", (unsigned long)bi.beat_count, (unsigned long)bi.onset_count, bi.meter, bi.bar_beat, bi.bar_sure ? "true" : "false", (unsigned long)bi.downbeat_count, @@ -220,6 +222,7 @@ static void start_webserver(void) ota_register(s_server); drv_ota_register(s_server); api_register(s_server); + ws_register(s_server); ESP_LOGI(TAG, "HTTP server started on port %d", config.server_port); } diff --git a/main/outputs.c b/main/outputs.c new file mode 100644 index 0000000..828020d --- /dev/null +++ b/main/outputs.c @@ -0,0 +1,464 @@ +// Pixel outputs: the v1 app's models/output.py and controllers/output.py. Network fixtures (DDP, +// Art-Net, sACN) are reached over Ethernet; USB-DMX (dmx_serial) records are kept but this board +// has no USB-DMX adapter to drive. + +#include +#include +#include +#include +#include +#include "api_util.h" +#include "esp_mac.h" +#include "esp_timer.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "lwip/netdb.h" +#include "lwip/sockets.h" +#include "store.h" + +static const char *const PROTOCOLS[] = { "ddp", "artnet", "sacn", "dmx_serial" }; +static const char *const COLOR_ORDERS[] = { "rgb", "rbg", "grb", "gbr", "brg", "bgr" }; +static const char *const DMX_MODES[] = { "enttec_pro", "open_dmx" }; + +#define COUNT(a) (sizeof(a) / sizeof((a)[0])) +#define UNIVERSE_BYTES 510 // 170 RGB pixels per DMX universe +#define DDP_MAX_DATA 1440 + +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 cJSON *defaults(void) +{ + return cJSON_Parse("{\"name\":\"\",\"protocol\":\"ddp\",\"host\":\"\",\"port\":null,\"universe\":null,\"channel\":1," + "\"serial_port\":\"\",\"dmx_mode\":\"enttec_pro\",\"pixel_count\":60,\"pixel_offset\":0," + "\"color_order\":\"rgb\",\"reverse\":false,\"brightness\":255,\"fps\":40,\"enabled\":true}"); +} + +// Lower-cased, trimmed copy of a string field ("" when missing) +static void text(const cJSON *doc, const char *key, char *buf, size_t len, bool lower) +{ + const cJSON *v = cJSON_GetObjectItem(doc, key); + const char *s = cJSON_IsString(v) ? 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; lower && *c; c++) { + *c = tolower((unsigned char)*c); + } +} + +// Integer field in [lo, hi]; numeric strings are accepted. Writes the error into err. +static bool int_field(cJSON *doc, const char *key, int lo, int hi, bool allow_null, char *err, size_t elen) +{ + const cJSON *v = cJSON_GetObjectItem(doc, key); + if (!v || cJSON_IsNull(v) || (cJSON_IsString(v) && !v->valuestring[0])) { + if (allow_null) { + api_set(doc, key, cJSON_CreateNull()); + return true; + } + snprintf(err, elen, "%s is required", key); + return false; + } + char *end = NULL; + double d = cJSON_IsNumber(v) ? v->valuedouble : (cJSON_IsString(v) ? strtod(v->valuestring, &end) : 0.5); + if ((end && *end) || d != (long)d) { + snprintf(err, elen, "%s must be an integer", key); + return false; + } + if (d < lo || d > hi) { + snprintf(err, elen, "%s must be between %d and %d", key, lo, hi); + return false; + } + api_set(doc, key, cJSON_CreateNumber((long)d)); + return true; +} + +// Defaults, then data; returns the normalised record or NULL with err set +static cJSON *validate(const cJSON *data, char *err, size_t elen) +{ + cJSON *doc = defaults(); + api_merge(doc, data); + char buf[64]; + text(doc, "name", buf, sizeof(buf), false); + if (!buf[0]) { + snprintf(err, elen, "name is required"); + goto fail; + } + api_set(doc, "name", cJSON_CreateString(buf)); + char proto[16]; + text(doc, "protocol", proto, sizeof(proto), true); + if (!one_of(proto, PROTOCOLS, COUNT(PROTOCOLS))) { + snprintf(err, elen, "protocol must be one of: ddp, artnet, sacn, dmx_serial"); + goto fail; + } + api_set(doc, "protocol", cJSON_CreateString(proto)); + text(doc, "host", buf, sizeof(buf), false); + api_set(doc, "host", cJSON_CreateString(buf)); + if (!strcmp(proto, "ddp") && !buf[0]) { + snprintf(err, elen, "host is required for ddp"); + goto fail; + } + text(doc, "serial_port", buf, sizeof(buf), false); + api_set(doc, "serial_port", cJSON_CreateString(buf)); + bool dmx = !strcmp(proto, "dmx_serial"); + if (dmx) { + if (!buf[0]) { + snprintf(err, elen, "serial_port is required for dmx_serial"); + goto fail; + } + text(doc, "dmx_mode", buf, sizeof(buf), true); + if (!one_of(buf[0] ? buf : "enttec_pro", DMX_MODES, COUNT(DMX_MODES))) { + snprintf(err, elen, "dmx_mode must be one of: enttec_pro, open_dmx"); + goto fail; + } + api_set(doc, "dmx_mode", cJSON_CreateString(buf[0] ? buf : "enttec_pro")); + } + bool sacn = !strcmp(proto, "sacn"); + if (!int_field(doc, "port", 1, 65535, true, err, elen) || + !int_field(doc, "universe", sacn ? 1 : 0, sacn ? 63999 : 0x7FFF, true, err, elen) || + !int_field(doc, "channel", 1, 512, false, err, elen) || + !int_field(doc, "pixel_count", 1, 100000, false, err, elen) || + !int_field(doc, "pixel_offset", 0, 100000, false, err, elen) || + !int_field(doc, "brightness", 0, 255, false, err, elen) || !int_field(doc, "fps", 1, 120, false, err, elen)) { + goto fail; + } + if (dmx) { + int ch = cJSON_GetObjectItem(doc, "channel")->valueint; + int max_px = (512 - ch + 1) / 3; + if (cJSON_GetObjectItem(doc, "pixel_count")->valueint > max_px) { + snprintf(err, elen, "pixel_count must be at most %d for one DMX universe from channel %d", max_px, ch); + goto fail; + } + } + text(doc, "color_order", buf, sizeof(buf), true); + if (!one_of(buf[0] ? buf : "rgb", COLOR_ORDERS, COUNT(COLOR_ORDERS))) { + snprintf(err, elen, "color_order must be one of: rgb, rbg, grb, gbr, brg, bgr"); + goto fail; + } + api_set(doc, "color_order", cJSON_CreateString(buf[0] ? buf : "rgb")); + api_set(doc, "reverse", cJSON_CreateBool(cJSON_IsTrue(cJSON_GetObjectItem(doc, "reverse")))); + api_set(doc, "enabled", cJSON_CreateBool(!cJSON_IsFalse(cJSON_GetObjectItem(doc, "enabled")))); + return doc; +fail: + cJSON_Delete(doc); + return NULL; +} + +/* ------------------------------------------------------------ test frames */ + +typedef struct { + char name[64], proto[16], host[64], order[4]; + int port, universe, pixels, brightness, fps, id; + int sock; + struct sockaddr_in to; + uint8_t seq; + uint8_t cid[16]; + int frames, packets, bytes, errors; + char last_error[96]; +} out_t; + +static void fail(out_t *o, const char *what) +{ + o->errors++; + snprintf(o->last_error, sizeof(o->last_error), "%s: errno %d", what, errno); +} + +static bool resolve(out_t *o, int universe_for_sacn) +{ + memset(&o->to, 0, sizeof(o->to)); + o->to.sin_family = AF_INET; + o->to.sin_port = htons(o->port); + if (!o->host[0]) { + if (!strcmp(o->proto, "sacn")) { // multicast group of the universe + o->to.sin_addr.s_addr = htonl(0xEFFF0000 | (universe_for_sacn & 0xFFFF)); + } else { + o->to.sin_addr.s_addr = htonl(INADDR_BROADCAST); + } + return true; + } + if (inet_aton(o->host, &o->to.sin_addr)) { + return true; + } + struct addrinfo hints = { .ai_family = AF_INET, .ai_socktype = SOCK_DGRAM }, *res = NULL; + if (getaddrinfo(o->host, NULL, &hints, &res) != 0 || !res) { + o->errors++; + snprintf(o->last_error, sizeof(o->last_error), "cannot resolve %s", o->host); + return false; + } + o->to.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr; + freeaddrinfo(res); + return true; +} + +static void send_pkt(out_t *o, const uint8_t *pkt, size_t len) +{ + if (sendto(o->sock, pkt, len, 0, (struct sockaddr *)&o->to, sizeof(o->to)) < 0) { + fail(o, "send"); + } else { + o->packets++; + o->bytes += len; + } +} + +static void send_ddp(out_t *o, const uint8_t *data, size_t len) +{ + static uint8_t pkt[10 + DDP_MAX_DATA]; + o->seq = o->seq % 15 + 1; + for (size_t off = 0; off < len; off += DDP_MAX_DATA) { + size_t n = len - off < DDP_MAX_DATA ? len - off : DDP_MAX_DATA; + bool last = off + n >= len; + uint8_t h[10] = { 0x40 | (last ? 0x01 : 0), o->seq, 0x0B, 1, + off >> 24, off >> 16, off >> 8, off, n >> 8, n }; + memcpy(pkt, h, 10); + memcpy(pkt + 10, data + off, n); + send_pkt(o, pkt, 10 + n); + } +} + +static void send_artnet(out_t *o, const uint8_t *data, size_t len) +{ + static uint8_t pkt[18 + UNIVERSE_BYTES + 1]; + o->seq = o->seq % 255 + 1; + int base = o->universe; + for (size_t off = 0, u = 0; off < len; off += UNIVERSE_BYTES, u++) { + size_t n = len - off < UNIVERSE_BYTES ? len - off : UNIVERSE_BYTES; + size_t dl = n + (n & 1); + dl = dl < 2 ? 2 : dl; + int uni = base + u; + memcpy(pkt, "Art-Net\0", 8); + uint8_t h[10] = { 0x00, 0x50, 0, 14, o->seq, 0, uni & 0xFF, (uni >> 8) & 0x7F, dl >> 8, dl & 0xFF }; + memcpy(pkt + 8, h, 10); + memset(pkt + 18, 0, dl); + memcpy(pkt + 18, data + off, n); + send_pkt(o, pkt, 18 + dl); + } +} + +static void put16(uint8_t *p, unsigned v) +{ + p[0] = v >> 8; + p[1] = v; +} + +static void send_sacn(out_t *o, const uint8_t *data, size_t len) +{ + static uint8_t pkt[126 + UNIVERSE_BYTES]; + o->seq++; + for (size_t off = 0, u = 0; off < len; off += UNIVERSE_BYTES, u++) { + size_t n = len - off < UNIVERSE_BYTES ? len - off : UNIVERSE_BYTES; + int uni = o->universe + u; + size_t total = 126 + n; + memset(pkt, 0, 126); + put16(pkt, 0x0010); + memcpy(pkt + 4, "ASC-E1.17\0\0\0", 12); + put16(pkt + 16, 0x7000 | (total - 16)); + pkt[21] = 0x04; + memcpy(pkt + 22, o->cid, 16); + put16(pkt + 38, 0x7000 | (total - 38)); + pkt[43] = 0x02; + snprintf((char *)pkt + 44, 64, "led-controller %.48s", o->name); + pkt[108] = 100; + pkt[111] = o->seq; + put16(pkt + 113, uni); + put16(pkt + 115, 0x7000 | (total - 115)); + pkt[117] = 0x02; + pkt[118] = 0xA1; + put16(pkt + 121, 0x0001); + put16(pkt + 123, n + 1); + memcpy(pkt + 126, data + off, n); + if (!o->host[0]) { + o->to.sin_addr.s_addr = htonl(0xEFFF0000 | (uni & 0xFFFF)); + } + send_pkt(o, pkt, total); + } +} + +static void send_frame(out_t *o, const uint8_t *frame, size_t len) +{ + if (!strcmp(o->proto, "ddp")) { + send_ddp(o, frame, len); + } else if (!strcmp(o->proto, "artnet")) { + send_artnet(o, frame, len); + } else { + send_sacn(o, frame, len); + } + o->frames++; +} + +// Solid colour with the output's brightness and colour order applied +static void fill(const out_t *o, uint8_t *frame, const uint8_t rgb[3]) +{ + uint8_t c[3]; + for (int k = 0; k < 3; k++) { + int src = o->order[k] == 'r' ? 0 : o->order[k] == 'g' ? 1 : 2; + c[k] = (rgb[src] * o->brightness + 127) / 255; + } + for (int p = 0; p < o->pixels; p++) { + memcpy(frame + 3 * p, c, 3); + } +} + +static cJSON *run_test(out_t *o, double step_s) +{ + static const uint8_t STEPS[][3] = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 }, { 255, 255, 255 } }; + static const uint8_t BLACK[3] = { 0, 0, 0 }; + size_t len = (size_t)o->pixels * 3; + uint8_t *frame = malloc(len); + o->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (o->sock < 0) { + fail(o, "socket"); + } else { + int on = 1; + setsockopt(o->sock, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)); + } + if (frame && o->sock >= 0 && resolve(o, o->universe)) { + int64_t gap_us = 1000000 / o->fps; + for (size_t s = 0; s < COUNT(STEPS); s++) { + fill(o, frame, STEPS[s]); + int64_t end = esp_timer_get_time() + (int64_t)(step_s * 1e6); + do { + send_frame(o, frame, len); + TickType_t t = pdMS_TO_TICKS(gap_us / 1000); + vTaskDelay(t ? t : 1); + } while (esp_timer_get_time() < end); + } + fill(o, frame, BLACK); + send_frame(o, frame, len); + } + if (o->sock >= 0) { + close(o->sock); + } + free(frame); + cJSON *st = cJSON_CreateObject(); + cJSON_AddStringToObject(st, "name", o->name); + cJSON_AddStringToObject(st, "protocol", o->proto); + cJSON_AddStringToObject(st, "kind", "frame"); + cJSON_AddNumberToObject(st, "pixel_count", o->pixels); + cJSON_AddNumberToObject(st, "frames", o->frames); + cJSON_AddNumberToObject(st, "packets", o->packets); + cJSON_AddNumberToObject(st, "bytes", o->bytes); + cJSON_AddNumberToObject(st, "errors", o->errors); + cJSON_AddItemToObject(st, "last_error", o->last_error[0] ? cJSON_CreateString(o->last_error) : cJSON_CreateNull()); + return st; +} + +static int num(const cJSON *rec, const char *key, int dflt) +{ + const cJSON *v = cJSON_GetObjectItem(rec, key); + return cJSON_IsNumber(v) ? v->valueint : dflt; +} + +// POST /outputs//test {step_s}: solid red, green, blue and white for step_s each, then black +static esp_err_t test_output(httpd_req_t *req, const cJSON *rec, const char *id) +{ + cJSON *body = api_body_opt(req); + if (!body) { + return ESP_OK; + } + const cJSON *sv = cJSON_GetObjectItem(body, "step_s"); + double step_s = cJSON_IsNumber(sv) ? sv->valuedouble : 1.0; + step_s = step_s < 0.1 ? 0.1 : (step_s > 5 ? 5 : step_s); + cJSON_Delete(body); + + out_t *o = calloc(1, sizeof(*o)); + if (!o) { + return api_error(req, "500 Internal Server Error", "out of memory"); + } + text(rec, "name", o->name, sizeof(o->name), false); + text(rec, "protocol", o->proto, sizeof(o->proto), true); + text(rec, "host", o->host, sizeof(o->host), false); + text(rec, "color_order", o->order, sizeof(o->order), true); + if (strlen(o->order) != 3) { + strcpy(o->order, "rgb"); + } + if (!strcmp(o->proto, "dmx_serial")) { + free(o); + return api_error(req, "503 Service Unavailable", "Test failed: this board has no USB-DMX adapter"); + } + bool sacn = !strcmp(o->proto, "sacn"); + o->port = num(rec, "port", !strcmp(o->proto, "ddp") ? 4048 : sacn ? 5568 : 6454); + o->universe = num(rec, "universe", sacn ? 1 : 0); + o->pixels = num(rec, "pixel_count", 60); + o->brightness = num(rec, "brightness", 255); + o->fps = num(rec, "fps", 40); + uint8_t mac[6]; + esp_read_mac(mac, ESP_MAC_ETH); + memcpy(o->cid, mac, 6); + snprintf((char *)o->cid + 6, 10, "%.9s", id); + + store_unlock(); // frames go out for several seconds; keep the sequencer running + cJSON *st = run_test(o, step_s); + store_lock(); + free(o); + cJSON *r = cJSON_CreateObject(); + cJSON_AddStringToObject(r, "message", "Test sent"); + cJSON_AddItemToObject(r, "status", st); + return api_json(req, "200 OK", r, true); +} + +bool outputs_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) +{ + cJSON *all = store_coll("output"); + const int method = req->method; + char err[96]; + if (n == 1 && method == HTTP_POST) { + cJSON *body = api_body(req); + if (!body) { + *ret = ESP_OK; + return true; + } + cJSON *doc = validate(body, err, sizeof(err)); + cJSON_Delete(body); + if (!doc) { + *ret = api_error(req, "400 Bad Request", err); + return true; + } + char id[16]; + api_add("output", doc, id, sizeof(id)); + store_save("output"); + *ret = api_json(req, "201 Created", doc, false); + return true; + } + if (n < 2 || (method != HTTP_PUT && !(n == 3 && method == HTTP_POST))) { + return false; + } + const cJSON *rec = cJSON_GetObjectItem(all, seg[1]); + if (!rec) { + *ret = api_error(req, "404 Not Found", "Output not found"); + return true; + } + if (n == 3) { + *ret = !strcmp(seg[2], "test") ? test_output(req, rec, seg[1]) : api_error(req, "404 Not Found", "unknown action"); + return true; + } + cJSON *body = api_body(req); + if (!body) { + *ret = ESP_OK; + return true; + } + cJSON *merged = cJSON_Duplicate(rec, true); + api_merge(merged, body); + cJSON_Delete(body); + cJSON *doc = validate(merged, err, sizeof(err)); + cJSON_Delete(merged); + if (!doc) { + *ret = api_error(req, "400 Bad Request", err); + return true; + } + api_set(doc, "id", cJSON_CreateString(seg[1])); + cJSON_ReplaceItemInObject(all, seg[1], doc); + store_save("output"); + *ret = api_json(req, "200 OK", doc, false); + return true; +} diff --git a/main/patterns.c b/main/patterns.c new file mode 100644 index 0000000..398a67a --- /dev/null +++ b/main/patterns.c @@ -0,0 +1,470 @@ +// Patterns: the v1 app's controllers/pattern.py. Pattern metadata lives in the "pattern" collection, +// keyed by name. Pattern sources (.py) come from led-driver/src/patterns, embedded in the firmware +// (see tools/build_web.sh), and from uploads stored under /db/patterns, which take precedence. + +#include +#include +#include +#include +#include +#include +#include +#include "api_util.h" +#include "drv_ota.h" +#include "esp_log.h" +#include "store.h" +#include "web.h" + +static const char *TAG = "patterns"; + +#define PAT_DIR "/db/patterns" +#define CODE_MAX (64 * 1024) +#define NAME_MAX_LEN 64 + +// on and off are built into the driver firmware; there is no file to serve or send +static bool builtin(const char *name) +{ + return !strcmp(name, "on") || !strcmp(name, "off"); +} + +// "blink", "blink.py" or "blink.py.py" -> "blink"; false for anything that is not a plain file name +static bool base_name(const char *in, char out[NAME_MAX_LEN + 1]) +{ + size_t n = strlen(in); + while (n >= 3 && !strncmp(in + n - 3, ".py", 3)) { + n -= 3; + } + if (n == 0 || n > NAME_MAX_LEN) { + return false; + } + for (size_t i = 0; i < n; i++) { + char c = in[i]; + if (!(isalnum((unsigned char)c) || c == '_' || c == '-')) { + return false; + } + } + memcpy(out, in, n); + out[n] = 0; + return true; +} + +static void file_path(const char *base, char *path, size_t len) +{ + snprintf(path, len, PAT_DIR "/%s.py", base); +} + +// Pattern source: an upload, else the copy in the firmware. *heap says whether the caller frees *data. +static bool load(const char *base, const uint8_t **data, size_t *len, bool *heap) +{ + char path[96]; + file_path(base, path, sizeof(path)); + FILE *f = fopen(path, "rb"); + if (f) { + fseek(f, 0, SEEK_END); + long size = ftell(f); + fseek(f, 0, SEEK_SET); + uint8_t *buf = size >= 0 ? malloc(size + 1) : NULL; + bool ok = buf && fread(buf, 1, size, f) == (size_t)size; + fclose(f); + if (ok) { + *data = buf; + *len = size; + *heap = true; + return true; + } + free(buf); + } + char name[NAME_MAX_LEN + 16]; + snprintf(name, sizeof(name), "patterns/%s.py", base); + uint32_t n; + if (web_file(name, data, &n)) { + *len = n; + *heap = false; + return true; + } + return false; +} + +static bool exists(const char *base) +{ + const uint8_t *d; + size_t n; + bool heap; + if (!load(base, &d, &n, &heap)) { + return false; + } + if (heap) { + free((void *)d); + } + return true; +} + +static void add_name(const char *file, void *ctx) +{ + char base[NAME_MAX_LEN + 1]; + if (base_name(file, base) && strcmp(base, "__init__") && !cJSON_GetObjectItem(ctx, base)) { + cJSON_AddItemToObject(ctx, base, cJSON_CreateObject()); + } +} + +// Every pattern with a source file, as {name: {}} +static cJSON *file_names(void) +{ + cJSON *o = cJSON_CreateObject(); + web_each("patterns/", add_name, o); + DIR *dir = opendir(PAT_DIR); + struct dirent *e; + while (dir && (e = readdir(dir))) { + add_name(e->d_name, o); + } + if (dir) { + closedir(dir); + } + return o; +} + +static esp_err_t write_file(const char *base, const char *code, size_t len) +{ + if (mkdir(PAT_DIR, 0775) != 0 && errno != EEXIST) { + return ESP_FAIL; + } + char path[96]; + file_path(base, path, sizeof(path)); + FILE *f = fopen(path, "wb"); + if (!f) { + return ESP_FAIL; + } + bool ok = fwrite(code, 1, len, f) == len; + ok = fclose(f) == 0 && ok; + return ok ? ESP_OK : ESP_FAIL; +} + +// GET /patterns and /patterns/definitions: stored metadata plus {} for every other pattern file +static esp_err_t list_patterns(httpd_req_t *req) +{ + cJSON *o = cJSON_Duplicate(store_coll("pattern"), true); + cJSON *files = file_names(), *it; + cJSON_ArrayForEach(it, files) + { + if (!cJSON_GetObjectItem(o, it->string)) { + cJSON_AddItemToObject(o, it->string, cJSON_CreateObject()); + } + } + cJSON_Delete(files); + return api_json(req, "200 OK", o, true); +} + +// POST /patterns {name, data: {...}, ...}: data (plus any other keys) becomes the record under name +static esp_err_t create_pattern(httpd_req_t *req) +{ + cJSON *body = api_body(req); + if (!body) { + return ESP_OK; + } + const cJSON *name = cJSON_GetObjectItem(body, "name"); + const cJSON *data = cJSON_GetObjectItem(body, "data"); + char key[NAME_MAX_LEN + 1]; + if (cJSON_IsString(name) && name->valuestring[0]) { + snprintf(key, sizeof(key), "%s", name->valuestring); + } else { + store_next_id("pattern", key, sizeof(key)); + } + cJSON *rec = cJSON_IsObject(data) ? cJSON_Duplicate(data, true) : cJSON_CreateObject(); + cJSON_DeleteItemFromObject(body, "data"); + cJSON_DeleteItemFromObject(body, "name"); + api_merge(rec, body); + cJSON_Delete(body); + cJSON *all = store_coll("pattern"); + cJSON_DeleteItemFromObject(all, key); + cJSON_AddItemToObject(all, key, rec); + store_save("pattern"); + return api_json(req, "201 Created", rec, false); +} + +static esp_err_t serve_file(httpd_req_t *req, const char *name) +{ + char base[NAME_MAX_LEN + 1]; + if (!base_name(name, base)) { + return api_error(req, "400 Bad Request", "Invalid pattern file name"); + } + if (builtin(base)) { + return api_error(req, "400 Bad Request", "on and off are built into the driver firmware"); + } + const uint8_t *data; + size_t len; + bool heap; + if (!load(base, &data, &len, &heap)) { + return api_error(req, "404 Not Found", "Pattern file not found"); + } + httpd_resp_set_type(req, "text/plain; charset=utf-8"); + esp_err_t r = httpd_resp_send(req, (const char *)data, len); + if (heap) { + free((void *)data); + } + return r; +} + +static esp_err_t manifest(httpd_req_t *req) +{ + char host[64]; + if (httpd_req_get_hdr_value_str(req, "Host", host, sizeof(host)) != ESP_OK || !host[0]) { + return api_error(req, "400 Bad Request", "Host header required"); + } + cJSON *o = cJSON_CreateObject(), *files = cJSON_AddArrayToObject(o, "files"); + cJSON *names = file_names(), *it; + cJSON_ArrayForEach(it, names) + { + char url[192]; + cJSON *f = cJSON_CreateObject(); + snprintf(url, sizeof(url), "%s.py", it->string); + cJSON_AddStringToObject(f, "name", url); + snprintf(url, sizeof(url), "http://%s/patterns/ota/file/%s.py", host, it->string); + cJSON_AddStringToObject(f, "url", url); + cJSON_AddItemToArray(files, f); + } + cJSON_Delete(names); + return api_json(req, "200 OK", o, true); +} + +// The name and code of an upload; on error a response has been sent and false returned +static bool upload_args(httpd_req_t *req, cJSON *body, char base[NAME_MAX_LEN + 1], const char **code, bool *overwrite, + esp_err_t *ret) +{ + const cJSON *name = cJSON_GetObjectItem(body, "name"); + if (!cJSON_IsString(name)) { + name = cJSON_GetObjectItem(body, "filename"); + } + const cJSON *c = cJSON_GetObjectItem(body, "code"); + const cJSON *ow = cJSON_GetObjectItem(body, "overwrite"); + const char *err = !cJSON_IsString(name) || !base_name(name->valuestring, base) ? "a valid name is required" + : builtin(base) ? "on and off are built into the driver firmware" + : !cJSON_IsString(c) || !c->valuestring[0] ? "code is required" + : strlen(c->valuestring) > CODE_MAX ? "code must be at most 64 KB" + : NULL; + if (err) { + *ret = api_error(req, "400 Bad Request", err); + return false; + } + *code = c->valuestring; + *overwrite = !cJSON_IsFalse(ow); + if (!*overwrite && exists(base)) { + *ret = api_error(req, "409 Conflict", "Pattern already exists"); + return false; + } + return true; +} + +// POST /patterns/upload {name, code, overwrite}: store a pattern source +static esp_err_t upload(httpd_req_t *req) +{ + cJSON *body = api_body(req); + if (!body) { + return ESP_OK; + } + char base[NAME_MAX_LEN + 1]; + const char *code; + bool overwrite; + esp_err_t ret; + if (!upload_args(req, body, base, &code, &overwrite, &ret)) { + cJSON_Delete(body); + return ret; + } + bool had = exists(base); + if (write_file(base, code, strlen(code)) != ESP_OK) { + cJSON_Delete(body); + return api_error(req, "500 Internal Server Error", "could not save the pattern"); + } + cJSON_Delete(body); + char fname[NAME_MAX_LEN + 4]; + snprintf(fname, sizeof(fname), "%s.py", base); + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "message", "Pattern uploaded"); + cJSON_AddStringToObject(o, "name", fname); + cJSON_AddBoolToObject(o, "overwrote", had); + return api_json(req, "201 Created", o, true); +} + +// POST /patterns/driver {name, code, overwrite, min_delay, max_delay, max_colors, n1..n8}: store the +// source and its metadata (n1..n8 are the parameter labels) +static esp_err_t create_driver_pattern(httpd_req_t *req) +{ + cJSON *body = api_body(req); + if (!body) { + return ESP_OK; + } + char base[NAME_MAX_LEN + 1]; + const char *code; + bool overwrite; + esp_err_t ret; + if (!upload_args(req, body, base, &code, &overwrite, &ret)) { + cJSON_Delete(body); + return ret; + } + if (!isalpha((unsigned char)base[0]) && base[0] != '_') { + cJSON_Delete(body); + return api_error(req, "400 Bad Request", "name must start with a letter or _"); + } + for (const char *c = base; *c; c++) { + if (*c == '-') { + cJSON_Delete(body); + return api_error(req, "400 Bad Request", "name may only hold letters, digits and _"); + } + } + cJSON *meta = cJSON_CreateObject(); + static const char *const INTS[] = { "min_delay", "max_delay", "max_colors" }; + for (size_t i = 0; i < sizeof(INTS) / sizeof(INTS[0]); i++) { + const cJSON *v = cJSON_GetObjectItem(body, INTS[i]); + if (!v || cJSON_IsNull(v) || (cJSON_IsString(v) && !v->valuestring[0])) { + continue; + } + double d = cJSON_IsNumber(v) ? v->valuedouble : (cJSON_IsString(v) ? strtod(v->valuestring, NULL) : 0.5); + if (d != (int)d) { + cJSON_Delete(meta); + cJSON_Delete(body); + return api_error(req, "400 Bad Request", "min_delay, max_delay and max_colors must be integers"); + } + cJSON_AddNumberToObject(meta, INTS[i], (int)d); + } + for (int i = 1; i <= 8; i++) { + char key[4]; + snprintf(key, sizeof(key), "n%d", i); + const cJSON *v = cJSON_GetObjectItem(body, key); + if (cJSON_IsString(v) && v->valuestring[0]) { + cJSON_AddStringToObject(meta, key, v->valuestring); + } + } + if (write_file(base, code, strlen(code)) != ESP_OK) { + cJSON_Delete(meta); + cJSON_Delete(body); + return api_error(req, "500 Internal Server Error", "could not save the pattern"); + } + cJSON_Delete(body); + cJSON *all = store_coll("pattern"); + cJSON *rec = cJSON_GetObjectItem(all, base); + if (!cJSON_IsObject(rec)) { + cJSON_DeleteItemFromObject(all, base); + rec = cJSON_AddObjectToObject(all, base); + } + api_merge(rec, meta); + store_save("pattern"); + char fname[NAME_MAX_LEN + 4]; + snprintf(fname, sizeof(fname), "%s.py", base); + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "message", "Pattern created"); + cJSON_AddStringToObject(o, "name", base); + cJSON_AddStringToObject(o, "file", fname); + cJSON_AddItemToObject(o, "metadata", meta); + return api_json(req, "201 Created", o, true); +} + +// POST /patterns//send {device_id?}: push the source to one driver or every ESP-NOW driver +// (patterns/.py on the driver), which then resets to load it +static esp_err_t send_pattern(httpd_req_t *req, const char *name) +{ + char base[NAME_MAX_LEN + 1]; + if (!base_name(name, base)) { + return api_error(req, "400 Bad Request", "Invalid pattern name"); + } + if (builtin(base)) { + return api_error(req, "400 Bad Request", "on and off are built into the driver firmware"); + } + cJSON *body = api_body_opt(req); + if (!body) { + return ESP_OK; + } + char macs[16] = "all"; + const cJSON *did = cJSON_GetObjectItem(body, "device_id"); + if (cJSON_IsString(did) && did->valuestring[0]) { + const cJSON *dev = cJSON_GetObjectItem(store_coll("device"), did->valuestring); + const cJSON *tr = cJSON_GetObjectItem(dev, "transport"), *addr = cJSON_GetObjectItem(dev, "address"); + if (!dev) { + cJSON_Delete(body); + return api_error(req, "404 Not Found", "Device not found"); + } + if (!cJSON_IsString(tr) || strcmp(tr->valuestring, "espnow") || !cJSON_IsString(addr) || + strlen(addr->valuestring) != 12) { + cJSON_Delete(body); + return api_error(req, "400 Bad Request", "Device is not an ESP-NOW driver"); + } + snprintf(macs, sizeof(macs), "%s", addr->valuestring); + } + cJSON_Delete(body); + const uint8_t *data; + size_t len; + bool heap; + if (!load(base, &data, &len, &heap)) { + return api_error(req, "404 Not Found", "Pattern file not found"); + } + char path[NAME_MAX_LEN + 16]; + snprintf(path, sizeof(path), "patterns/%s.py", base); + esp_err_t err; + store_unlock(); // the transfer takes seconds; the sequencer must keep running + cJSON *results = drv_ota_send(macs, path, data, len, true, &err); + store_lock(); + if (heap) { + free((void *)data); + } + if (!results) { + return err == ESP_ERR_INVALID_STATE ? api_error(req, "409 Conflict", "a driver update is already running") + : err == ESP_ERR_NOT_FOUND ? api_error(req, "404 Not Found", "No ESP-NOW drivers") + : api_error(req, "400 Bad Request", "Pattern cannot be sent"); + } + cJSON *o = cJSON_CreateObject(), *ids = cJSON_CreateArray(), *it; + cJSON_ArrayForEach(it, results) + { + const cJSON *res = cJSON_GetObjectItem(it, "result"); + if (cJSON_IsString(res) && strcmp(res->valuestring, "error")) { + cJSON_AddItemToArray(ids, cJSON_CreateString(it->string)); + } + } + int sent = cJSON_GetArraySize(ids); + ESP_LOGI(TAG, "%s sent to %d driver(s)", path, sent); + cJSON_AddStringToObject(o, sent ? "message" : "error", sent ? "Pattern sent" : "No driver accepted the pattern"); + cJSON_AddStringToObject(o, "pattern", path + strlen("patterns/")); + cJSON_AddItemToObject(o, "device_ids", ids); + cJSON_AddNumberToObject(o, "sent_count", sent); + cJSON_AddItemToObject(o, "results", results); + return api_json(req, sent ? "200 OK" : "503 Service Unavailable", o, true); +} + +bool patterns_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) +{ + static const char FILE_PREFIX[] = "/patterns/ota/file/"; + const int method = req->method; + if (method == HTTP_GET && !strncmp(req->uri, FILE_PREFIX, sizeof(FILE_PREFIX) - 1)) { + char name[NAME_MAX_LEN + 8]; + const char *s = req->uri + sizeof(FILE_PREFIX) - 1; + size_t len = strcspn(s, "?"); + if (len >= sizeof(name)) { + *ret = api_error(req, "400 Bad Request", "Invalid pattern file name"); + return true; + } + memcpy(name, s, len); + name[len] = 0; + *ret = serve_file(req, name); + return true; + } + if (n == 3 && method == HTTP_GET && !strcmp(seg[1], "ota") && !strcmp(seg[2], "manifest")) { + *ret = manifest(req); + return true; + } + if (method == HTTP_GET && (n == 1 || (n == 2 && !strcmp(seg[1], "definitions")))) { + *ret = list_patterns(req); + return true; + } + if (method != HTTP_POST) { + return false; + } + if (n == 1) { + *ret = create_pattern(req); + } else if (n == 2 && !strcmp(seg[1], "upload")) { + *ret = upload(req); + } else if (n == 2 && !strcmp(seg[1], "driver")) { + *ret = create_driver_pattern(req); + } else if (n == 3 && !strcmp(seg[2], "send")) { + *ret = send_pattern(req, seg[1]); + } else { + return false; + } + return true; +} diff --git a/main/res_device.c b/main/res_device.c new file mode 100644 index 0000000..e8ff50c --- /dev/null +++ b/main/res_device.c @@ -0,0 +1,372 @@ +// 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; + } +} diff --git a/main/res_misc.c b/main/res_misc.c new file mode 100644 index 0000000..b8e3269 --- /dev/null +++ b/main/res_misc.c @@ -0,0 +1,252 @@ +// Palettes and sequences: the v1 app's controllers/palette.py and sequence.py + +#include +#include +#include +#include "api_util.h" +#include "engine.h" +#include "store.h" + +/* --------------------------------------------------------------- palettes */ + +// A palette is stored as a bare list of colours; older records hold {"colors": [...]} +static const cJSON *palette_colors(const cJSON *rec) +{ + if (cJSON_IsObject(rec)) { + rec = cJSON_GetObjectItem(rec, "colors"); + } + return cJSON_IsArray(rec) ? rec : NULL; +} + +static cJSON *palette_reply(const char *id, const cJSON *rec) +{ + const cJSON *colors = palette_colors(rec); + cJSON *o = cJSON_CreateObject(); + cJSON_AddItemToObject(o, "colors", colors ? cJSON_Duplicate(colors, true) : cJSON_CreateArray()); + cJSON_AddStringToObject(o, "id", id); + return o; +} + +// Colours from {"colors": [...]}; anything else is an empty list +static cJSON *colors_from(const cJSON *body) +{ + const cJSON *c = cJSON_GetObjectItem(body, "colors"); + return cJSON_IsArray(c) ? cJSON_Duplicate(c, true) : cJSON_CreateArray(); +} + +bool palettes_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) +{ + cJSON *all = store_coll("palette"); + const int method = req->method; + if (n == 1 && method == HTTP_GET) { + cJSON *o = cJSON_CreateObject(), *it; + cJSON_ArrayForEach(it, all) + { + const cJSON *colors = palette_colors(it); + cJSON_AddItemToObject(o, it->string, colors ? cJSON_Duplicate(colors, true) : cJSON_CreateArray()); + } + *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; + } + cJSON *colors = colors_from(body); + cJSON_Delete(body); + char id[16]; + api_add("palette", colors, id, sizeof(id)); + store_save("palette"); + *ret = api_json(req, "201 Created", palette_reply(id, colors), true); + return true; + } + if (n != 2 || (method != HTTP_GET && method != HTTP_PUT)) { + return false; + } + cJSON *rec = cJSON_GetObjectItem(all, seg[1]); + if (!rec) { + *ret = api_error(req, "404 Not Found", "Palette not found"); + return true; + } + if (method == HTTP_PUT) { + cJSON *body = api_body(req); + if (!body) { + *ret = ESP_OK; + return true; + } + rec = colors_from(body); + cJSON_Delete(body); + cJSON_ReplaceItemInObject(all, seg[1], rec); + store_save("palette"); + } + *ret = api_json(req, "200 OK", palette_reply(seg[1], rec), true); + return true; +} + +/* -------------------------------------------------------------- sequences */ + +#define DURATION_MIN_S 0.5 +#define DURATION_MAX_S 600.0 +#define DURATION_DEFAULT_S 5.0 + +static bool truthy(const cJSON *v, bool dflt) +{ + if (!v || cJSON_IsNull(v)) { + return dflt; + } + if (cJSON_IsString(v)) { + return v->valuestring[0] != 0; + } + return cJSON_IsTrue(v) || (cJSON_IsNumber(v) && v->valuedouble != 0); +} + +// Bring a sequence record into shape: {name, zone_id, loop, repeat_count, steps: [{preset_id, +// duration_s}], active}. Returns an error message, or NULL when doc is valid. +static const char *normalize_seq(cJSON *doc) +{ + char buf[64]; + const cJSON *name = cJSON_GetObjectItem(doc, "name"); + const char *s = cJSON_IsString(name) ? 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; + } + api_set(doc, "name", cJSON_CreateString(buf)); + + api_set(doc, "zone_id", api_id(cJSON_GetObjectItem(doc, "zone_id"), buf, sizeof(buf)) ? cJSON_CreateString(buf) + : cJSON_CreateNull()); + api_set(doc, "loop", cJSON_CreateBool(truthy(cJSON_GetObjectItem(doc, "loop"), true))); + + const cJSON *rc = cJSON_GetObjectItem(doc, "repeat_count"); + int repeat = 0; + if (cJSON_IsNumber(rc)) { + repeat = (int)rc->valuedouble; + } else if (rc && !cJSON_IsNull(rc) && !cJSON_IsFalse(rc)) { + return "repeat_count must be an integer"; + } + api_set(doc, "repeat_count", cJSON_CreateNumber(repeat < 0 ? 0 : repeat)); + + const cJSON *steps = cJSON_GetObjectItem(doc, "steps"); + if (steps && !cJSON_IsNull(steps) && !cJSON_IsArray(steps)) { + return "steps must be a list"; + } + cJSON *out = cJSON_CreateArray(); + const cJSON *st; + cJSON_ArrayForEach(st, steps) + { + const cJSON *pid = cJSON_IsObject(st) ? cJSON_GetObjectItem(st, "preset_id") : st; + if (!api_id(pid, buf, sizeof(buf))) { + cJSON_Delete(out); + return "each step needs a preset_id"; + } + const cJSON *dv = cJSON_IsObject(st) ? cJSON_GetObjectItem(st, "duration_s") : NULL; + double d = cJSON_IsNumber(dv) ? dv->valuedouble : DURATION_DEFAULT_S; + d = d < DURATION_MIN_S ? DURATION_MIN_S : (d > DURATION_MAX_S ? DURATION_MAX_S : d); + cJSON *step = cJSON_CreateObject(); + cJSON_AddStringToObject(step, "preset_id", buf); + cJSON_AddNumberToObject(step, "duration_s", d); + cJSON_AddItemToArray(out, step); + } + api_set(doc, "steps", out); + api_set(doc, "active", cJSON_CreateBool(truthy(cJSON_GetObjectItem(doc, "active"), false))); + return NULL; +} + +static esp_err_t play_sequence(httpd_req_t *req, const char *id) +{ + const cJSON *rec = cJSON_GetObjectItem(store_coll("sequence"), id); + if (!rec) { + return api_error(req, "404 Not Found", "Sequence not found"); + } + char zone[24]; + if (!api_id(cJSON_GetObjectItem(rec, "zone_id"), zone, sizeof(zone))) { + return api_error(req, "400 Bad Request", "Sequence has no zone_id"); + } + if (!cJSON_GetArraySize(cJSON_GetObjectItem(rec, "steps"))) { + return api_error(req, "400 Bad Request", "Sequence has no steps"); + } + if (!cJSON_GetObjectItem(store_coll("zone"), zone)) { + return api_error(req, "404 Not Found", "Zone not found"); + } + esp_err_t err = engine_seq_play(id); + if (err == ESP_ERR_NO_MEM) { + return api_error(req, "503 Service Unavailable", "too many sequences running"); + } + if (err != ESP_OK) { + return api_result(req, err, ""); + } + cJSON *all = engine_seq_status(); + cJSON *state = cJSON_DetachItemFromObject(all, id); + cJSON_Delete(all); + return api_json(req, "200 OK", state ? state : cJSON_CreateObject(), true); +} + +bool sequences_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) +{ + cJSON *all = store_coll("sequence"); + const int method = req->method; + if (n == 2 && method == HTTP_GET && !strcmp(seg[1], "status")) { + *ret = api_json(req, "200 OK", engine_seq_status(), true); + return true; + } + if (n == 3 && method == HTTP_POST && !strcmp(seg[2], "play")) { + *ret = play_sequence(req, seg[1]); + return true; + } + if (n == 3 && method == HTTP_POST && !strcmp(seg[2], "stop")) { + bool stopped = engine_seq_stop(seg[1]) == ESP_OK; + cJSON *o = cJSON_CreateObject(); + cJSON_AddBoolToObject(o, "stopped", stopped); + *ret = api_json(req, "200 OK", o, true); + return true; + } + if ((n == 1 && method == HTTP_POST) || (n == 2 && method == HTTP_PUT)) { + cJSON *old = n == 2 ? cJSON_GetObjectItem(all, seg[1]) : NULL; + if (n == 2 && !old) { + *ret = api_error(req, "404 Not Found", "Sequence not found"); + return true; + } + cJSON *body = api_body(req); + if (!body) { + *ret = ESP_OK; + return true; + } + cJSON *doc = old ? cJSON_Duplicate(old, true) : cJSON_CreateObject(); + api_merge(doc, body); + cJSON_Delete(body); + const char *bad = normalize_seq(doc); + if (bad) { + cJSON_Delete(doc); + *ret = api_error(req, "400 Bad Request", bad); + return true; + } + char id[16]; + if (old) { + snprintf(id, sizeof(id), "%s", seg[1]); + api_set(doc, "id", cJSON_CreateString(id)); + cJSON_ReplaceItemInObject(all, id, doc); + } else { + api_add("sequence", doc, id, sizeof(id)); + } + store_save("sequence"); + *ret = api_json(req, old ? "200 OK" : "201 Created", doc, false); + return true; + } + if (n == 2 && method == HTTP_DELETE) { + if (!cJSON_GetObjectItem(all, seg[1])) { + *ret = api_error(req, "404 Not Found", "Sequence not found"); + return true; + } + engine_seq_stop(seg[1]); + cJSON_DeleteItemFromObject(all, seg[1]); + store_save("sequence"); + *ret = api_message(req, "200 OK", "Sequence deleted successfully"); + return true; + } + return false; +} diff --git a/main/res_profile.c b/main/res_profile.c new file mode 100644 index 0000000..30afdc6 --- /dev/null +++ b/main/res_profile.c @@ -0,0 +1,787 @@ +// Profiles, zones and presets: the v1 app's controllers/profile.py, zone.py and preset.py + +#include +#include +#include +#include "api_util.h" +#include "engine.h" +#include "store.h" +#include "web.h" + +/* ---------------------------------------------------------------- presets */ + +// A new preset before the request's fields are applied +static cJSON *preset_defaults(const char *profile_id) +{ + cJSON *p = cJSON_CreateObject(); + cJSON_AddStringToObject(p, "name", ""); + cJSON_AddStringToObject(p, "pattern", ""); + cJSON_AddArrayToObject(p, "colors"); + cJSON_AddNumberToObject(p, "brightness", 0); + cJSON_AddNumberToObject(p, "delay", 0); + for (int i = 1; i <= 8; i++) { + char k[4]; + snprintf(k, sizeof(k), "n%d", i); + cJSON_AddNumberToObject(p, k, 0); + } + cJSON_AddStringToObject(p, "profile_id", profile_id); + return p; +} + +static esp_err_t send_keyed(httpd_req_t *req, const char *status, const char *id, cJSON *rec) +{ + cJSON *o = cJSON_CreateObject(); + cJSON_AddItemReferenceToObject(o, id, rec); + return api_json(req, status, o, true); +} + +static esp_err_t push_presets(httpd_req_t *req) +{ + cJSON *body = api_body(req); + if (!body) { + return ESP_OK; + } + const cJSON *seq = cJSON_GetObjectItem(body, "sequence"); + const cJSON *payload = cJSON_GetObjectItem(body, "payload"); + cJSON *one = NULL; + if (!cJSON_IsArray(seq) && payload) { + one = cJSON_CreateArray(); + cJSON_AddItemReferenceToArray(one, (cJSON *)payload); + seq = one; + } + esp_err_t err = ESP_ERR_INVALID_ARG; + if (cJSON_IsArray(seq) && cJSON_GetArraySize(seq)) { + err = engine_push(seq, cJSON_GetObjectItem(body, "targets")); + } + cJSON_Delete(one); + cJSON_Delete(body); + return err == ESP_ERR_INVALID_ARG ? api_error(req, "400 Bad Request", "sequence or payload required") + : api_result(req, err, "Delivered"); +} + +static esp_err_t send_presets(httpd_req_t *req) +{ + cJSON *body = api_body(req); + if (!body) { + return ESP_OK; + } + const cJSON *ids = cJSON_GetObjectItem(body, "preset_ids"); + if (!cJSON_IsArray(ids)) { + ids = cJSON_GetObjectItem(body, "ids"); + } + if (!cJSON_IsArray(ids) || !cJSON_GetArraySize(ids)) { + cJSON_Delete(body); + return api_error(req, "400 Bad Request", "preset_ids must be a non-empty list"); + } + const cJSON *save = cJSON_GetObjectItem(body, "save"); + char def[24]; + api_id(cJSON_GetObjectItem(body, "default"), def, sizeof(def)); + const cJSON *targets = cJSON_GetObjectItem(body, "targets"); + cJSON *single = NULL; + const cJSON *dest = cJSON_GetObjectItem(body, "destination_mac"); + if (!cJSON_IsArray(targets) && cJSON_IsString(dest)) { + single = cJSON_CreateArray(); + cJSON_AddItemToArray(single, cJSON_CreateString(dest->valuestring)); + targets = single; + } + int sent = 0; + esp_err_t err = engine_send_presets(ids, !save || cJSON_IsTrue(save), def[0] ? def : NULL, targets, &sent); + cJSON_Delete(single); + cJSON_Delete(body); + if (err != ESP_OK) { + return api_result(req, err, ""); + } + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "message", "Presets sent"); + cJSON_AddNumberToObject(o, "presets_sent", sent); + return api_json(req, "200 OK", o, true); +} + +bool presets_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_POST && !strcmp(seg[1], "push")) { + *ret = push_presets(req); + return true; + } + if (n == 2 && method == HTTP_POST && !strcmp(seg[1], "send")) { + *ret = send_presets(req); + return true; + } + const char *profile = api_current_profile(); + if (n == 1 && method == HTTP_POST) { + if (!profile) { + *ret = api_error(req, "404 Not Found", "No profile available"); + return true; + } + cJSON *body = api_body(req); + if (!body) { + *ret = ESP_OK; + return true; + } + cJSON *rec = preset_defaults(profile); + api_merge(rec, body); + cJSON_Delete(body); + api_set(rec, "profile_id", cJSON_CreateString(profile)); + char id[16]; + api_add("preset", rec, id, sizeof(id)); + store_save("preset"); + *ret = send_keyed(req, "201 Created", id, rec); + return true; + } + if (n == 2 && method == HTTP_PUT) { + cJSON *rec = cJSON_GetObjectItem(store_coll("preset"), seg[1]); + if (!rec || !api_preset_in_profile(rec)) { + *ret = api_error(req, "404 Not Found", "Preset not found"); + return true; + } + cJSON *body = api_body(req); + if (!body) { + *ret = ESP_OK; + return true; + } + api_merge(rec, body); + cJSON_Delete(body); + if (profile) { + api_set(rec, "profile_id", cJSON_CreateString(profile)); + } + store_save("preset"); + *ret = api_json(req, "200 OK", rec, false); + return true; + } + return false; +} + +/* --------------------------------------------------------------- profiles */ + +typedef struct { + const char *name, *pattern, *colors; + int brightness, delay; + int n[4]; // n1..n4 +} seed_t; + +static const seed_t SEED[] = { + { "on", "on", "[\"#FFFFFF\"]", 255, 100, { 0 } }, + { "off", "off", "[]", 0, 100, { 0 } }, + { "rainbow", "rainbow", "[]", 255, 100, { 2 } }, + { "Colour Cycle", "colour_cycle", "[\"#FF0000\",\"#00FF00\",\"#0000FF\"]", 255, 100, { 1 } }, + { "transition", "transition", "[\"#FF0000\",\"#00FF00\",\"#0000FF\"]", 255, 500, { 0 } }, + { "flicker", "flicker", "[\"#FFB84D\"]", 255, 80, { 30 } }, + { "flame", "flame", "[]", 255, 50, { 35, 2600 } }, + { "twinkle", "twinkle", "[\"#78C8FF\",\"#508CFF\",\"#B478FF\",\"#64DCE8\",\"#A0C8FF\"]", 255, 55, { 72, 140, 2, 6 } }, +}; +static const seed_t SEED_DJ[] = { + { "DJ Rainbow", "rainbow", "[]", 220, 60, { 12 } }, + { "DJ Single Color", "on", "[\"#ff00ff\"]", 220, 100, { 0 } }, + { "DJ Transition", "transition", "[\"#ff0000\",\"#00ff00\",\"#0000ff\"]", 220, 250, { 0 } }, +}; + +// Create the seed presets and a zone that lists them; returns the zone id in zid +static void seed_zone(const char *profile, const char *zone_name, const char *driver_name, bool with_auto, + const seed_t *seed, int count, char *zid, size_t zlen) +{ + cJSON *flat = cJSON_CreateArray(); + for (int i = 0; i < count; i++) { + cJSON *p = preset_defaults(profile); + api_set(p, "name", cJSON_CreateString(seed[i].name)); + api_set(p, "pattern", cJSON_CreateString(seed[i].pattern)); + api_set(p, "colors", cJSON_Parse(seed[i].colors)); + api_set(p, "brightness", cJSON_CreateNumber(seed[i].brightness)); + api_set(p, "delay", cJSON_CreateNumber(seed[i].delay)); + for (int k = 0; k < 4; k++) { + char key[4]; + snprintf(key, sizeof(key), "n%d", k + 1); + api_set(p, key, cJSON_CreateNumber(seed[i].n[k])); + } + if (with_auto) { + cJSON_AddTrueToObject(p, "auto"); + } + char pid[16]; + api_add("preset", p, pid, sizeof(pid)); + cJSON_AddItemToArray(flat, cJSON_CreateString(pid)); + } + cJSON *z = cJSON_CreateObject(); + cJSON_AddStringToObject(z, "name", zone_name); + cJSON *names = cJSON_AddArrayToObject(z, "names"); + cJSON_AddItemToArray(names, cJSON_CreateString(driver_name)); + cJSON *rows = cJSON_AddArrayToObject(z, "presets"); + cJSON_AddItemToArray(rows, cJSON_Duplicate(flat, true)); + cJSON_AddItemToObject(z, "presets_flat", flat); + cJSON *first = cJSON_GetArrayItem(flat, 0); + cJSON_AddItemToObject(z, "default_preset", first ? cJSON_Duplicate(first, false) : cJSON_CreateNull()); + api_add("zone", z, zid, zlen); +} + +static bool truthy(const cJSON *v) +{ + if (cJSON_IsString(v)) { + const char *s = v->valuestring; + return !strcasecmp(s, "1") || !strcasecmp(s, "true") || !strcasecmp(s, "yes") || !strcasecmp(s, "on"); + } + return cJSON_IsTrue(v) || (cJSON_IsNumber(v) && v->valuedouble != 0); +} + +// POST /profiles: the profile, an empty palette, the seed presets and a "default" zone (plus a "dj" +// zone with seed_dj_zone) +static esp_err_t create_profile(httpd_req_t *req) +{ + cJSON *body = api_body(req); + if (!body) { + return ESP_OK; + } + bool dj = truthy(cJSON_GetObjectItem(body, "seed_dj_zone")); + cJSON_DeleteItemFromObject(body, "seed_dj_zone"); + + char palid[16], pid[16], zid[16], djid[16]; + api_add("palette", cJSON_CreateArray(), palid, sizeof(palid)); + cJSON *prof = cJSON_CreateObject(); + cJSON_AddStringToObject(prof, "name", ""); + cJSON_AddStringToObject(prof, "type", "zones"); + cJSON_AddArrayToObject(prof, "zones"); + cJSON_AddArrayToObject(prof, "scenes"); + api_merge(prof, body); + cJSON_Delete(body); + api_set(prof, "palette_id", cJSON_CreateString(palid)); + api_add("profile", prof, pid, sizeof(pid)); + + cJSON *zones = cJSON_CreateArray(); + seed_zone(pid, "default", "1", true, SEED, sizeof(SEED) / sizeof(SEED[0]), zid, sizeof(zid)); + cJSON_AddItemToArray(zones, cJSON_CreateString(zid)); + if (dj) { + seed_zone(pid, "dj", "dj", false, SEED_DJ, sizeof(SEED_DJ) / sizeof(SEED_DJ[0]), djid, sizeof(djid)); + cJSON_AddItemToArray(zones, cJSON_CreateString(djid)); + } + api_set(prof, "zones", zones); + store_save("palette"); + store_save("preset"); + store_save("zone"); + store_save("profile"); + engine_groups_changed(); + return send_keyed(req, "201 Created", pid, prof); +} + +static const cJSON *profile_zones(const cJSON *prof) +{ + const cJSON *z = cJSON_GetObjectItem(prof, "zones"); + if (!cJSON_IsArray(z)) { + z = cJSON_GetObjectItem(prof, "zone_order"); + } + return cJSON_IsArray(z) ? z : NULL; +} + +// Copy of a preset reference list (ids, possibly nested in rows) with ids mapped through map +static cJSON *remap(const cJSON *v, const cJSON *map) +{ + if (cJSON_IsArray(v)) { + cJSON *out = cJSON_CreateArray(); + const cJSON *it; + cJSON_ArrayForEach(it, v) + { + cJSON_AddItemToArray(out, remap(it, map)); + } + return out; + } + char id[24]; + const cJSON *to = api_id(v, id, sizeof(id)) ? cJSON_GetObjectItem(map, id) : NULL; + return to ? cJSON_Duplicate(to, false) : cJSON_Duplicate(v, true); +} + +// POST /profiles//clone: the profile with its own copies of its palette, zones and presets +static esp_err_t clone_profile(httpd_req_t *req, const char *src_id) +{ + cJSON *src = cJSON_GetObjectItem(store_coll("profile"), src_id); + if (!src) { + return api_error(req, "404 Not Found", "Profile not found"); + } + cJSON *body = api_body_opt(req); + if (!body) { + return ESP_OK; + } + const cJSON *name = cJSON_GetObjectItem(body, "name"); + cJSON *prof = cJSON_Duplicate(src, true); + if (cJSON_IsString(name) && name->valuestring[0]) { + api_set(prof, "name", cJSON_CreateString(name->valuestring)); + } + cJSON_Delete(body); + char pid[16], id[16]; + api_add("profile", prof, pid, sizeof(pid)); + + char palsrc[24]; + const cJSON *pal = api_id(cJSON_GetObjectItem(src, "palette_id"), palsrc, sizeof(palsrc)) + ? cJSON_GetObjectItem(store_coll("palette"), palsrc) + : NULL; + if (cJSON_IsObject(pal)) { // legacy {"colors": [...]} + pal = cJSON_GetObjectItem(pal, "colors"); + } + api_add("palette", cJSON_IsArray(pal) ? cJSON_Duplicate(pal, true) : cJSON_CreateArray(), id, sizeof(id)); + api_set(prof, "palette_id", cJSON_CreateString(id)); + + // Every preset of the source profile gets a copy owned by the clone + cJSON *map = cJSON_CreateObject(); + cJSON *presets = store_coll("preset"); + cJSON *ids = cJSON_CreateArray(), *it; + cJSON_ArrayForEach(it, presets) + { + char owner[24]; + if (api_id(cJSON_GetObjectItem(it, "profile_id"), owner, sizeof(owner)) && !strcmp(owner, src_id)) { + cJSON_AddItemToArray(ids, cJSON_CreateString(it->string)); + } + } + cJSON_ArrayForEach(it, ids) + { + cJSON *copy = cJSON_Duplicate(cJSON_GetObjectItem(presets, it->valuestring), true); + api_set(copy, "profile_id", cJSON_CreateString(pid)); + api_add("preset", copy, id, sizeof(id)); + cJSON_AddStringToObject(map, it->valuestring, id); + } + cJSON_Delete(ids); + + cJSON *zones = cJSON_CreateArray(); + const cJSON *zid; + cJSON_ArrayForEach(zid, profile_zones(src)) + { + char key[24]; + cJSON *z = api_id(zid, key, sizeof(key)) ? cJSON_GetObjectItem(store_coll("zone"), key) : NULL; + if (!z) { + continue; + } + cJSON *copy = cJSON_Duplicate(z, true); + static const char *const REFS[] = { "presets", "presets_flat", "default_preset" }; + for (size_t i = 0; i < sizeof(REFS) / sizeof(REFS[0]); i++) { + const cJSON *v = cJSON_GetObjectItem(z, REFS[i]); + if (v && !cJSON_IsNull(v)) { + api_set(copy, REFS[i], remap(v, map)); + } + } + api_add("zone", copy, id, sizeof(id)); + cJSON_AddItemToArray(zones, cJSON_CreateString(id)); + } + cJSON_Delete(map); + api_set(prof, "zones", zones); + cJSON_DeleteItemFromObject(prof, "zone_order"); + store_save("palette"); + store_save("preset"); + store_save("zone"); + store_save("profile"); + engine_groups_changed(); + return send_keyed(req, "201 Created", pid, prof); +} + +// Is id listed by any profile other than skip under key (a list, or a single value)? +static bool used_elsewhere(const char *skip, const char *key, const char *id) +{ + const cJSON *p; + cJSON_ArrayForEach(p, store_coll("profile")) + { + if (!strcmp(p->string, skip)) { + continue; + } + const cJSON *v = cJSON_GetObjectItem(p, key), *it; + char buf[24]; + if (!cJSON_IsArray(v)) { + if (api_id(v, buf, sizeof(buf)) && !strcmp(buf, id)) { + return true; + } + continue; + } + cJSON_ArrayForEach(it, v) + { + if (api_id(it, buf, sizeof(buf)) && !strcmp(buf, id)) { + return true; + } + } + } + return false; +} + +// DELETE /profiles/: the profile with its presets, and its zones and palette unless another profile +// uses them. Ids are reused (next id = highest + 1), so leftovers would turn up in the next new profile. +static esp_err_t delete_profile(httpd_req_t *req, const char *id) +{ + char pid[24]; + snprintf(pid, sizeof(pid), "%s", id); + cJSON *prof = cJSON_GetObjectItem(store_coll("profile"), pid); + if (!prof) { + return api_error(req, "404 Not Found", "Profile not found"); + } + cJSON *presets = store_coll("preset"), *it = presets->child; + while (it) { + cJSON *next = it->next; + char owner[24]; + if (api_id(cJSON_GetObjectItem(it, "profile_id"), owner, sizeof(owner)) && !strcmp(owner, pid)) { + cJSON_Delete(cJSON_DetachItemViaPointer(presets, it)); + } + it = next; + } + const cJSON *z; + cJSON_ArrayForEach(z, profile_zones(prof)) + { + char zid[24]; + if (api_id(z, zid, sizeof(zid)) && !used_elsewhere(pid, "zones", zid) && !used_elsewhere(pid, "zone_order", zid)) { + cJSON_DeleteItemFromObject(store_coll("zone"), zid); + } + } + char pal[24]; + if (api_id(cJSON_GetObjectItem(prof, "palette_id"), pal, sizeof(pal)) && !used_elsewhere(pid, "palette_id", pal)) { + cJSON_DeleteItemFromObject(store_coll("palette"), pal); + } + cJSON_DeleteItemFromObject(store_coll("profile"), pid); + const cJSON *cur = cJSON_GetObjectItem(store_settings(), "current_profile_id"); + if (cJSON_IsString(cur) && !strcmp(cur->valuestring, pid)) { + cJSON_DeleteItemFromObject(store_settings(), "current_profile_id"); + store_save("settings"); + } + store_save("preset"); + store_save("zone"); + store_save("palette"); + store_save("profile"); + engine_groups_changed(); + return api_message(req, "200 OK", "Profile deleted successfully"); +} + +bool profiles_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_DELETE && strcmp(seg[1], "current")) { + *ret = delete_profile(req, seg[1]); + return true; + } + if (n == 1 && method == HTTP_POST) { + *ret = create_profile(req); + return true; + } + if (n == 3 && method == HTTP_POST && !strcmp(seg[2], "clone")) { + *ret = clone_profile(req, seg[1]); + return true; + } + if (n == 3 && method == HTTP_POST && !strcmp(seg[2], "apply")) { + if (!cJSON_GetObjectItem(store_coll("profile"), seg[1])) { + *ret = api_error(req, "404 Not Found", "Profile not found"); + return true; + } + api_set(store_settings(), "current_profile_id", cJSON_CreateString(seg[1])); + store_save("settings"); + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "message", "Profile applied"); + cJSON_AddStringToObject(o, "id", seg[1]); + *ret = api_json(req, "200 OK", o, true); + return true; + } + return false; +} + +/* ------------------------------------------------------------------ zones */ + +#define ZONE_COOKIE "current_zone" + +static cJSON *current_profile_rec(void) +{ + const char *cur = api_current_profile(); + return cur ? cJSON_GetObjectItem(store_coll("profile"), cur) : NULL; +} + +// The current profile's zone list, created when the profile has none +static cJSON *profile_zone_list(void) +{ + cJSON *prof = current_profile_rec(); + if (!prof) { + return NULL; + } + cJSON *z = (cJSON *)profile_zones(prof); + if (!z) { + z = cJSON_AddArrayToObject(prof, "zones"); + } + return z; +} + +static void list_remove(cJSON *list, const char *id) +{ + for (int i = cJSON_GetArraySize(list) - 1; i >= 0; i--) { + char key[24]; + if (api_id(cJSON_GetArrayItem(list, i), key, sizeof(key)) && !strcmp(key, id)) { + cJSON_DeleteItemFromArray(list, i); + } + } +} + +// Zone picked with set-current (cookie), else the current profile's first zone; NULL when none +static const char *current_zone(httpd_req_t *req, char *buf, size_t len) +{ + size_t n = len; + if (httpd_req_get_cookie_val(req, ZONE_COOKIE, buf, &n) == ESP_OK && buf[0] && + cJSON_GetObjectItem(store_coll("zone"), buf)) { + return buf; + } + cJSON *prof = current_profile_rec(); + const cJSON *first = prof ? cJSON_GetArrayItem(profile_zones(prof), 0) : NULL; + return api_id(first, buf, len) ? buf : NULL; +} + +static void set_zone_cookie(httpd_req_t *req, const char *zone_id) +{ + static char hdr[96]; // must outlive the response send + if (zone_id) { + snprintf(hdr, sizeof(hdr), ZONE_COOKIE "=%s; Path=/; Max-Age=31536000; SameSite=Lax", zone_id); + } else { + snprintf(hdr, sizeof(hdr), ZONE_COOKIE "=; Path=/; Max-Age=0; SameSite=Lax"); + } + httpd_resp_set_hdr(req, "Set-Cookie", hdr); +} + +static esp_err_t list_zones(httpd_req_t *req) +{ + char cur[24]; + const char *zid = current_zone(req, cur, sizeof(cur)); + const char *pid = api_current_profile(); + cJSON *prof = current_profile_rec(); + const cJSON *order = prof ? profile_zones(prof) : NULL; + cJSON *o = cJSON_CreateObject(); + cJSON_AddItemReferenceToObject(o, "zones", store_coll("zone")); + cJSON_AddItemToObject(o, "zone_order", order ? cJSON_Duplicate(order, true) : cJSON_CreateArray()); + cJSON_AddItemToObject(o, "current_zone_id", zid ? cJSON_CreateString(zid) : cJSON_CreateNull()); + cJSON_AddItemToObject(o, "profile_id", pid ? cJSON_CreateString(pid) : cJSON_CreateNull()); + return api_json(req, "200 OK", o, true); +} + +static esp_err_t create_zone(httpd_req_t *req) +{ + cJSON *body = api_body(req); + if (!body) { + return ESP_OK; + } + const cJSON *name = cJSON_GetObjectItem(body, "name"); + if (!cJSON_IsString(name) || !name->valuestring[0]) { + cJSON_Delete(body); + return api_error(req, "400 Bad Request", "name is required"); + } + cJSON *names = cJSON_GetObjectItem(body, "names"); + if (!names) { + names = cJSON_GetObjectItem(body, "ids"); + } + cJSON *z = cJSON_CreateObject(); + cJSON_AddStringToObject(z, "name", name->valuestring); + cJSON_AddItemToObject(z, "names", cJSON_IsArray(names) ? cJSON_Duplicate(names, true) : cJSON_CreateArray()); + const cJSON *presets = cJSON_GetObjectItem(body, "presets"); + cJSON_AddItemToObject(z, "presets", cJSON_IsArray(presets) ? cJSON_Duplicate(presets, true) : cJSON_CreateArray()); + cJSON_AddNullToObject(z, "default_preset"); + cJSON_DeleteItemFromObject(body, "ids"); + api_merge(z, body); + cJSON_Delete(body); + char id[16]; + api_add("zone", z, id, sizeof(id)); + cJSON *list = profile_zone_list(); + if (list) { + cJSON_AddItemToArray(list, cJSON_CreateString(id)); + store_save("profile"); + } + store_save("zone"); + engine_groups_changed(); + return send_keyed(req, "201 Created", id, z); +} + +static esp_err_t clone_zone(httpd_req_t *req, const char *src_id) +{ + cJSON *src = cJSON_GetObjectItem(store_coll("zone"), src_id); + if (!src) { + return api_error(req, "404 Not Found", "Zone not found"); + } + cJSON *body = api_body_opt(req); + if (!body) { + return ESP_OK; + } + cJSON *z = cJSON_Duplicate(src, true); + const cJSON *name = cJSON_GetObjectItem(body, "name"), *src_name = cJSON_GetObjectItem(src, "name"); + char copy_name[96]; + if (cJSON_IsString(name) && name->valuestring[0]) { + snprintf(copy_name, sizeof(copy_name), "%s", name->valuestring); + } else if (cJSON_IsString(src_name) && src_name->valuestring[0]) { + snprintf(copy_name, sizeof(copy_name), "%s Copy", src_name->valuestring); + } else { + snprintf(copy_name, sizeof(copy_name), "Zone %s Copy", src_id); + } + cJSON_Delete(body); + api_set(z, "name", cJSON_CreateString(copy_name)); + char id[16]; + api_add("zone", z, id, sizeof(id)); + cJSON *list = profile_zone_list(); + if (list) { + cJSON_AddItemToArray(list, cJSON_CreateString(id)); + store_save("profile"); + } + store_save("zone"); + engine_groups_changed(); + return send_keyed(req, "201 Created", id, z); +} + +static esp_err_t delete_zone(httpd_req_t *req, const char *id) +{ + char cur[24]; + const char *curz = current_zone(req, cur, sizeof(cur)); + if (!strcmp(id, "current")) { + if (!curz) { + return api_error(req, "404 Not Found", "No current zone set"); + } + id = curz; + } + if (!cJSON_GetObjectItem(store_coll("zone"), id)) { + return api_error(req, "404 Not Found", "Zone not found"); + } + char key[24]; + snprintf(key, sizeof(key), "%s", id); + cJSON *prof; + cJSON_ArrayForEach(prof, store_coll("profile")) + { + list_remove((cJSON *)profile_zones(prof), key); + } + if (curz && !strcmp(curz, key)) { + set_zone_cookie(req, NULL); + } + cJSON_DeleteItemFromObject(store_coll("zone"), key); + store_save("profile"); + store_save("zone"); + engine_groups_changed(); + return api_message(req, "200 OK", "Zone deleted successfully"); +} + +// htmx swaps this in as a zone's tab content; a plain request gets the whole page +static esp_err_t content_fragment(httpd_req_t *req, const char *id) +{ + char cur[24]; + if (!strcmp(id, "current")) { + id = current_zone(req, cur, sizeof(cur)); + if (!id) { + return api_error(req, "404 Not Found", "No current zone set"); + } + } + if (!cJSON_GetObjectItem(store_coll("zone"), id)) { + httpd_resp_set_status(req, "404 Not Found"); + httpd_resp_set_type(req, "text/html"); + return httpd_resp_sendstr(req, "
Zone not found
"); + } + set_zone_cookie(req, id); + if (httpd_req_get_hdr_value_len(req, "HX-Request") == 0) { + return web_send_page(req, "index.html"); + } + char html[320]; + snprintf(html, sizeof(html), + "

Presets

" + "
" + "
", + id); + httpd_resp_set_type(req, "text/html"); + return httpd_resp_sendstr(req, html); +} + +bool zones_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) +{ + const int method = req->method; + if (n == 1) { + if (method == HTTP_GET) { + *ret = list_zones(req); + return true; + } + if (method == HTTP_POST) { + *ret = create_zone(req); + return true; + } + return false; + } + if (n == 2 && method == HTTP_GET && !strcmp(seg[1], "current")) { + char cur[24]; + const char *zid = current_zone(req, cur, sizeof(cur)); + cJSON *o = cJSON_CreateObject(); + if (!zid) { + cJSON_AddStringToObject(o, "error", "No current zone set"); + cJSON_AddNullToObject(o, "zone"); + cJSON_AddNullToObject(o, "zone_id"); + *ret = api_json(req, "404 Not Found", o, true); + return true; + } + cJSON_AddItemReferenceToObject(o, "zone", cJSON_GetObjectItem(store_coll("zone"), zid)); + cJSON_AddStringToObject(o, "zone_id", zid); + *ret = api_json(req, "200 OK", o, true); + return true; + } + if (n == 2 && method == HTTP_DELETE) { + *ret = delete_zone(req, seg[1]); + return true; + } + if (n != 3) { + return false; + } + if (!strcmp(seg[1], "engine") && !strcmp(seg[2], "status")) { + *ret = api_json(req, "200 OK", engine_status(), true); + return true; + } + if (method == HTTP_GET && !strcmp(seg[2], "content-fragment")) { + *ret = content_fragment(req, seg[1]); + return true; + } + if (method != HTTP_POST) { + return false; + } + if (!strcmp(seg[2], "set-current")) { + if (!cJSON_GetObjectItem(store_coll("zone"), seg[1])) { + *ret = api_error(req, "404 Not Found", "Zone not found"); + return true; + } + set_zone_cookie(req, seg[1]); + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "message", "Current zone set"); + cJSON_AddStringToObject(o, "zone_id", seg[1]); + *ret = api_json(req, "200 OK", o, true); + return true; + } + if (!strcmp(seg[2], "clone")) { + *ret = clone_zone(req, seg[1]); + return true; + } + if (!strcmp(seg[2], "play")) { + cJSON *body = api_body_opt(req); + if (!body) { + *ret = ESP_OK; + return true; + } + char key[24]; + api_id(cJSON_GetObjectItem(body, "preset_id"), key, sizeof(key)); + // The UI sends drivers:false when it has pushed to the drivers itself + bool skip = cJSON_IsFalse(cJSON_GetObjectItem(body, "drivers")); + cJSON_Delete(body); + if (!key[0]) { + *ret = api_error(req, "400 Bad Request", "preset_id required"); + return true; + } + if (!cJSON_GetObjectItem(store_coll("zone"), seg[1])) { + *ret = api_error(req, "404 Not Found", "Zone not found"); + return true; + } + if (!cJSON_GetObjectItem(store_coll("preset"), key)) { + *ret = api_error(req, "404 Not Found", "Preset not found"); + return true; + } + esp_err_t err = skip ? ESP_OK : engine_play(seg[1], key); + if (err != ESP_OK) { + *ret = api_result(req, err, ""); + return true; + } + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "message", "Playing"); + cJSON_AddStringToObject(o, "zone_id", seg[1]); + cJSON_AddStringToObject(o, "preset_id", key); + *ret = api_json(req, "200 OK", o, true); + return true; + } + if (!strcmp(seg[2], "stop")) { + esp_err_t err = engine_stop(seg[1]); + if (err != ESP_OK && err != ESP_ERR_NOT_FOUND) { + *ret = api_result(req, err, ""); + return true; + } + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "message", "Stopped"); + cJSON_AddBoolToObject(o, "stopped", err == ESP_OK); + *ret = api_json(req, "200 OK", o, true); + return true; + } + return false; +} diff --git a/main/store.c b/main/store.c index a69c7ec..54294d1 100644 --- a/main/store.c +++ b/main/store.c @@ -4,6 +4,7 @@ #include #include #include "esp_check.h" +#include "esp_heap_caps.h" #include "esp_littlefs.h" #include "esp_log.h" #include "freertos/FreeRTOS.h" @@ -68,8 +69,18 @@ static cJSON *load_file(const char *name) return obj; } +// JSON nodes are small, so plain malloc would put the whole store in internal RAM, which the mic, +// Wi-Fi and lwIP need. They go to PSRAM instead (free() releases either kind). +static void *json_malloc(size_t size) +{ + void *p = heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + return p ? p : malloc(size); +} + esp_err_t store_init(void) { + cJSON_Hooks hooks = { .malloc_fn = json_malloc, .free_fn = free }; + cJSON_InitHooks(&hooks); s_lock = xSemaphoreCreateRecursiveMutex(); ESP_RETURN_ON_FALSE(s_lock, ESP_ERR_NO_MEM, TAG, "mutex"); ESP_RETURN_ON_ERROR(mount("db", "/db"), TAG, "mount db"); diff --git a/main/web.c b/main/web.c index 37c297d..44b490a 100644 --- a/main/web.c +++ b/main/web.c @@ -68,6 +68,36 @@ static bool find_file(const char *path, const uint8_t **data, uint32_t *len) return false; } +bool web_file(const char *path, const uint8_t **data, uint32_t *len) +{ + return find_file(path, data, len); +} + +void web_each(const char *prefix, void (*fn)(const char *name, void *ctx), void *ctx) +{ + const uint8_t *p = www_pack_start + 4, *end = www_pack_end; + if (end - www_pack_start < 6 || memcmp(www_pack_start, "WWW1", 4) != 0) { + return; + } + size_t plen = strlen(prefix); + while (end - p >= 6) { + uint16_t nlen; + uint32_t dlen; + memcpy(&nlen, p, 2); + memcpy(&dlen, p + 2, 4); + if (nlen == 0 || end - p < 6 + nlen + (ptrdiff_t)dlen) { + return; + } + char name[128]; + if (nlen < sizeof(name) && nlen > plen && memcmp(p + 6, prefix, plen) == 0) { + memcpy(name, p + 6 + plen, nlen - plen); + name[nlen - plen] = 0; + fn(name, ctx); + } + p += 6 + nlen + dlen; + } +} + // path is the URL-relative name, e.g. "static/zones.js" static esp_err_t send_gz(httpd_req_t *req, const char *path, bool immutable) { diff --git a/main/web.h b/main/web.h index 990a528..b16d8da 100644 --- a/main/web.h +++ b/main/web.h @@ -1,5 +1,7 @@ #pragma once +#include +#include #include "esp_err.h" #include "esp_http_server.h" @@ -9,3 +11,8 @@ esp_err_t web_register(httpd_handle_t server); // Send one of the top-level pages (e.g. "settings.html") esp_err_t web_send_page(httpd_req_t *req, const char *name); + +// A file in the embedded blob (gzipped, except patterns/*.py which are stored as they are) +bool web_file(const char *path, const uint8_t **data, uint32_t *len); +// Call fn with the rest of every name in the blob that starts with prefix +void web_each(const char *prefix, void (*fn)(const char *name, void *ctx), void *ctx); diff --git a/main/ws.c b/main/ws.c new file mode 100644 index 0000000..84b4c92 --- /dev/null +++ b/main/ws.c @@ -0,0 +1,90 @@ +#include "ws.h" + +#include +#include +#include "cJSON.h" +#include "engine.h" +#include "esp_log.h" +#include "store.h" + +static const char *TAG = "ws"; + +#define FRAME_MAX 4096 + +static void send_text(httpd_req_t *req, const char *text) +{ + httpd_ws_frame_t f = { .type = HTTPD_WS_TYPE_TEXT, .payload = (uint8_t *)text, .len = strlen(text) }; + httpd_ws_send_frame_async(req->handle, httpd_req_to_sockfd(req), &f); +} + +// One v1 driver message from the browser: "to" (a MAC) addresses one driver, otherwise it is broadcast +static void forward(httpd_req_t *req, const char *text) +{ + cJSON *msg = cJSON_Parse(text); + if (!cJSON_IsObject(msg)) { + cJSON_Delete(msg); + send_text(req, "{\"error\":\"JSON object required\"}"); + return; + } + cJSON *to = cJSON_DetachItemFromObject(msg, "to"), *targets = NULL; + if (cJSON_IsString(to)) { + targets = cJSON_CreateArray(); + cJSON_AddItemToArray(targets, to); + } else { + cJSON_Delete(to); + } + cJSON *messages = cJSON_CreateArray(); + cJSON_AddItemToArray(messages, msg); + store_lock(); + esp_err_t err = engine_push(messages, targets); + store_unlock(); + cJSON_Delete(messages); + cJSON_Delete(targets); + if (err != ESP_OK) { + send_text(req, "{\"error\":\"Send failed\"}"); + } +} + +static esp_err_t ws_handler(httpd_req_t *req) +{ + if (req->method == HTTP_GET) { + if (httpd_ws_get_fd_info(req->handle, httpd_req_to_sockfd(req)) != HTTPD_WS_CLIENT_WEBSOCKET) { + httpd_resp_set_status(req, "426 Upgrade Required"); + httpd_resp_set_hdr(req, "Upgrade", "websocket"); + return httpd_resp_sendstr(req, "websocket only"); + } + // The controller keeps no Wi-Fi driver connections, so the v1 snapshot is always empty + send_text(req, "{\"type\":\"device_tcp_snapshot\",\"connected_ips\":[]}"); + return ESP_OK; + } + httpd_ws_frame_t f = { 0 }; + esp_err_t err = httpd_ws_recv_frame(req, &f, 0); + if (err != ESP_OK) { + return err; + } + if (f.type != HTTPD_WS_TYPE_TEXT || f.len == 0) { + return ESP_OK; + } + if (f.len > FRAME_MAX) { + ESP_LOGW(TAG, "frame of %u bytes dropped", (unsigned)f.len); + return ESP_FAIL; // closes the connection + } + char *buf = malloc(f.len + 1); + if (!buf) { + return ESP_ERR_NO_MEM; + } + f.payload = (uint8_t *)buf; + err = httpd_ws_recv_frame(req, &f, f.len); + if (err == ESP_OK) { + buf[f.len] = 0; + forward(req, buf); + } + free(buf); + return err; +} + +esp_err_t ws_register(httpd_handle_t server) +{ + const httpd_uri_t u = { .uri = "/ws", .method = HTTP_GET, .handler = ws_handler, .is_websocket = true }; + return httpd_register_uri_handler(server, &u); +} diff --git a/main/ws.h b/main/ws.h new file mode 100644 index 0000000..ae80ba4 --- /dev/null +++ b/main/ws.h @@ -0,0 +1,8 @@ +#pragma once + +#include "esp_err.h" +#include "esp_http_server.h" + +// GET /ws: the v1 browser websocket. Each text frame is a v1 driver message (JSON); an optional "to" +// MAC sends it to one driver, otherwise it is broadcast. Replies {"error": ...} when it cannot go out. +esp_err_t ws_register(httpd_handle_t server); diff --git a/sdkconfig.defaults b/sdkconfig.defaults index edbdece..3929b70 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -18,3 +18,5 @@ CONFIG_ESPNOW_CHANNEL=5 CONFIG_BEAT_TEST_GPIO=4 # A new OTA image must confirm itself (ota_confirm_later) or the bootloader goes back to the old one CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y +# /ws (browser websocket) +CONFIG_HTTPD_WS_SUPPORT=y diff --git a/test/api/test_collections.py b/test/api/test_collections.py index 33bfb1f..02a16f1 100644 --- a/test/api/test_collections.py +++ b/test/api/test_collections.py @@ -1,6 +1,6 @@ """Groups, sequences, scenes and palettes.""" -from helpers import find_id_by_field, missing, new_id, unique +from helpers import find_id_by_field, new_id, unique def test_groups(c): @@ -31,14 +31,12 @@ def test_sequences_crud(c): assert c.delete(f"/sequences/{sid}").status_code == 200 -@missing("sequence step validation") def test_sequence_step_needs_preset(c): sid = new_id(c.post("/sequences", json={"name": unique("pytest-seq"), "steps": []})) assert c.put(f"/sequences/{sid}", json={"steps": [{"duration_s": 1}]}).status_code == 400 c.delete(f"/sequences/{sid}") -@missing("400 for a sequence without zone_id") def test_sequence_without_zone_cannot_play(c): sid = new_id(c.post("/sequences", json={"name": unique("pytest-seq"), "steps": [{"preset_id": "1", "duration_s": 1}]})) @@ -46,7 +44,6 @@ def test_sequence_without_zone_cannot_play(c): c.delete(f"/sequences/{sid}") -@missing("sequence play/stop status replies and active flag") def test_sequence_play_and_stop(c): profile = new_id(c.post("/profiles", json={"name": unique("pytest-engine")})) c.post(f"/profiles/{profile}/apply") @@ -80,7 +77,6 @@ def test_scenes(c): assert c.delete(f"/scenes/{sid}").status_code == 200 -@missing("v1 palette shape ({id, colors})") def test_palettes(c): resp = c.post("/palettes", json={"colors": ["#112233", "#445566"]}) assert resp.status_code == 201 @@ -95,7 +91,6 @@ def test_palettes(c): assert c.delete(f"/palettes/{pid}").status_code == 200 -@missing("v1 palette shape ({id, colors})") def test_palettes_list_is_colour_lists(c): pid = str(c.post("/palettes", json={"colors": ["#abcdef"]}).json()["id"]) assert c.get("/palettes").json()[pid] == ["#abcdef"] diff --git a/test/api/test_devices.py b/test/api/test_devices.py index 52b275c..59ebcc1 100644 --- a/test/api/test_devices.py +++ b/test/api/test_devices.py @@ -1,7 +1,5 @@ import pytest -from helpers import missing - # Test MACs from v1; no real driver has them ESPNOW_MAC = "aabbccddeeff" WIFI_MAC = "102030405060" @@ -33,12 +31,10 @@ def test_list(c): assert isinstance(resp.json(), dict) -@missing("v1 device registry (MAC keys, validation)") def test_create_requires_name(c): assert c.post("/devices", json={}).status_code == 400 -@missing("v1 device registry (MAC keys, validation)") def test_create_espnow_keyed_by_mac(espnow_dev): dev = espnow_dev.json() assert list(dev) == [ESPNOW_MAC] @@ -50,7 +46,6 @@ def test_create_espnow_keyed_by_mac(espnow_dev): assert rec["address"] == ESPNOW_MAC -@missing("v1 device registry (MAC keys, validation)") def test_get_espnow_has_no_connection_state(c, espnow_dev): resp = c.get(f"/devices/{ESPNOW_MAC}") assert resp.status_code == 200 @@ -59,7 +54,6 @@ def test_get_espnow_has_no_connection_state(c, espnow_dev): assert c.get("/devices").json()[ESPNOW_MAC].get("connected") is None -@missing("v1 device registry (MAC keys, validation)") def test_create_wifi(c, wifi_dev): rec = wifi_dev.json()[WIFI_MAC] assert rec["transport"] == "wifi" @@ -67,7 +61,6 @@ def test_create_wifi(c, wifi_dev): assert c.get(f"/devices/{WIFI_MAC}").json().get("connected") is False -@missing("v1 device registry (MAC keys, validation)") def test_create_second_wifi_same_name(c, wifi_dev): resp = c.post("/devices", json={"name": "pytest-wifi", "transport": "wifi", "address": "192.168.50.11", "mac": WIFI_MAC2}) @@ -76,30 +69,25 @@ def test_create_second_wifi_same_name(c, wifi_dev): assert c.delete(f"/devices/{WIFI_MAC2}").status_code == 200 -@missing("v1 device registry (MAC keys, validation)") def test_create_duplicate_mac(c, wifi_dev): resp = c.post("/devices", json={"name": "pytest-wifi-dupmac", "transport": "wifi", "address": "192.168.50.99", "mac": WIFI_MAC}) assert resp.status_code == 409 -@missing("v1 device registry (MAC keys, validation)") def test_create_wifi_requires_mac(c): resp = c.post("/devices", json={"name": "no-mac-wifi", "transport": "wifi", "address": "192.168.50.12"}) assert resp.status_code == 400 -@missing("v1 device registry (MAC keys, validation)") def test_create_rejects_unknown_transport(c): assert c.post("/devices", json={"name": "bad-tr", "transport": "serial"}).status_code == 400 -@missing("v1 device registry (MAC keys, validation)") def test_rename_blank(c, espnow_dev): assert c.put(f"/devices/{ESPNOW_MAC}", json={"name": " "}).status_code == 400 -@missing("v1 device registry (MAC keys, validation)") def test_rename(c, espnow_dev, wifi_dev): for mac in (ESPNOW_MAC, WIFI_MAC): resp = c.put(f"/devices/{mac}", json={"name": "renamed"}) @@ -107,19 +95,16 @@ def test_rename(c, espnow_dev, wifi_dev): assert resp.json()["name"] == "renamed" -@missing("v1 device registry (MAC keys, validation)") def test_cannot_change_mac(c, espnow_dev): assert c.put(f"/devices/{ESPNOW_MAC}", json={"mac": "001122334455"}).status_code == 400 -@missing("device identify") def test_identify(c, espnow_dev): resp = c.post(f"/devices/{ESPNOW_MAC}/identify") assert resp.status_code == 200 assert resp.json().get("message") -@missing("device identify") def test_identify_unknown(c): assert c.post("/devices/000000000000/identify").status_code == 404 @@ -130,7 +115,6 @@ def test_status(c): assert isinstance(resp.json(), dict) -@missing("v1 device registry (MAC keys, validation)") def test_delete(c, espnow_dev): assert c.delete(f"/devices/{ESPNOW_MAC}").status_code == 200 assert c.get(f"/devices/{ESPNOW_MAC}").status_code == 404 diff --git a/test/api/test_led_tool.py b/test/api/test_led_tool.py deleted file mode 100644 index 422c4f3..0000000 --- a/test/api/test_led_tool.py +++ /dev/null @@ -1,20 +0,0 @@ -"""led-tool: configure drivers over USB serial (v1 controllers/led_tool.py).""" - -from helpers import missing - -# Every test here fails on v2 -pytestmark = missing("led-tool (USB serial)") - - -def test_ports(c): - resp = c.get("/led-tool/ports") - assert resp.status_code == 200 - assert isinstance(resp.json()["ports"], list) - - -def test_settings_requires_port(c): - assert c.get("/led-tool/settings").status_code == 400 - - -def test_reset_requires_port(c): - assert c.post("/led-tool/reset", json={}).status_code == 400 diff --git a/test/api/test_outputs.py b/test/api/test_outputs.py index df0a2e2..cc58547 100644 --- a/test/api/test_outputs.py +++ b/test/api/test_outputs.py @@ -1,10 +1,5 @@ import pytest -from helpers import missing - -# Every test here fails on v2 -pytestmark = missing("pixel outputs (DDP, Art-Net, sACN, DMX)") - @pytest.fixture def output(c): diff --git a/test/api/test_patterns.py b/test/api/test_patterns.py index 2c222c2..f2666b0 100644 --- a/test/api/test_patterns.py +++ b/test/api/test_patterns.py @@ -1,21 +1,18 @@ -from helpers import missing, unique +from helpers import unique -@missing("/patterns/definitions") def test_definitions(c): resp = c.get("/patterns/definitions") assert resp.status_code == 200 assert isinstance(resp.json(), dict) -@missing("driver pattern files in /patterns") def test_list_includes_driver_patterns(c): resp = c.get("/patterns") assert resp.status_code == 200 assert "blink" in resp.json() -@missing("v1 pattern create ({name, data})") def test_crud(c): pid = unique("pytest_pattern").replace("-", "_") resp = c.post("/patterns", json={"name": pid, "data": {"foo": "bar"}}) @@ -30,7 +27,6 @@ def test_crud(c): assert c.delete(f"/patterns/{pid}").status_code == 200 -@missing("/patterns/ota/file") def test_ota_file(c): resp = c.get("/patterns/ota/file/blink.py") assert resp.status_code == 200 @@ -38,7 +34,6 @@ def test_ota_file(c): assert "class" in resp.text -@missing("/patterns/ota/file") def test_ota_file_rejects_builtin(c): # on/off are built into the driver firmware, not OTA files resp = c.get("/patterns/ota/file/on.py") @@ -46,7 +41,6 @@ def test_ota_file_rejects_builtin(c): assert "error" in resp.json() -@missing("/patterns/ota/manifest") def test_ota_manifest(c): resp = c.get("/patterns/ota/manifest") assert resp.status_code == 200 @@ -54,20 +48,17 @@ def test_ota_manifest(c): assert "blink.py" in names -@missing("/patterns//send") def test_send_rejects_builtin(c): resp = c.post("/patterns/off/send", json={}) assert resp.status_code == 400 assert "error" in resp.json() -@missing("/patterns/upload") def test_upload_rejects_builtin(c): resp = c.post("/patterns/upload", json={"name": "on.py", "code": "class On:\n def run(self, p):\n yield\n"}) assert resp.status_code == 400 -@missing("/patterns/driver") def test_driver_rejects_builtin(c): resp = c.post("/patterns/driver", json={"name": "off", "code": "class Off:\n def run(self, p):\n yield\n"}) assert resp.status_code == 400 diff --git a/test/api/test_presets.py b/test/api/test_presets.py index 758a45c..45d82ad 100644 --- a/test/api/test_presets.py +++ b/test/api/test_presets.py @@ -1,6 +1,6 @@ import pytest -from helpers import missing, new_id, unique +from helpers import new_id, unique @pytest.fixture @@ -21,7 +21,6 @@ def preset(c, profile): c.delete(f"/presets/{pid}") -@missing("seeded presets for a new profile") def test_list_and_get(c, profile): resp = c.get("/presets") assert resp.status_code == 200 @@ -40,7 +39,6 @@ def test_create_belongs_to_current_profile(c, profile): assert str(resp.json()[pid]["profile_id"]) == profile -@missing("preset defaults on create") def test_create_fills_defaults(c, profile): resp = c.post("/presets", json={"name": unique("pytest-preset"), "pattern": "on"}) rec = resp.json()[new_id(resp)] diff --git a/test/api/test_profiles.py b/test/api/test_profiles.py index eaa6cca..6c0ce9c 100644 --- a/test/api/test_profiles.py +++ b/test/api/test_profiles.py @@ -1,6 +1,6 @@ import pytest -from helpers import missing, new_id, unique +from helpers import new_id, unique # Presets every new profile is seeded with (v1 controllers/profile.py) SEEDED = {"on", "off", "rainbow", "Colour Cycle", "transition", "flicker", "flame", "twinkle"} @@ -35,7 +35,6 @@ def test_apply_unknown_profile(c): assert c.post("/profiles/999999/apply").status_code == 404 -@missing("profile seeding (presets, default zone, palette)") def test_new_profile_is_seeded(c, profile): presets = c.get("/presets").json() assert SEEDED <= {p["name"] for p in presets.values()} @@ -61,7 +60,6 @@ def test_put(c, profile): assert resp.json()["name"] == name -@missing("profile clone") def test_clone(c, profile): name = unique("pytest-profile-clone") resp = c.post(f"/profiles/{profile}/clone", json={"name": name}) diff --git a/test/api/test_routes.py b/test/api/test_routes.py index b490d25..238ea66 100644 --- a/test/api/test_routes.py +++ b/test/api/test_routes.py @@ -1,7 +1,5 @@ import pytest -from helpers import missing - def test_index(c): resp = c.get("/") @@ -24,7 +22,6 @@ def test_settings_page(c): assert "LED Controller" in resp.text -@missing("/ws") def test_ws_rejects_plain_get(c): # A websocket endpoint refuses a request that is not an upgrade resp = c.get("/ws") diff --git a/test/api/test_settings.py b/test/api/test_settings.py index 3119b18..6d500a8 100644 --- a/test/api/test_settings.py +++ b/test/api/test_settings.py @@ -1,49 +1,15 @@ -from helpers import missing, unique - -@missing("settings defaults") def test_get_settings(c): resp = c.get("/settings") assert resp.status_code == 200 assert "wifi_channel" in resp.json() -@missing("/settings/wifi/ap") -def test_wifi_ap_get(c): - resp = c.get("/settings/wifi/ap") - assert resp.status_code == 200 - ap = resp.json() - assert "saved_ssid" in ap - assert "active" in ap - - -@missing("/settings/wifi/ap") -def test_wifi_ap_post(c): - ssid = unique("pytest-ssid") - resp = c.post("/settings/wifi/ap", json={"ssid": ssid, "password": "secret", "channel": 1}) - assert resp.status_code == 200 - assert resp.json()["ssid"] == ssid - assert resp.json()["channel"] == 1 - assert c.get("/settings/wifi/ap").json()["saved_ssid"] == ssid - - -@missing("/settings/wifi/ap") -def test_wifi_ap_rejects_bad_channel(c): - resp = c.post("/settings/wifi/ap", json={"ssid": "bad-ssid", "password": "secret", "channel": 12}) - assert resp.status_code == 400 - - -@missing("/settings/wifi/ap") -def test_wifi_ap_requires_ssid(c): - assert c.post("/settings/wifi/ap", json={"password": "secret"}).status_code == 400 - - def test_wifi_channel(c): assert c.put("/settings/settings", json={"wifi_channel": 11}).status_code == 200 assert c.get("/settings").json()["wifi_channel"] == 11 -@missing("settings validation") def test_wifi_channel_out_of_range(c): assert c.put("/settings/settings", json={"wifi_channel": 12}).status_code == 400 @@ -53,6 +19,5 @@ def test_global_brightness(c): assert c.get("/settings").json().get("global_brightness") == 42 -@missing("settings validation") def test_global_brightness_out_of_range(c): assert c.put("/settings/settings", json={"global_brightness": 300}).status_code == 400 diff --git a/test/api/test_zones.py b/test/api/test_zones.py index c593365..33013f3 100644 --- a/test/api/test_zones.py +++ b/test/api/test_zones.py @@ -1,6 +1,6 @@ import pytest -from helpers import missing, new_id, unique +from helpers import new_id, unique @pytest.fixture @@ -21,7 +21,6 @@ def zone(c, profile): c.delete(f"/zones/{zid}") -@missing("v1 zone list shape and profile zone order") def test_list(c, profile, zone): resp = c.get("/zones") assert resp.status_code == 200 @@ -32,12 +31,10 @@ def test_list(c, profile, zone): assert "current_zone_id" in data -@missing("adding new zones to the current profile") def test_create_adds_to_profile(c, profile, zone): assert zone in c.get(f"/profiles/{profile}").json()["zones"] -@missing("zone validation") def test_create_requires_name(c, profile): assert c.post("/zones", json={"names": ["1"]}).status_code == 400 @@ -48,7 +45,6 @@ def test_get(c, zone): assert resp.json()["name"].startswith("pytest-zone") -@missing("zone set-current") def test_set_current(c, zone): resp = c.post(f"/zones/{zone}/set-current") assert resp.status_code == 200 @@ -59,7 +55,6 @@ def test_set_current(c, zone): assert resp.json()["zone_id"] == zone -@missing("zone set-current") def test_set_current_unknown(c): assert c.post("/zones/999999/set-current").status_code == 404 @@ -75,7 +70,6 @@ def test_edit_workflow(c, zone): assert stored["names"] == ["2", "3", "4"] -@missing("zone clone") def test_clone(c, profile, zone): resp = c.post(f"/zones/{zone}/clone", json={"name": "pytest-zone-clone"}) assert resp.status_code == 201 @@ -88,7 +82,6 @@ def test_clone(c, profile, zone): assert c.delete(f"/zones/{clone}").status_code == 200 -@missing("zone clone") def test_clone_default_name(c, zone): resp = c.post(f"/zones/{zone}/clone", json={}) clone = new_id(resp) @@ -96,14 +89,12 @@ def test_clone_default_name(c, zone): c.delete(f"/zones/{clone}") -@missing("zone content-fragment") def test_content_fragment(c, zone): resp = c.get(f"/zones/{zone}/content-fragment", headers={"HX-Request": "true", "Accept": "text/html"}) assert resp.status_code == 200 assert f'data-zone-id="{zone}"' in resp.text -@missing("removing deleted zones from the profile") def test_delete_removes_from_profile(c, profile): zid = new_id(c.post("/zones", json={"name": unique("pytest-zone"), "names": ["1"]})) assert c.delete(f"/zones/{zid}").status_code == 200 @@ -119,7 +110,6 @@ def test_play_unknown_preset(c, zone): assert c.post(f"/zones/{zone}/play", json={"preset_id": "nope"}).status_code == 404 -@missing("zone stop reply ({stopped})") def test_play_and_stop(c, zone): preset = new_id(c.post("/presets", json={"name": "pytest-on", "pattern": "on", "colors": ["#ff0000"]})) resp = c.post(f"/zones/{zone}/play", json={"preset_id": preset}) diff --git a/tools/build_web.sh b/tools/build_web.sh index 70c7d20..846775a 100755 --- a/tools/build_web.sh +++ b/tools/build_web.sh @@ -31,22 +31,30 @@ npx --yes html-minifier-terser@7.2.0 --collapse-whitespace --remove-comments \ find "$OUT" -type f -exec gzip -9 -n -f {} \; find "$OUT" -name '*.gz' -exec gzip -t {} \; +# led-driver pattern sources, kept uncompressed: the controller serves them and pushes them to drivers +mkdir -p "$OUT/patterns" +cp led-driver/src/patterns/*.py "$OUT/patterns/" + total=$(find "$OUT" -name '*.gz' -printf '%s\n' | paste -sd+ | bc) echo "www_dist: $(find "$OUT" -name '*.gz' | wc -l) files, $total bytes (limit $MAX)" (( total <= MAX )) || { echo "ERROR: web UI exceeds the size limit" >&2; exit 1; } # One blob for the firmware: "WWW1", then per file u16 name length, u32 data length, name (no .gz), -# data; a zero name length ends it. Little-endian, read by main/web.c. +# data; a zero name length ends it. Little-endian, read by main/web.c. patterns/*.py go in as they are. python3 - "$OUT" <<'PY' import os, struct, sys root = sys.argv[1] out = bytearray(b"WWW1") for dirpath, _, names in sorted(os.walk(root)): for n in sorted(names): - if not n.endswith(".gz"): - continue full = os.path.join(dirpath, n) - name = os.path.relpath(full, root)[:-3].encode() + rel = os.path.relpath(full, root) + if rel.startswith("patterns/") and n.endswith(".py"): + name = rel.encode() + elif n.endswith(".gz"): + name = rel[:-3].encode() + else: + continue data = open(full, "rb").read() out += struct.pack("