#include "api.h" #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 "sdkconfig.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" }, }; /* ---------------------------------------------------------------- helpers */ esp_err_t api_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; } 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 api_json(req, status, o, true); } 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) { api_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); api_error(req, "400 Bad Request", "JSON object required"); return NULL; } return obj; } 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; 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; } 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)) { return v->valuestring; } cJSON *first = store_coll("profile")->child; // fall back to the first profile return first ? first->string : NULL; } bool api_preset_in_profile(const cJSON *rec) { const char *cur = api_current_profile(); if (!cur) { return true; } char pid[24]; return api_id(cJSON_GetObjectItem(rec, "profile_id"), pid, sizeof(pid)) && strcmp(pid, cur) == 0; } void api_set(cJSON *obj, const char *key, cJSON *val) { 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) { api_set(dst, it->string, cJSON_Duplicate(it, true)); } } } void api_add(const char *coll, cJSON *rec, char *id, size_t len) { store_next_id(coll, id, len); if (cJSON_IsObject(rec)) { api_set(rec, "id", cJSON_CreateString(id)); } cJSON_AddItemToObject(store_coll(coll), id, rec); } /* ------------------------------------------------------------ collections */ static bool route(const char *res, httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) { 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); } } return false; } static esp_err_t collection_handler_inner(httpd_req_t *req) { api_seg_t seg; int n = api_split(req->uri, seg); const char *coll = n ? coll_for(seg[0]) : NULL; if (!coll) { 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; if (n == 3 && method == HTTP_POST && !strcmp(seg[0], "scenes")) { if (!strcmp(seg[2], "play")) { return api_result(req, engine_scene_play(seg[1]), "Scene started"); } if (!strcmp(seg[2], "stop")) { return api_result(req, engine_scene_stop(seg[1]), "Scene stopped"); } } if (n == 3) { 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 = api_current_profile(); if (!id) { 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 api_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 = api_current_profile(); cJSON_AddStringToObject(o, "current_profile_id", cur ? cur : ""); return api_json(req, "200 OK", o, true); } if (is_presets) { cJSON *o = cJSON_CreateObject(), *it; cJSON_ArrayForEach(it, all) { if (api_preset_in_profile(it)) { cJSON_AddItemReferenceToObject(o, it->string, it); } } return api_json(req, "200 OK", o, true); } return api_json(req, "200 OK", all, false); } if (method == HTTP_POST) { cJSON *body = api_body(req); if (!body) { return ESP_OK; } char nid[16]; api_add(coll, body, nid, sizeof(nid)); store_save(coll); if (groups_change) { engine_groups_changed(); } cJSON *o = cJSON_CreateObject(); cJSON_AddItemReferenceToObject(o, nid, body); return api_json(req, "201 Created", o, true); } return api_error(req, "405 Method Not Allowed", "method not allowed"); } cJSON *rec = cJSON_GetObjectItem(all, id); if (!rec || (is_presets && !api_preset_in_profile(rec))) { return api_error(req, "404 Not Found", "not found"); } switch (method) { case HTTP_GET: return api_json(req, "200 OK", rec, false); case HTTP_PUT: { cJSON *body = api_body(req); if (!body) { return ESP_OK; } api_merge(rec, body); cJSON_Delete(body); store_save(coll); if (groups_change) { engine_groups_changed(); } return api_json(req, "200 OK", rec, false); } case HTTP_DELETE: { cJSON_DeleteItemFromObject(all, id); store_save(coll); if (groups_change) { engine_groups_changed(); } return api_message(req, "200 OK", "Deleted"); } default: 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) { 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 api_json(req, "200 OK", store_settings(), false); } if (n == 2 && strcmp(seg[1], "settings") == 0 && req->method == HTTP_PUT) { return put_settings(req); } 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) { api_seg_t seg; int n = api_split(req->uri, seg); if (n != 2 || !store_known(seg[1])) { return api_error(req, "404 Not Found", "unknown collection"); } if (req->method == HTTP_GET) { return api_json(req, "200 OK", store_coll(seg[1]), false); } if (req->method == HTTP_PUT) { cJSON *body = api_body(req); if (!body) { return ESP_OK; } if (store_replace(seg[1], body) != ESP_OK) { 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 api_json(req, "200 OK", o, true); } return api_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) /* ------------------------------------------------------------------ tests */ // Bench tests: /test/loss and /test/beats static esp_err_t test_handler_inner(httpd_req_t *req) { 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 = api_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 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 = api_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 api_error(req, "400 Bad Request", "bpm must be 30-300"); } } return api_json(req, "200 OK", bench_results(), true); } 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*", }; 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; }