#include "api.h" #include #include #include #include #include "api_util.h" #include "cJSON.h" #include "esp_log.h" #include "esp_timer.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "bench.h" #include "bridge.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 */ // Time spent printing JSON and sending the reply for the current request (the httpd task handles // one request at a time), reported by the LOCKED wrapper's log line static int64_t s_print_us, s_send_us; esp_err_t api_json(httpd_req_t *req, const char *status, cJSON *obj, bool own) { int64_t t0 = esp_timer_get_time(); char *s = cJSON_PrintUnformatted(obj); s_print_us += esp_timer_get_time() - t0; 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"); int64_t t1 = esp_timer_get_time(); esp_err_t ret = httpd_resp_send(req, s, HTTPD_RESP_USE_STRLEN); s_send_us += esp_timer_get_time() - t1; 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) { if (bundles_route(req, n, seg, ret)) { // //import and //export return true; } 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 }, { "groups", groups_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) { 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 (!cJSON_IsBool(cJSON_GetObjectItem(st, "ap_enabled"))) { api_set(st, "ap_enabled", cJSON_CreateBool(true)); 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; } static const struct { const char *key; int lo, hi; const char *err; } INTS[] = { { "wifi_channel", 1, 11, "wifi_channel must be an integer between 1 and 11" }, { "global_brightness", 0, 255, "global_brightness must be between 0 and 255" }, { "audio_beat_phase_ms", 0, 500, "audio_beat_phase_ms must be between 0 and 500" }, { "audio_input_volume", 0, 200, "audio_input_volume must be between 0 and 200" }, }; const char *bad = NULL; for (size_t i = 0; i < sizeof(INTS) / sizeof(INTS[0]) && !bad; i++) { const cJSON *v = cJSON_GetObjectItem(body, INTS[i].key); if (v && !cJSON_IsNull(v) && !int_in(v, INTS[i].lo, INTS[i].hi)) { bad = INTS[i].err; } } const cJSON *ap = cJSON_GetObjectItem(body, "ap_enabled"); if (ap && !cJSON_IsBool(ap)) { bad = "ap_enabled must be true or false"; } const cJSON *pw = cJSON_GetObjectItem(body, "ap_password"); if (!bad && pw && !cJSON_IsNull(pw) && !(cJSON_IsString(pw) && (!pw->valuestring[0] || (strlen(pw->valuestring) >= 8 && strlen(pw->valuestring) <= 63)))) { bad = "ap_password must be empty (open) or 8 to 63 characters"; } const cJSON *br = cJSON_GetObjectItem(body, "bridge"); if (!bad && br && !cJSON_IsNull(br) && !(cJSON_IsString(br) && strlen(br->valuestring) < 64)) { bad = "bridge must be \"host:port\", empty or null"; } const cJSON *brs = cJSON_GetObjectItem(body, "bridges"); if (!bad && brs && !cJSON_IsNull(brs) && !(cJSON_IsArray(brs) && cJSON_GetArraySize(brs) <= BRIDGE_MAX_LINKS)) { bad = "bridges must be a list of up to 8 addresses"; } const cJSON *sw = cJSON_GetObjectItem(body, "sequence_switch_wait"); if (!bad && sw && !cJSON_IsNull(sw) && !(cJSON_IsString(sw) && (!strcasecmp(sw->valuestring, "beat") || !strcasecmp(sw->valuestring, "downbeat")))) { bad = "sequence_switch_wait must be beat or downbeat"; } if (bad) { cJSON_Delete(body); return api_error(req, "400 Bad Request", bad); } const cJSON *bpm = cJSON_GetObjectItem(body, "audio_simulated_bpm"); if (bpm && !cJSON_IsNull(bpm)) { // clamped to the BPM range, like main's clamp_bpm double v = cJSON_IsNumber(bpm) ? bpm->valuedouble : (cJSON_IsString(bpm) ? strtod(bpm->valuestring, NULL) : 120); api_set(body, "audio_simulated_bpm", cJSON_CreateNumber((int)(v < 60 ? 60 : (v > 200 ? 200 : v)))); } // global_brightness is only stored: the UI pushes each driver its combined brightness // (POST /devices//brightness, /groups//brightness) api_merge(store_settings(), body); cJSON_Delete(body); store_save("settings"); return api_message(req, "200 OK", "Settings updated successfully"); } // The bridges the controller sends its ESP-NOW frames to (USB boards, network boards, the simulator). // GET /settings/bridge: {supported, bridges: [{addr, kind, status}], ports}. // PUT /settings/bridge: {bridges: [addr, ...]} sets the whole list; {addr, channel} sets a board's channel. // Both apply at once on the host; a device reads the list at the next restart. static esp_err_t bridge_get(httpd_req_t *req) { char links[1536], ports[512]; bridge_status_json(links, sizeof(links)); bridge_ports_json(ports, sizeof(ports)); cJSON *out = cJSON_CreateObject(); #if CONFIG_IDF_TARGET_LINUX cJSON_AddBoolToObject(out, "supported", true); #else cJSON_AddBoolToObject(out, "supported", false); #endif cJSON_AddItemToObject(out, "bridges", cJSON_Parse(links)); cJSON_AddItemToObject(out, "ports", cJSON_Parse(ports)); return api_json(req, "200 OK", out, true); } // Save the list the running bridges actually have (a bridge that failed to open is not kept) static void bridge_store(void) { char addrs[BRIDGE_MAX_LINKS][BRIDGE_ADDR_MAX]; size_t n = bridge_list(addrs, BRIDGE_MAX_LINKS); cJSON *list = cJSON_CreateArray(); for (size_t i = 0; i < n; i++) { cJSON_AddItemToArray(list, cJSON_CreateString(addrs[i])); } cJSON *patch = cJSON_CreateObject(); cJSON_AddItemToObject(patch, "bridges", list); cJSON_AddStringToObject(patch, "bridge", n ? addrs[0] : ""); api_merge(store_settings(), patch); cJSON_Delete(patch); store_save("settings"); } static esp_err_t bridge_put(httpd_req_t *req) { #if !CONFIG_IDF_TARGET_LINUX return api_error(req, "404 Not Found", "the bridges are set in the controller settings on this build"); #endif cJSON *body = api_body(req); if (!body) { return ESP_OK; } const cJSON *list = cJSON_GetObjectItem(body, "bridges"); const cJSON *addr = cJSON_GetObjectItem(body, "addr"); const cJSON *ch = cJSON_GetObjectItem(body, "channel"); const char *bad = NULL; if (!list && !(addr && ch)) { bad = "send bridges (a list), or addr and channel"; } else if (list && !cJSON_IsArray(list)) { bad = "bridges must be a list of addresses"; } else if (list && cJSON_GetArraySize(list) > BRIDGE_MAX_LINKS) { bad = "too many bridges"; } else if (addr && !cJSON_IsString(addr)) { bad = "addr must be a board port (/dev/...) or host:port"; } else if (ch && !(cJSON_IsNumber(ch) && ch->valueint >= 1 && ch->valueint <= 13)) { bad = "channel must be 1 to 13"; } const cJSON *item = NULL; if (!bad && list) { cJSON_ArrayForEach(item, list) { if (!cJSON_IsString(item) || strlen(item->valuestring) >= BRIDGE_ADDR_MAX) { bad = "each bridge must be a board port (/dev/...), host:port or serial:/dev/..."; } } } if (bad) { cJSON_Delete(body); return api_error(req, "400 Bad Request", bad); } if (list) { char addrs[BRIDGE_MAX_LINKS][BRIDGE_ADDR_MAX]; size_t n = 0; cJSON_ArrayForEach(item, list) { snprintf(addrs[n], BRIDGE_ADDR_MAX, "%s", item->valuestring); n++; } esp_err_t err = espnow_tx_change_bridges(addrs, n); bridge_store(); if (err != ESP_OK) { cJSON_Delete(body); return api_error(req, "400 Bad Request", "one of the bridges could not be opened (the others are running)"); } } if (addr && ch) { // A board just switched in answers its INFO a moment later: wait up to 3 s for it before giving up esp_err_t err = ESP_OK; for (int tries = 0; tries < 30; tries++) { err = bridge_board_set_channel(addr->valuestring, (uint8_t)ch->valueint); if (err != ESP_ERR_INVALID_STATE) { break; } vTaskDelay(pdMS_TO_TICKS(100)); } if (err != ESP_OK) { cJSON_Delete(body); return api_error(req, "400 Bad Request", err == ESP_ERR_INVALID_STATE ? "the board did not answer, so its channel was not set" : "no running bridge board has that address"); } } cJSON_Delete(body); return api_message(req, "200 OK", "Bridges updated"); } 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 == 2 && strcmp(seg[1], "editor") == 0 && req->method == HTTP_GET) { return web_send_page(req, "settings_editor.html"); } if (n == 1 && req->method == HTTP_GET) { return api_json(req, "200 OK", store_settings(), false); } if (n == 2 && strcmp(seg[1], "bridge") == 0 && req->method == HTTP_GET) { return bridge_get(req); } if (n == 2 && strcmp(seg[1], "bridge") == 0 && req->method == HTTP_PUT) { return bridge_put(req); } if (req->method == HTTP_PUT && (n == 1 || (n == 2 && strcmp(seg[1], "settings") == 0))) { 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"); } static void log_timing(httpd_req_t *req, int64_t lock_us, int64_t handle_us) { ESP_LOGI("http", "%s %s: lock %.1f ms, handle %.1f ms = build %.1f + print %.1f + send %.1f", req->method == HTTP_GET ? "GET" : req->method == HTTP_PUT ? "PUT" : req->method == HTTP_POST ? "POST" : "DEL", req->uri, lock_us / 1000.0, handle_us / 1000.0, (handle_us - s_print_us - s_send_us) / 1000.0, s_print_us / 1000.0, s_send_us / 1000.0); } // Logs how long each request took: waiting for the store lock, then the handler, split into // building the data, printing JSON and sending (send includes the radio/TCP hand-off) #define LOCKED(name) \ static esp_err_t name(httpd_req_t *req) \ { \ int64_t t0 = esp_timer_get_time(); \ store_lock(); \ int64_t t1 = esp_timer_get_time(); \ s_print_us = s_send_us = 0; \ esp_err_t r = name##_inner(req); \ int64_t t2 = esp_timer_get_time(); \ store_unlock(); \ log_timing(req, t1 - t0, t2 - t1); \ 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) { store_lock(); api_settings_defaults(); api_seed_defaults(); api_migrate_sequences(); api_migrate_zones(); api_migrate_groups(); store_unlock(); 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; }