#include "api.h" #include #include #include #include "cJSON.h" #include "esp_log.h" #include "bench.h" #include "engine.h" #include "espnow_tx.h" #include "rel.h" #include "store.h" #include "web.h" static const char *TAG = "api"; #define BODY_MAX (256 * 1024) // URL resource -> store collection static const struct { const char *res; const char *coll; } RES[] = { { "devices", "device" }, { "zones", "zone" }, { "presets", "preset" }, { "profiles", "profile" }, { "palettes", "palette" }, { "patterns", "pattern" }, { "sequences", "sequence" }, { "scenes", "scene" }, { "groups", "group" }, { "outputs", "output" }, }; static esp_err_t send_json(httpd_req_t *req, const char *status, cJSON *obj, bool own) { char *s = cJSON_PrintUnformatted(obj); if (own) { cJSON_Delete(obj); } if (!s) { return httpd_resp_send_500(req); } httpd_resp_set_status(req, status); httpd_resp_set_type(req, "application/json"); esp_err_t ret = httpd_resp_send(req, s, HTTPD_RESP_USE_STRLEN); free(s); return ret; } static esp_err_t send_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); } // Parsed JSON object body, or NULL after an error response has been sent static cJSON *read_body(httpd_req_t *req) { if (req->content_len == 0 || req->content_len > BODY_MAX) { send_error(req, "400 Bad Request", req->content_len ? "body too large" : "body required"); return NULL; } char *buf = malloc(req->content_len + 1); if (!buf) { httpd_resp_send_500(req); return NULL; } size_t got = 0; while (got < req->content_len) { int r = httpd_req_recv(req, buf + got, req->content_len - got); if (r <= 0) { free(buf); httpd_resp_send_err(req, HTTPD_408_REQ_TIMEOUT, "read failed"); return NULL; } got += r; } buf[got] = 0; cJSON *obj = cJSON_Parse(buf); free(buf); if (!cJSON_IsObject(obj)) { cJSON_Delete(obj); send_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]) { int n = 0; const char *p = uri; while (*p == '/' && n < 3) { p++; size_t len = strcspn(p, "/?"); if (len == 0 || len >= 64) { break; } memcpy(seg[n], p, len); seg[n][len] = 0; n++; p += len; } return n; } static const char *coll_for(const char *res) { for (size_t i = 0; i < sizeof(RES) / sizeof(RES[0]); i++) { if (strcmp(RES[i].res, res) == 0) { return RES[i].coll; } } return NULL; } static const char *current_profile(void) { cJSON *v = cJSON_GetObjectItem(store_settings(), "current_profile_id"); if (cJSON_IsString(v) && cJSON_GetObjectItem(store_coll("profile"), v->valuestring)) { return v->valuestring; } cJSON *first = store_coll("profile")->child; // fall back to the first profile return first ? first->string : NULL; } static bool preset_in_profile(cJSON *rec) { const char *cur = current_profile(); cJSON *pid = cJSON_GetObjectItem(rec, "profile_id"); 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; } static void merge(cJSON *dst, cJSON *src) { 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); } } } static esp_err_t send_message(httpd_req_t *req, const char *status, const char *msg) { 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"); } } 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); } static esp_err_t handle_profile_action(httpd_req_t *req, const char *id, const char *action) { if (strcmp(action, "apply") == 0) { if (!cJSON_GetObjectItem(store_coll("profile"), id)) { return send_error(req, "404 Not Found", "profile not found"); } 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); } static esp_err_t collection_handler_inner(httpd_req_t *req) { char seg[3][64]; int n = split_path(req->uri, seg); const char *coll = n ? coll_for(seg[0]) : NULL; if (!coll) { return send_error(req, "404 Not Found", "unknown resource"); } const bool is_presets = strcmp(coll, "preset") == 0; const bool is_profiles = strcmp(coll, "profile") == 0; 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"); } if (!strcmp(seg[2], "stop")) { return 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); } // "current" profile aliases const char *id = n == 2 ? seg[1] : NULL; if (is_profiles && id && strcmp(id, "current") == 0) { id = current_profile(); if (!id) { return send_error(req, "404 Not Found", "no profiles"); } 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); } } if (!id) { if (method == HTTP_GET) { if (is_profiles) { cJSON *o = cJSON_CreateObject(); cJSON_AddItemReferenceToObject(o, "profiles", all); const char *cur = current_profile(); cJSON_AddStringToObject(o, "current_profile_id", cur ? cur : ""); return send_json(req, "200 OK", o, true); } if (is_presets) { cJSON *o = cJSON_CreateObject(), *it; cJSON_ArrayForEach(it, all) { if (preset_in_profile(it)) { cJSON_AddItemReferenceToObject(o, it->string, it); } } return send_json(req, "200 OK", o, true); } return send_json(req, "200 OK", all, false); } if (method == HTTP_POST) { cJSON *body = read_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); store_save(coll); if (!strcmp(coll, "zone") || !strcmp(coll, "device")) { engine_groups_changed(); } cJSON *o = cJSON_CreateObject(); cJSON_AddItemReferenceToObject(o, nid, body); return send_json(req, "201 Created", o, true); } return send_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"); } switch (method) { case HTTP_GET: return send_json(req, "200 OK", rec, false); case HTTP_PUT: { cJSON *body = read_body(req); if (!body) { return ESP_OK; } merge(rec, body); cJSON_Delete(body); store_save(coll); if (!strcmp(coll, "zone") || !strcmp(coll, "device")) { engine_groups_changed(); } return send_json(req, "200 OK", rec, false); } case HTTP_DELETE: { cJSON_DeleteItemFromObject(all, id); store_save(coll); if (!strcmp(coll, "zone") || !strcmp(coll, "device")) { engine_groups_changed(); } cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "message", "Deleted"); return send_json(req, "200 OK", o, true); } default: return send_error(req, "405 Method Not Allowed", "method not allowed"); } } static esp_err_t settings_handler_inner(httpd_req_t *req) { char seg[3][64]; int n = split_path(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); } 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 not_implemented(req, "this settings route"); } // 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); if (n != 2 || !store_known(seg[1])) { return send_error(req, "404 Not Found", "unknown collection"); } if (req->method == HTTP_GET) { return send_json(req, "200 OK", store_coll(seg[1]), false); } if (req->method == HTTP_PUT) { cJSON *body = read_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"); } cJSON *o = cJSON_CreateObject(); cJSON_AddNumberToObject(o, "records", cJSON_GetArraySize(store_coll(seg[1]))); return send_json(req, "200 OK", o, true); } return send_error(req, "405 Method Not Allowed", "method not allowed"); } #define LOCKED(name) \ static esp_err_t name(httpd_req_t *req) \ { \ store_lock(); \ esp_err_t r = name##_inner(req); \ store_unlock(); \ return r; \ } LOCKED(collection_handler) LOCKED(settings_handler) LOCKED(db_handler) // 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); if (n >= 2 && !strcmp(seg[1], "loss")) { if (req->method == HTTP_POST) { cJSON *b = read_body(req); if (!b) { return ESP_OK; } const cJSON *p = cJSON_GetObjectItem(b, "percent"), *beats = cJSON_GetObjectItem(b, "beats"); espnow_tx_set_loss(cJSON_IsNumber(p) ? (int)p->valuedouble : 0, !cJSON_IsFalse(beats)); cJSON_Delete(b); } bool inc; int pct = espnow_tx_loss(&inc); cJSON *o = cJSON_CreateObject(); cJSON_AddNumberToObject(o, "percent", pct); cJSON_AddBoolToObject(o, "beats", inc); return send_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); if (!b) { return ESP_OK; } const cJSON *bpm = cJSON_GetObjectItem(b, "bpm"), *count = cJSON_GetObjectItem(b, "count"); esp_err_t err = bench_start(cJSON_IsNumber(bpm) ? (float)bpm->valuedouble : 120, 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 send_json(req, "200 OK", bench_results(), true); } return send_error(req, "404 Not Found", "unknown test"); } LOCKED(test_handler) esp_err_t api_register(httpd_handle_t server) { static const char *const ROUTES[] = { "/devices*", "/zones*", "/presets*", "/profiles*", "/palettes*", "/patterns*", "/sequences*", "/scenes*", "/groups*", "/outputs*", }; static const httpd_method_t METHODS[] = { HTTP_GET, HTTP_POST, HTTP_PUT, HTTP_DELETE }; for (size_t r = 0; r < sizeof(ROUTES) / sizeof(ROUTES[0]); r++) { for (size_t m = 0; m < 4; m++) { httpd_uri_t u = { .uri = ROUTES[r], .method = METHODS[m], .handler = collection_handler }; ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &u)); } } for (size_t m = 0; m < 4; m++) { httpd_uri_t t = { .uri = "/test/*", .method = METHODS[m], .handler = test_handler }; ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &t)); } for (size_t m = 0; m < 4; m++) { httpd_uri_t s = { .uri = "/settings*", .method = METHODS[m], .handler = settings_handler }; httpd_uri_t d = { .uri = "/db/*", .method = METHODS[m], .handler = db_handler }; ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &s)); ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &d)); } ESP_LOGI(TAG, "API registered"); return ESP_OK; }