/* * SPDX-License-Identifier: Apache-2.0 */ #include #include #include #include "cJSON.h" #include "esp_http_client.h" #include "mdns.h" #include "esp_http_server.h" #include "esp_log.h" #include "esp_netif.h" #include "esp_timer.h" #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include #include #include "esp_wifi.h" #include "net.h" #include "ota.h" #include "ddp.h" #include "patterns.h" #include "effects.h" #include "presets.h" #include "settings.h" #include "web.h" #include "ws_client.h" static const char *TAG = "web"; // Files embedded from web/ (see main/CMakeLists.txt EMBED_TXTFILES) extern const char index_html_start[] asm("_binary_index_html_start"); extern const char index_html_end[] asm("_binary_index_html_end"); extern const char app_js_start[] asm("_binary_app_js_start"); extern const char app_js_end[] asm("_binary_app_js_end"); extern const char style_css_start[] asm("_binary_style_css_start"); extern const char style_css_end[] asm("_binary_style_css_end"); static httpd_handle_t s_server; #define MAX_BODY 1024 #define MAX_SCAN 20 static esp_err_t send_embedded(httpd_req_t *req, const char *type, const char *start, const char *end) { httpd_resp_set_type(req, type); httpd_resp_set_hdr(req, "Cache-Control", "no-cache"); // EMBED_TXTFILES includes the file's terminating NUL; don't send it size_t len = end - start; if (len > 0 && start[len - 1] == '\0') { len--; } return httpd_resp_send(req, start, len); } // True for http://, http://.local and localhost, with an optional port. // Pages on the internet are refused, so only the LAN and this computer can read the API cross-origin. static bool origin_is_lan(const char *o) { static const char prefix[] = "http://"; if (strncmp(o, prefix, sizeof(prefix) - 1) != 0) { return false; } char host[64]; const char *p = o + sizeof(prefix) - 1; size_t n = 0; while (p[n] && p[n] != ':') { if (n + 1 >= sizeof(host)) { return false; } host[n] = p[n]; n++; } host[n] = '\0'; if (p[n] == ':') { // port: digits only for (const char *q = p + n + 1; *q; q++) { if (*q < '0' || *q > '9') { return false; } } } if (n == 0) { return false; } if (strcmp(host, "localhost") == 0) { return true; } size_t len = strlen(host); if (len > 6 && strcmp(host + len - 6, ".local") == 0) { for (size_t i = 0; i < len - 6; i++) { char c = host[i]; bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '.'; if (!ok) { return false; } } return true; } unsigned a, b, c, d; char extra; if (sscanf(host, "%u.%u.%u.%u%c", &a, &b, &c, &d, &extra) != 4) { return false; } for (const char *q = host; *q; q++) { if (!((*q >= '0' && *q <= '9') || *q == '.')) { return false; } } if (a > 255 || b > 255 || c > 255 || d > 255) { return false; } return a == 10 || (a == 192 && b == 168) || (a == 172 && b >= 16 && b <= 31); } void web_allow_lan_origin(httpd_req_t *req) { // The httpd server runs one handler at a time, and the header keeps a pointer to this buffer // until the reply is sent, so a static buffer is safe here. static char origin[96]; if (httpd_req_get_hdr_value_str(req, "Origin", origin, sizeof(origin)) != ESP_OK) { return; } if (!origin_is_lan(origin)) { return; } httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", origin); httpd_resp_set_hdr(req, "Vary", "Origin"); } // One API call, from an HTTP request or from a WebSocket message. Handlers use only the helpers // below, so the same handler serves both. typedef struct { httpd_req_t *http; // the HTTP request, or NULL for a WebSocket call const char *body; // WebSocket call: the request body text const char *query; // WebSocket call: the query string after '?', or "" char *out; // WebSocket call: the reply text is written here size_t out_cap; int status; // WebSocket call: the reply's status code } api_req_t; typedef esp_err_t (*api_fn_t)(api_req_t *req); // Send a JSON reply. status is a status line such as "200 OK". static esp_err_t send_text(api_req_t *req, const char *status, const char *text) { if (req->http) { web_allow_lan_origin(req->http); httpd_resp_set_status(req->http, status); httpd_resp_set_type(req->http, "application/json"); return httpd_resp_sendstr(req->http, text); } req->status = atoi(status); snprintf(req->out, req->out_cap, "%s", text); return ESP_OK; } static esp_err_t send_json(api_req_t *req, cJSON *obj) { char *s = cJSON_PrintUnformatted(obj); cJSON_Delete(obj); if (!s) { return send_text(req, "500 Internal Server Error", "{\"error\":\"out of memory\"}"); } esp_err_t err = send_text(req, "200 OK", s); cJSON_free(s); return err; } static esp_err_t send_error(api_req_t *req, const char *status, const char *msg) { cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "error", msg); char *s = cJSON_PrintUnformatted(o); cJSON_Delete(o); esp_err_t err = send_text(req, status, s ? s : "{}"); cJSON_free(s); return err; } // Read the request body into buf (NUL-terminated). False if missing, too big or unreadable. static bool read_body(api_req_t *req, char *buf, size_t cap) { if (!req->http) { size_t n = req->body ? strlen(req->body) : 0; if (n == 0 || n >= cap) { return false; } memcpy(buf, req->body, n + 1); return true; } int len = req->http->content_len; if (len <= 0 || (size_t)len >= cap) { return false; } int got = 0; while (got < len) { int r = httpd_req_recv(req->http, buf + got, len - got); if (r <= 0) { return false; } got += r; } buf[got] = '\0'; return true; } // Read a JSON body; NULL (no reply sent) if missing, too big or not JSON. Caller frees with cJSON_Delete. static cJSON *read_json(api_req_t *req) { char body[MAX_BODY]; if (!read_body(req, body, sizeof(body))) { return NULL; } return cJSON_Parse(body); } // GET / , /app.js , /style.css static esp_err_t index_get(httpd_req_t *req) { return send_embedded(req, "text/html", index_html_start, index_html_end); } static esp_err_t app_js_get(httpd_req_t *req) { return send_embedded(req, "application/javascript", app_js_start, app_js_end); } static esp_err_t style_css_get(httpd_req_t *req) { return send_embedded(req, "text/css", style_css_start, style_css_end); } // GET /api/status : the running preset (same fields as a preset), plus device and network state static esp_err_t status_get(api_req_t *req) { preset_t p; patterns_get(&p); char ap[16], ip[16]; net_ap_ssid(ap, sizeof(ap)); bool up = net_sta_status(ip, sizeof(ip)); net_cfg_t n; settings_load_net(&n); cJSON *o = preset_to_json(&p); cJSON_AddStringToObject(o, "ap_ssid", ap); cJSON_AddBoolToObject(o, "ap_on", net_ap_on()); cJSON_AddStringToObject(o, "hostname", n.hostname); cJSON_AddBoolToObject(o, "sta_connected", up); cJSON_AddStringToObject(o, "sta_ip", ip); cJSON_AddStringToObject(o, "selected", presets_selected()); cJSON_AddNumberToObject(o, "global_brightness", patterns_get_global()); cJSON_AddNumberToObject(o, "master_brightness", patterns_get_master()); cJSON *modes = cJSON_AddArrayToObject(o, "patterns"); for (int i = 0; i < patterns_count(); i++) { cJSON_AddItemToArray(modes, cJSON_CreateString(patterns_name(i))); } return send_json(req, o); } // POST /api/pattern : change the running settings. Fields missing from the body keep their value. static esp_err_t pattern_post(api_req_t *req) { cJSON *in = read_json(req); if (!in) { return send_error(req, "400 Bad Request", "empty, too large or invalid JSON"); } preset_t p; patterns_get(&p); bool ok = preset_from_json(in, &p); cJSON_Delete(in); if (!ok) { return send_error(req, "400 Bad Request", "unknown pattern"); } patterns_set(p); return send_json(req, cJSON_CreateObject()); } // GET /api/wifi : saved client SSID and connection state static esp_err_t wifi_get(api_req_t *req) { wifi_creds_t c = {}; settings_load_wifi(&c); char ip[16]; bool up = net_sta_status(ip, sizeof(ip)); cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "ssid", c.ssid); cJSON_AddBoolToObject(o, "connected", up); cJSON_AddStringToObject(o, "ip", ip); return send_json(req, o); } // POST /api/wifi {"ssid","password"} : save and connect static esp_err_t wifi_post(api_req_t *req) { char body[MAX_BODY]; if (!read_body(req, body, sizeof(body))) { return send_error(req, "400 Bad Request", "empty or too large body"); } cJSON *in = cJSON_Parse(body); if (!in) { return send_error(req, "400 Bad Request", "invalid JSON"); } cJSON *ssid = cJSON_GetObjectItem(in, "ssid"); cJSON *pass = cJSON_GetObjectItem(in, "password"); const char *pw = cJSON_IsString(pass) ? pass->valuestring : ""; if (!cJSON_IsString(ssid) || !ssid->valuestring[0] || strlen(ssid->valuestring) > 32) { cJSON_Delete(in); return send_error(req, "400 Bad Request", "SSID must be 1-32 characters"); } size_t plen = strlen(pw); if (plen > 0 && (plen < 8 || plen > 64)) { cJSON_Delete(in); return send_error(req, "400 Bad Request", "password must be empty or 8-64 characters"); } wifi_creds_t c = {}; strncpy(c.ssid, ssid->valuestring, sizeof(c.ssid) - 1); strncpy(c.pass, pw, sizeof(c.pass) - 1); cJSON_Delete(in); esp_err_t err = net_sta_connect(&c); if (err != ESP_OK) { ESP_LOGW(TAG, "Connect to %s failed: %s", c.ssid, esp_err_to_name(err)); return send_error(req, "500 Internal Server Error", esp_err_to_name(err)); } cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "message", "saved; connecting"); return send_json(req, o); } // GET /api/wifi/scan : visible networks static esp_err_t wifi_scan_get(api_req_t *req) { static wifi_ap_record_t recs[MAX_SCAN]; uint16_t count = MAX_SCAN; esp_err_t err = net_scan(recs, &count); if (err != ESP_OK) { return send_error(req, "500 Internal Server Error", esp_err_to_name(err)); } cJSON *arr = cJSON_CreateArray(); for (int i = 0; i < count; i++) { cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "ssid", (const char *)recs[i].ssid); cJSON_AddNumberToObject(o, "rssi", recs[i].rssi); cJSON_AddBoolToObject(o, "open", recs[i].authmode == WIFI_AUTH_OPEN); cJSON_AddItemToArray(arr, o); } cJSON *root = cJSON_CreateObject(); cJSON_AddItemToObject(root, "networks", arr); return send_json(req, root); } // A DNS label: 1-63 letters, digits or hyphens, not starting or ending with a hyphen static bool valid_hostname(const char *s) { size_t n = strlen(s); if (n == 0 || n > 63 || s[0] == '-' || s[n - 1] == '-') { return false; } for (size_t i = 0; i < n; i++) { char c = s[i]; bool ok = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-'; if (!ok) { return false; } } return true; } static bool valid_ipv4(const char *s) { esp_ip4_addr_t a; return s && s[0] && esp_netif_str_to_ip4(s, &a) == ESP_OK; } // GET /api/network : mDNS name and client address settings, with the current address static esp_err_t network_get(api_req_t *req) { net_cfg_t n; settings_load_net(&n); char ip[16]; bool up = net_sta_status(ip, sizeof(ip)); cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "hostname", n.hostname); cJSON_AddStringToObject(o, "mode", n.use_static ? "static" : "dhcp"); cJSON_AddStringToObject(o, "ip", n.ip); cJSON_AddStringToObject(o, "netmask", n.netmask); cJSON_AddStringToObject(o, "gateway", n.gateway); cJSON_AddStringToObject(o, "dns", n.dns); cJSON_AddBoolToObject(o, "connected", up); cJSON_AddStringToObject(o, "current_ip", ip); cJSON_AddBoolToObject(o, "ap_enabled", n.ap_enabled); char ap_name[33]; net_ap_ssid(ap_name, sizeof(ap_name)); cJSON_AddStringToObject(o, "ap_ssid", ap_name); // the name in use now cJSON_AddBoolToObject(o, "ap_ssid_custom", n.ap_ssid[0] != '\0'); cJSON_AddBoolToObject(o, "ap_password_set", strlen(n.ap_pass) >= 8); // the password itself is never sent cJSON_AddBoolToObject(o, "ddp_enabled", n.ddp_enabled); return send_json(req, o); } // POST /api/network {"hostname","mode":"dhcp"|"static","ip","netmask","gateway","dns"} // Missing fields keep their current value. Saves, applies and reconnects the client. static esp_err_t network_post(api_req_t *req) { cJSON *in = read_json(req); if (!in) { return send_error(req, "400 Bad Request", "empty, too large or invalid JSON"); } net_cfg_t n; settings_load_net(&n); cJSON *h = cJSON_GetObjectItem(in, "hostname"); if (cJSON_IsString(h)) { char name[64]; strncpy(name, h->valuestring, sizeof(name) - 1); name[sizeof(name) - 1] = '\0'; for (char *p = name; *p; p++) { if (*p >= 'A' && *p <= 'Z') *p = *p - 'A' + 'a'; } if (!valid_hostname(name)) { cJSON_Delete(in); return send_error(req, "400 Bad Request", "hostname: 1-63 letters, digits or hyphens"); } strncpy(n.hostname, name, sizeof(n.hostname) - 1); } cJSON *mode = cJSON_GetObjectItem(in, "mode"); if (cJSON_IsString(mode)) { if (strcmp(mode->valuestring, "static") == 0) { n.use_static = true; } else if (strcmp(mode->valuestring, "dhcp") == 0) { n.use_static = false; } else { cJSON_Delete(in); return send_error(req, "400 Bad Request", "mode must be dhcp or static"); } } struct { const char *key; char *dst; size_t len; } fields[] = { { "ip", n.ip, sizeof(n.ip) }, { "netmask", n.netmask, sizeof(n.netmask) }, { "gateway", n.gateway, sizeof(n.gateway) }, { "dns", n.dns, sizeof(n.dns) }, }; for (auto &f : fields) { cJSON *v = cJSON_GetObjectItem(in, f.key); if (cJSON_IsString(v)) { strncpy(f.dst, v->valuestring, f.len - 1); f.dst[f.len - 1] = '\0'; } } cJSON *ap = cJSON_GetObjectItem(in, "ap_enabled"); if (cJSON_IsBool(ap)) { n.ap_enabled = cJSON_IsTrue(ap); } // Access point name: empty goes back to led-XXXXXX. Password: empty is open, else 8-63 characters. cJSON *apn = cJSON_GetObjectItem(in, "ap_ssid"); if (cJSON_IsString(apn)) { if (strlen(apn->valuestring) > 32) { cJSON_Delete(in); return send_error(req, "400 Bad Request", "ap_ssid: up to 32 characters, or empty for the default name"); } snprintf(n.ap_ssid, sizeof(n.ap_ssid), "%s", apn->valuestring); } cJSON *app = cJSON_GetObjectItem(in, "ap_password"); if (cJSON_IsString(app)) { const size_t plen = strlen(app->valuestring); if (plen != 0 && (plen < 8 || plen > 63)) { cJSON_Delete(in); return send_error(req, "400 Bad Request", "ap_password: empty (open) or 8-63 characters"); } snprintf(n.ap_pass, sizeof(n.ap_pass), "%s", app->valuestring); } cJSON *ddp = cJSON_GetObjectItem(in, "ddp_enabled"); if (cJSON_IsBool(ddp)) { n.ddp_enabled = cJSON_IsTrue(ddp); ddp_set_enabled(n.ddp_enabled); } cJSON_Delete(in); if (n.use_static) { if (!valid_ipv4(n.ip) || !valid_ipv4(n.netmask) || !valid_ipv4(n.gateway)) { return send_error(req, "400 Bad Request", "static mode needs ip, netmask and gateway as IPv4 addresses"); } if (n.dns[0] && !valid_ipv4(n.dns)) { return send_error(req, "400 Bad Request", "dns must be an IPv4 address or empty"); } } esp_err_t err = net_save_network(&n); if (err == ESP_ERR_INVALID_STATE) { return send_error(req, "400 Bad Request", "connect to a Wi-Fi network before turning the access point off"); } if (err != ESP_OK) { ESP_LOGW(TAG, "Network apply failed: %s", esp_err_to_name(err)); return send_error(req, "500 Internal Server Error", esp_err_to_name(err)); } // With a static address the page's current address changes, so say where to go next char addr[80]; if (n.use_static) { snprintf(addr, sizeof(addr), "%s", n.ip); } else { snprintf(addr, sizeof(addr), "%s.local", n.hostname); } cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "message", "saved; reconnecting"); cJSON_AddStringToObject(o, "address", addr); return send_json(req, o); } // ---- presets ----------------------------------------------------------------------------------- // ---- LED strip hardware ------------------------------------------------------------------------ static bool valid_order(const char *s) { if (strlen(s) != 3) return false; bool seen[3] = { false, false, false }; for (int i = 0; i < 3; i++) { int k = s[i] == 'r' ? 0 : (s[i] == 'g' ? 1 : (s[i] == 'b' ? 2 : -1)); if (k < 0 || seen[k]) return false; seen[k] = true; } return true; } // GPIOs that can drive the strip on the ESP32-C3: not the flash (11-17) or the USB (18, 19) static bool valid_pin(int pin) { return (pin >= 0 && pin <= 10) || pin == 20 || pin == 21; } // GET /api/hardware : LED strip settings static esp_err_t hardware_get(api_req_t *req) { hw_cfg_t hw; settings_load_hw(&hw); cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "rgb_order", hw.order); cJSON_AddNumberToObject(o, "max_brightness", hw.max_brightness); cJSON_AddNumberToObject(o, "num_leds", hw.num_leds); cJSON_AddNumberToObject(o, "pin", hw.pin); return send_json(req, o); } // POST /api/hardware {"rgb_order","max_brightness":0-255,"num_leds":1-512}. Missing fields keep their value. static esp_err_t hardware_post(api_req_t *req) { cJSON *in = read_json(req); if (!in) { return send_error(req, "400 Bad Request", "empty, too large or invalid JSON"); } hw_cfg_t hw; settings_load_hw(&hw); cJSON *v = cJSON_GetObjectItem(in, "rgb_order"); if (cJSON_IsString(v)) { char order[4]; for (int i = 0; i < 3; i++) order[i] = (char)(v->valuestring[i] >= 'A' && v->valuestring[i] <= 'Z' ? v->valuestring[i] + 32 : v->valuestring[i]); order[3] = '\0'; if (!valid_order(order)) { cJSON_Delete(in); return send_error(req, "400 Bad Request", "rgb_order must be rgb, rbg, grb, gbr, brg or bgr"); } strncpy(hw.order, order, sizeof(hw.order)); } v = cJSON_GetObjectItem(in, "max_brightness"); if (cJSON_IsNumber(v)) { if (v->valueint < 0 || v->valueint > 255) { cJSON_Delete(in); return send_error(req, "400 Bad Request", "max_brightness must be 0-255"); } hw.max_brightness = (uint8_t)v->valueint; } v = cJSON_GetObjectItem(in, "num_leds"); if (cJSON_IsNumber(v)) { if (v->valueint < 1 || v->valueint > FX_LEDS_MAX) { cJSON_Delete(in); return send_error(req, "400 Bad Request", "num_leds must be 1-512"); } hw.num_leds = v->valueint; } v = cJSON_GetObjectItem(in, "pin"); if (cJSON_IsNumber(v)) { if (!valid_pin(v->valueint)) { cJSON_Delete(in); return send_error(req, "400 Bad Request", "pin must be 0-10 or 20-21 (not 11-19, which the flash and USB use)"); } hw.pin = v->valueint; } cJSON_Delete(in); esp_err_t err = patterns_set_hardware(hw); if (err != ESP_OK) { return send_error(req, "500 Internal Server Error", esp_err_to_name(err)); } err = settings_save_hw(&hw); if (err != ESP_OK) { return send_error(req, "500 Internal Server Error", esp_err_to_name(err)); } cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "message", "saved"); return send_json(req, o); } // GET /api/ddp[?led=N] : DDP receiver state, and the colour shown on LED N (for checks) static esp_err_t ddp_get(api_req_t *req) { bool active; uint32_t packets; patterns_ddp_status(&active, &packets); int led = 0; char q[32] = ""; if (req->http) { httpd_req_get_url_query_str(req->http, q, sizeof(q)); } else { snprintf(q, sizeof(q), "%s", req->query); } char v[8]; if (httpd_query_key_value(q, "led", v, sizeof(v)) == ESP_OK) { led = atoi(v); } uint8_t px[3]; patterns_shown_pixel(led, px); cJSON *o = cJSON_CreateObject(); cJSON_AddBoolToObject(o, "active", active); cJSON_AddNumberToObject(o, "packets", packets); cJSON_AddNumberToObject(o, "port", DDP_PORT); patterns_ddp_debug_t dbg; patterns_ddp_debug(&dbg); cJSON *sy = cJSON_AddObjectToObject(o, "sync"); cJSON_AddNumberToObject(sy, "port", DDP_SYNC_PORT); cJSON_AddNumberToObject(sy, "syncs", dbg.syncs); cJSON_AddNumberToObject(sy, "seq", dbg.sync_seq); cJSON_AddNumberToObject(sy, "age_ms", dbg.sync_age_ms == UINT32_MAX ? -1 : (double)dbg.sync_age_ms); cJSON_AddNumberToObject(sy, "frames", dbg.frames); cJSON_AddNumberToObject(sy, "shown", dbg.shown); cJSON_AddBoolToObject(sy, "held", dbg.held); cJSON_AddNumberToObject(o, "led", led); cJSON *px_arr = cJSON_AddArrayToObject(o, "rgb"); for (int i = 0; i < 3; i++) { cJSON_AddItemToArray(px_arr, cJSON_CreateNumber(px[i])); } return send_json(req, o); } // POST /api/presets/order {"names":[...]} : the presets' order on the front page static esp_err_t presets_order_post(api_req_t *req) { cJSON *in = read_json(req); if (!in) { return send_error(req, "400 Bad Request", "empty, too large or invalid JSON"); } cJSON *arr = cJSON_GetObjectItem(in, "names"); if (!cJSON_IsArray(arr)) { cJSON_Delete(in); return send_error(req, "400 Bad Request", "names must be a list"); } const char *names[PRESETS_MAX]; size_t n = 0; cJSON *item; cJSON_ArrayForEach(item, arr) { if (n < PRESETS_MAX && cJSON_IsString(item)) { names[n++] = item->valuestring; } } presets_set_order(names, n); cJSON_Delete(in); cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "message", "saved"); return send_json(req, o); } // POST /api/presets/defaults : add the default presets that are missing static esp_err_t presets_defaults_post(api_req_t *req) { cJSON *o = cJSON_CreateObject(); cJSON_AddNumberToObject(o, "added", presets_add_defaults()); return send_json(req, o); } // GET /api/presets static esp_err_t presets_get(api_req_t *req) { cJSON *o = cJSON_CreateObject(); cJSON *arr = cJSON_AddArrayToObject(o, "presets"); for (size_t i = 0; i < presets_count(); i++) { cJSON_AddItemToArray(arr, preset_to_json(presets_at(i))); } cJSON_AddStringToObject(o, "selected", presets_selected()); cJSON_AddStringToObject(o, "startup", presets_startup()); cJSON_AddNumberToObject(o, "max", PRESETS_MAX); return send_json(req, o); } // POST /api/brightness {"brightness":0-255} sets this device's level; {"master":0-255} sets its // master scale (sent to every device by "All devices"). Either or both, saved. // Returns NULL when applied, or the error message. static const char *brightness_apply(const cJSON *in) { const cJSON *v = cJSON_GetObjectItem(in, "brightness"); const cJSON *m = cJSON_GetObjectItem(in, "master"); if (!v && !m) { return "send brightness and/or master"; } if ((v && (!cJSON_IsNumber(v) || v->valueint < 0 || v->valueint > 255)) || (m && (!cJSON_IsNumber(m) || m->valueint < 0 || m->valueint > 255))) { return "brightness and master must be 0-255"; } hw_cfg_t hw; settings_load_hw(&hw); if (v) { hw.global_brightness = (uint8_t)v->valueint; patterns_set_global(hw.global_brightness); } if (m) { hw.master_brightness = (uint8_t)m->valueint; patterns_set_master(hw.master_brightness); } settings_save_hw(&hw); return NULL; } static esp_err_t brightness_post(api_req_t *req) { cJSON *in = read_json(req); if (!in) { return send_error(req, "400 Bad Request", "empty, too large or invalid JSON"); } const char *err = brightness_apply(in); cJSON_Delete(in); if (err) { return send_error(req, "400 Bad Request", err); } cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "message", "saved"); return send_json(req, o); } // POST /api/presets : create or update by name. Missing fields take the running settings. static esp_err_t presets_post(api_req_t *req) { cJSON *in = read_json(req); if (!in) { return send_error(req, "400 Bad Request", "empty, too large or invalid JSON"); } cJSON *name = cJSON_GetObjectItem(in, "name"); if (!cJSON_IsString(name) || !name->valuestring[0] || strlen(name->valuestring) >= 32) { cJSON_Delete(in); return send_error(req, "400 Bad Request", "name must be 1-31 characters"); } preset_t pr; patterns_get(&pr); bool ok = preset_from_json(in, &pr); cJSON_Delete(in); if (!ok) { return send_error(req, "400 Bad Request", "unknown pattern"); } esp_err_t err = presets_save(&pr); if (err == ESP_ERR_NO_MEM) { return send_error(req, "400 Bad Request", "preset list is full"); } if (err != ESP_OK) { return send_error(req, "500 Internal Server Error", esp_err_to_name(err)); } cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "message", "saved"); return send_json(req, o); } // Shared body for select, delete and startup: {"name"} static esp_err_t preset_name_action(api_req_t *req, esp_err_t (*action)(const char *), const char *ok_msg) { cJSON *in = read_json(req); if (!in) { return send_error(req, "400 Bad Request", "empty, too large or invalid JSON"); } cJSON *name = cJSON_GetObjectItem(in, "name"); if (!cJSON_IsString(name)) { cJSON_Delete(in); return send_error(req, "400 Bad Request", "name is required"); } char buf[32]; strncpy(buf, name->valuestring, sizeof(buf) - 1); buf[sizeof(buf) - 1] = '\0'; cJSON_Delete(in); esp_err_t err = action(buf); if (err == ESP_ERR_NOT_FOUND) { return send_error(req, "404 Not Found", "no such preset"); } if (err != ESP_OK) { return send_error(req, "500 Internal Server Error", esp_err_to_name(err)); } cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "message", ok_msg); return send_json(req, o); } static esp_err_t select_post(api_req_t *req) { return preset_name_action(req, presets_select, "selected"); } static esp_err_t delete_post(api_req_t *req) { return preset_name_action(req, presets_delete, "deleted"); } static esp_err_t startup_post(api_req_t *req) { return preset_name_action(req, presets_set_startup, "startup set"); } static void add_uri(httpd_handle_t srv, const char *uri, httpd_method_t method, esp_err_t (*handler)(httpd_req_t *)) { httpd_uri_t u = { .uri = uri, .method = method, .handler = handler, .user_ctx = NULL, .is_websocket = false, .handle_ws_control_frames = false, .supported_subprotocol = NULL }; httpd_register_uri_handler(srv, &u); } // Host part of a relay target: letters, digits, dots, dashes and an optional :port. static bool relay_host_ok(const char *h) { size_t n = strlen(h); if (n == 0 || n > 80) { return false; } for (const char *p = h; *p; p++) { char c = *p; bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == ':'; if (!ok) { return false; } } return true; } // Only this driver's own API and its firmware info and reboot, so the relay cannot reach other services. static bool relay_path_ok(const char *p) { if (strcmp(p, "/ota") == 0 || strcmp(p, "/reboot") == 0) { return true; } if (strncmp(p, "/api/", 5) != 0 || strcmp(p, "/api/relay") == 0 || strlen(p) > 120) { return false; } return strstr(p, "..") == NULL && strchr(p, ' ') == NULL && strchr(p, '\r') == NULL && strchr(p, '\n') == NULL; } // Relay connections are kept open per peer, so a relayed request does not pay for a new TCP connection. // The HTTP server runs one task, so relay calls never overlap and the slots need no lock. #define RELAY_SLOTS 4 #define RELAY_TIMEOUT_MS 4000 struct relay_slot_t { char host[80]; esp_http_client_handle_t cl; }; static relay_slot_t s_relay[RELAY_SLOTS]; // The kept-open client for this host, pointed at url. A new slot evicts the oldest one. static esp_http_client_handle_t relay_client(const char *host, const char *url) { int slot = -1; for (int i = 0; i < RELAY_SLOTS; i++) { if (s_relay[i].cl && strcmp(s_relay[i].host, host) == 0) { slot = i; break; } } if (slot < 0) { slot = 0; for (int i = 0; i < RELAY_SLOTS; i++) { if (!s_relay[i].cl) { slot = i; break; } } if (s_relay[slot].cl) { esp_http_client_cleanup(s_relay[slot].cl); } esp_http_client_config_t cfg = {}; cfg.url = url; cfg.timeout_ms = RELAY_TIMEOUT_MS; cfg.keep_alive_enable = true; s_relay[slot].cl = esp_http_client_init(&cfg); snprintf(s_relay[slot].host, sizeof(s_relay[slot].host), "%s", host); return s_relay[slot].cl; } esp_http_client_set_url(s_relay[slot].cl, url); return s_relay[slot].cl; } // One request to a peer over its kept-open connection. A dead connection is dropped and retried once. static esp_err_t relay_do(const char *host, const char *url, bool is_post, const char *body, int body_len, int *status, char *out, int cap, int *got) { for (int attempt = 0; attempt < 2; attempt++) { const int64_t t0 = esp_timer_get_time(); esp_http_client_handle_t cl = relay_client(host, url); const int64_t t_client = esp_timer_get_time(); if (!cl) { return ESP_ERR_NO_MEM; } esp_http_client_set_method(cl, is_post ? HTTP_METHOD_POST : HTTP_METHOD_GET); esp_http_client_set_header(cl, "Content-Type", "text/plain"); esp_err_t err = esp_http_client_open(cl, is_post ? body_len : 0); const int64_t t_open = esp_timer_get_time(); if (err == ESP_OK && is_post && body_len > 0 && esp_http_client_write(cl, body, body_len) != body_len) { err = ESP_FAIL; } const int64_t t_write = esp_timer_get_time(); *got = 0; bool full = false; int fetch_rc = -1; if (err == ESP_OK) { fetch_rc = esp_http_client_fetch_headers(cl); } const int64_t t_headers = esp_timer_get_time(); ESP_LOGI(TAG, "relay %s attempt %d: client %lld us, open %lld us, write %lld us, headers %lld us (rc %d, err %d)", host, attempt, (long long)(t_client - t0), (long long)(t_open - t_client), (long long)(t_write - t_open), (long long)(t_headers - t_write), fetch_rc, (int)err); if (err == ESP_OK && fetch_rc >= 0) { *status = esp_http_client_get_status_code(cl); int r; while (*got < cap && (r = esp_http_client_read(cl, out + *got, cap - *got)) > 0) { *got += r; } ESP_LOGI(TAG, "relay %s body %d bytes read in %lld us", host, *got, (long long)(esp_timer_get_time() - t_headers)); full = *got >= cap; // more body than fits: keep what fits, and drop the connection if (!full) { return ESP_OK; } esp_http_client_close(cl); return ESP_OK; } // Failed before the answer: drop this connection and try once more esp_http_client_close(cl); } return ESP_FAIL; } // Calls to a peer go over a kept-open WebSocket (its /ws), not a new HTTP request each time. #define WS_SLOTS 4 struct ws_slot_t { char host[80]; // empty when the slot is free int fd; }; static ws_slot_t s_ws[WS_SLOTS]; static void ws_slot_drop(ws_slot_t *slot) { ws_client_close(slot->fd); slot->fd = -1; slot->host[0] = '\0'; } // Send msg to host's /ws and read the reply into reply. Reconnects once if the connection is dead. static bool ws_fast_call(const char *host, const char *msg, char *reply, size_t cap) { for (int attempt = 0; attempt < 2; attempt++) { ws_slot_t *slot = NULL; for (int i = 0; i < WS_SLOTS; i++) { if (s_ws[i].host[0] && strcmp(s_ws[i].host, host) == 0) { slot = &s_ws[i]; break; } } if (!slot) { for (int i = 0; i < WS_SLOTS && !slot; i++) { if (!s_ws[i].host[0]) { slot = &s_ws[i]; } } if (!slot) { slot = &s_ws[0]; ws_slot_drop(slot); } slot->fd = ws_client_connect(host, "/ws"); if (slot->fd < 0) { slot->host[0] = '\0'; return false; } snprintf(slot->host, sizeof(slot->host), "%s", host); } if (ws_client_send_text(slot->fd, msg, strlen(msg)) == ESP_OK && ws_client_recv_text(slot->fd, reply, cap) >= 0) { return true; } ws_slot_drop(slot); } return false; } // The reply to a relayed or WebSocket call: {"status": n, "body": "..."} static void envelope(char *out, size_t cap, int status, const char *body_text) { cJSON *env = cJSON_CreateObject(); cJSON_AddNumberToObject(env, "status", status); cJSON_AddStringToObject(env, "body", body_text); char *s = cJSON_PrintUnformatted(env); snprintf(out, cap, "%s", s ? s : "{}"); cJSON_free(s); cJSON_Delete(env); } // Call another driver's API. The peer's WebSocket is tried first (kept open, so it is fast); the HTTP // call is the fallback. out gets the envelope {"status": n, "body": "..."}. static void relay_forward(const char *host, const char *method, const char *path, const char *body, char *out, size_t cap) { if (!relay_host_ok(host) || !relay_path_ok(path) || (strcmp(method, "GET") != 0 && strcmp(method, "POST") != 0)) { envelope(out, cap, 400, "{\"error\":\"need host, method GET or POST, and a path under /api/\"}"); return; } const bool is_post = strcmp(method, "POST") == 0; const char *b = is_post ? body : ""; cJSON *m = cJSON_CreateObject(); cJSON_AddStringToObject(m, "method", method); cJSON_AddStringToObject(m, "path", path); cJSON_AddStringToObject(m, "body", b); char *msg = cJSON_PrintUnformatted(m); cJSON_Delete(m); bool ok = msg && ws_fast_call(host, msg, out, cap); // the peer's reply is already an envelope cJSON_free(msg); if (ok) { return; } char *buf = (char *)malloc(4096); if (!buf) { envelope(out, cap, 503, "{\"error\":\"out of memory\"}"); return; } char url[200]; snprintf(url, sizeof(url), "http://%s%s", host, path); int got = 0; int status = 0; if (relay_do(host, url, is_post, b, (int)strlen(b), &status, buf, 4095, &got) != ESP_OK) { envelope(out, cap, 502, "{\"error\":\"could not reach that device\"}"); } else { buf[got] = '\0'; envelope(out, cap, status, buf); } free(buf); } // POST /api/relay {"host": "10.1.1.50", "method": "GET" or "POST", "path": "/api/status", "body": "..."} // Kept for HTTP callers; the page itself sends relayed calls over the WebSocket. static esp_err_t relay_post(api_req_t *req) { char *in = (char *)malloc(2048); char *out = (char *)malloc(8192); if (!in || !out) { free(in); free(out); return send_error(req, "503 Service Unavailable", "out of memory"); } esp_err_t result; if (!read_body(req, in, 2048)) { result = send_error(req, "400 Bad Request", "empty, too large or invalid JSON"); } else { cJSON *top = cJSON_Parse(in); const cJSON *jh = top ? cJSON_GetObjectItem(top, "host") : NULL; const cJSON *jm = top ? cJSON_GetObjectItem(top, "method") : NULL; const cJSON *jp = top ? cJSON_GetObjectItem(top, "path") : NULL; const cJSON *jb = top ? cJSON_GetObjectItem(top, "body") : NULL; if (!cJSON_IsString(jh) || !cJSON_IsString(jm) || !cJSON_IsString(jp)) { cJSON_Delete(top); result = send_error(req, "400 Bad Request", "need host, method and path"); } else { relay_forward(jh->valuestring, jm->valuestring, jp->valuestring, cJSON_IsString(jb) ? jb->valuestring : "", out, 8192); cJSON_Delete(top); result = send_text(req, "200 OK", out); } } free(in); free(out); return result; } static esp_err_t devices_get(api_req_t *req) { cJSON *arr = cJSON_CreateArray(); mdns_result_t *res = NULL; if (mdns_query_ptr("_http", "_tcp", 1500, 30, &res) == ESP_OK && res) { for (mdns_result_t *r = res; r; r = r->next) { if (!r->hostname) { continue; } bool is_strip = false; for (size_t i = 0; i < r->txt_count && r->txt; i++) { if (r->txt[i].key && r->txt[i].value && strcmp(r->txt[i].key, "app") == 0 && strcmp(r->txt[i].value, "led-strip") == 0) { is_strip = true; } } if (!is_strip) { continue; } char ip[16] = ""; for (mdns_ip_addr_t *a = r->addr; a; a = a->next) { if (a->addr.type == ESP_IPADDR_TYPE_V4) { snprintf(ip, sizeof(ip), IPSTR, IP2STR(&a->addr.u_addr.ip4)); break; } } if (ip[0] == '\0') { continue; } bool seen = false; // one entry per address (a service can be listed twice) for (int i = 0; i < cJSON_GetArraySize(arr); i++) { const cJSON *ip_item = cJSON_GetObjectItem(cJSON_GetArrayItem(arr, i), "ip"); if (cJSON_IsString(ip_item) && strcmp(ip_item->valuestring, ip) == 0) { seen = true; } } if (seen) { continue; } char host[96]; snprintf(host, sizeof(host), "%s.local", r->hostname); cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "name", r->hostname); cJSON_AddStringToObject(o, "host", host); cJSON_AddStringToObject(o, "ip", ip); cJSON_AddItemToArray(arr, o); } } if (res) { mdns_query_results_free(res); } cJSON *top = cJSON_CreateObject(); cJSON_AddItemToObject(top, "devices", arr); return send_json(req, top); } // The server sends each response header as its own small write. With Nagle on, every write after the // first waits for the client's delayed ACK (hundreds of ms), so turn Nagle off on each new connection. static esp_err_t open_nodelay(httpd_handle_t hd, int sockfd) { (void)hd; int one = 1; setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); return ESP_OK; } // The JSON API. Each route answers an HTTP request and a WebSocket message alike. typedef struct { const char *path; httpd_method_t method; api_fn_t fn; } api_route_t; static const api_route_t s_api[] = { {"/api/status", HTTP_GET, status_get}, {"/api/pattern", HTTP_POST, pattern_post}, {"/api/wifi", HTTP_GET, wifi_get}, {"/api/wifi", HTTP_POST, wifi_post}, {"/api/wifi/scan", HTTP_GET, wifi_scan_get}, {"/api/network", HTTP_GET, network_get}, {"/api/network", HTTP_POST, network_post}, {"/api/ddp", HTTP_GET, ddp_get}, {"/api/hardware", HTTP_GET, hardware_get}, {"/api/hardware", HTTP_POST, hardware_post}, {"/api/presets", HTTP_GET, presets_get}, {"/api/presets", HTTP_POST, presets_post}, {"/api/presets/select", HTTP_POST, select_post}, {"/api/presets/delete", HTTP_POST, delete_post}, {"/api/presets/startup", HTTP_POST, startup_post}, {"/api/presets/defaults", HTTP_POST, presets_defaults_post}, {"/api/presets/order", HTTP_POST, presets_order_post}, {"/api/brightness", HTTP_POST, brightness_post}, {"/api/devices", HTTP_GET, devices_get}, {"/api/relay", HTTP_POST, relay_post}, }; // An HTTP request for a route: the route's function is kept in the URI's user_ctx. static esp_err_t api_http_entry(httpd_req_t *req) { api_req_t a = {}; a.http = req; return reinterpret_cast(req->user_ctx)(&a); } #define WS_MSG_MAX WEB_API_MSG_MAX #define WS_REPLY_MAX WEB_API_REPLY_MAX // Run an API route on this driver: target is the path, optionally with a query string. static void ws_local(const char *method, const char *target, const char *body, char *out, size_t cap) { char path[64]; const char *q = strchr(target, '?'); size_t n = q ? (size_t)(q - target) : strlen(target); if (n >= sizeof(path)) { envelope(out, cap, 404, "{\"error\":\"no such API path\"}"); return; } memcpy(path, target, n); path[n] = '\0'; for (size_t i = 0; i < sizeof(s_api) / sizeof(s_api[0]); i++) { const bool is_get = s_api[i].method == HTTP_GET; if (strcmp(s_api[i].path, path) == 0 && strcmp(method, is_get ? "GET" : "POST") == 0) { char *reply = (char *)malloc(WS_REPLY_MAX); if (!reply) { envelope(out, cap, 503, "{\"error\":\"out of memory\"}"); return; } reply[0] = '\0'; api_req_t a = {}; a.body = body; a.query = q ? q + 1 : ""; a.out = reply; a.out_cap = WS_REPLY_MAX; a.status = 200; s_api[i].fn(&a); if (reply[0] == '\0') { snprintf(reply, WS_REPLY_MAX, "{}"); } envelope(out, cap, a.status, reply); free(reply); return; } } envelope(out, cap, 404, "{\"error\":\"no such API path\"}"); } // A WebSocket request: {"method": "GET" or "POST", "path": "/api/...", "body": ""}, plus // "host" to have this driver relay it to that driver. The reply is the envelope {"status": n, "body": "..."}. static void ws_dispatch(const char *msg, char *out, size_t cap) { cJSON *top = cJSON_Parse(msg); const cJSON *jm = top ? cJSON_GetObjectItem(top, "method") : NULL; const cJSON *jp = top ? cJSON_GetObjectItem(top, "path") : NULL; const cJSON *jb = top ? cJSON_GetObjectItem(top, "body") : NULL; const cJSON *jh = top ? cJSON_GetObjectItem(top, "host") : NULL; if (!cJSON_IsString(jp)) { envelope(out, cap, 400, "{\"error\":\"need a path\"}"); cJSON_Delete(top); return; } const char *method = cJSON_IsString(jm) ? jm->valuestring : "GET"; char *owned = NULL; // body printed from a JSON object (a string is used as it is) const char *body = ""; if (cJSON_IsString(jb)) { body = jb->valuestring; } else if (jb) { owned = cJSON_PrintUnformatted(jb); body = owned ? owned : ""; } if (cJSON_IsString(jh) && jh->valuestring[0] != '\0') { relay_forward(jh->valuestring, method, jp->valuestring, body, out, cap); } else { ws_local(method, jp->valuestring, body, out, cap); } cJSON_free(owned); cJSON_Delete(top); } // A call from outside the HTTP server (the USB config port). It runs on the server's own task, so it // never races an HTTP or WebSocket handler (the preset list has no lock of its own). struct api_call_t { const char *msg; char *out; size_t cap; SemaphoreHandle_t done; }; static void api_call_work(void *arg) { api_call_t *c = static_cast(arg); ws_dispatch(c->msg, c->out, c->cap); xSemaphoreGive(c->done); } void web_api_call(const char *msg, char *out, size_t cap) { api_call_t c = { msg, out, cap, xSemaphoreCreateBinary() }; if (!s_server || !c.done) { envelope(out, cap, 503, "{\"error\":\"web server not running\"}"); } else if (httpd_queue_work(s_server, api_call_work, &c) != ESP_OK) { envelope(out, cap, 503, "{\"error\":\"server busy\"}"); } else { xSemaphoreTake(c.done, portMAX_DELAY); } if (c.done) { vSemaphoreDelete(c.done); } } // WebSocket handler: one text frame in, one text frame out // Another site's page must not drive this driver. A browser sends its Origin with the WebSocket // handshake, and only a page from the LAN (or this device) may open the socket. ESP-IDF has no hook // before the handshake reply, so the check runs right after it: a refused socket is closed before any // frame is read, so its messages are never dispatched. static esp_err_t ws_origin_check(httpd_req_t *req) { size_t origin_len = httpd_req_get_hdr_value_len(req, "Origin"); if (origin_len == 0) { return ESP_OK; // not a browser (no Origin): the device's own client, or a tool } char origin[128]; if (origin_len >= sizeof(origin) || httpd_req_get_hdr_value_str(req, "Origin", origin, sizeof(origin)) != ESP_OK || !origin_is_lan(origin)) { return ESP_FAIL; } return ESP_OK; } static esp_err_t ws_handler(httpd_req_t *req) { if (req->method == HTTP_GET) { return ws_origin_check(req); // the handshake is done } httpd_ws_frame_t frame = {}; frame.type = HTTPD_WS_TYPE_TEXT; esp_err_t err = httpd_ws_recv_frame(req, &frame, 0); if (err != ESP_OK) { return err; } if (frame.len == 0 || frame.len > WS_MSG_MAX) { return ESP_FAIL; } uint8_t *buf = (uint8_t *)malloc(frame.len + 1); char *reply = (char *)malloc(WS_REPLY_MAX); if (!buf || !reply) { free(buf); free(reply); return ESP_ERR_NO_MEM; } frame.payload = buf; err = httpd_ws_recv_frame(req, &frame, frame.len); if (err == ESP_OK) { buf[frame.len] = '\0'; ws_dispatch((const char *)buf, reply, WS_REPLY_MAX); httpd_ws_frame_t out = {}; out.type = HTTPD_WS_TYPE_TEXT; out.payload = (uint8_t *)reply; out.len = strlen(reply); err = httpd_ws_send_frame(req, &out); } free(buf); free(reply); return err; } esp_err_t web_start(void) { httpd_config_t cfg = HTTPD_DEFAULT_CONFIG(); cfg.max_uri_handlers = 30; cfg.stack_size = 8192; cfg.lru_purge_enable = true; cfg.max_open_sockets = 7; cfg.backlog_conn = 10; cfg.open_fn = open_nodelay; esp_err_t err = httpd_start(&s_server, &cfg); if (err != ESP_OK) { ESP_LOGE(TAG, "HTTP server start failed: %s", esp_err_to_name(err)); return err; } add_uri(s_server, "/", HTTP_GET, index_get); add_uri(s_server, "/app.js", HTTP_GET, app_js_get); add_uri(s_server, "/style.css", HTTP_GET, style_css_get); for (size_t i = 0; i < sizeof(s_api) / sizeof(s_api[0]); i++) { httpd_uri_t u = {}; u.uri = s_api[i].path; u.method = s_api[i].method; u.handler = api_http_entry; u.user_ctx = reinterpret_cast(s_api[i].fn); httpd_register_uri_handler(s_server, &u); } static const httpd_uri_t ws_uri = { .uri = "/ws", .method = HTTP_GET, .handler = ws_handler, .user_ctx = NULL, .is_websocket = true, .handle_ws_control_frames = false, .supported_subprotocol = NULL }; httpd_register_uri_handler(s_server, &ws_uri); ota_register(s_server); ESP_LOGI(TAG, "Web UI on port 80"); return ESP_OK; }