feat: control several drivers from one web UI

- Device dropdown: All devices, this device by name, then drivers found by
  mDNS (tagged app=led-strip) and any added by hand.
- POST /api/relay: a driver calls another driver's API for the page, so the
  browser only talks to its own board. Limited to /api/*, /ota and /reboot.
- All devices sends brightness and preset plays to every device.
- Settings: sync this device's presets, order and startup to the others.
- CORS for LAN and localhost origins, and an OPTIONS handler for /ota.
- Header labels are removed; the controls keep aria-labels.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Haiku 5.5 committed 2026-11-11 02:48:48 +13:00
1 parent 4b623bb156
commit d32f3d69cf
8 files changed
+525 -11

No files matched your search

+248
View File
@@ -1,10 +1,13 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "cJSON.h"
#include "esp_http_client.h"
#include "mdns.h"
#include "esp_http_server.h"
#include "esp_log.h"
#include "esp_netif.h"
@@ -45,10 +48,85 @@ static esp_err_t send_embedded(httpd_req_t *req, const char *type, const char *s
return httpd_resp_send(req, start, len);
}
// True for http://<private IPv4>, http://<name>.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");
}
static esp_err_t send_json(httpd_req_t *req, cJSON *obj)
{
char *s = cJSON_PrintUnformatted(obj);
cJSON_Delete(obj);
web_allow_lan_origin(req);
if (!s) {
return httpd_resp_send_500(req);
}
@@ -627,6 +705,174 @@ static void add_uri(httpd_handle_t srv, const char *uri, httpd_method_t method,
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;
}
// POST /api/relay {"host": "10.1.1.50", "method": "GET" or "POST", "path": "/api/status", "body": "..."}
// Calls another driver from here and answers {"status": n, "body": "..."}. A page on this driver only
// talks to this driver, so the browser never has to reach the other device itself.
static esp_err_t relay_post(httpd_req_t *req)
{
// Heap buffers: the HTTP server task has an 8 KB stack
char *in = (char *)malloc(2048);
char *out = (char *)malloc(4096);
if (!in || !out) {
free(in);
free(out);
return send_error(req, "503 Service Unavailable", "out of memory");
}
esp_err_t result = ESP_FAIL;
if (!read_body(req, in, 2048)) {
result = send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
goto done;
} 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) || !relay_host_ok(jh->valuestring)
|| !relay_path_ok(jp->valuestring) || (strcmp(jm->valuestring, "GET") != 0 && strcmp(jm->valuestring, "POST") != 0)) {
cJSON_Delete(top);
result = send_error(req, "400 Bad Request", "need host, method GET or POST, and a path under /api/");
goto done;
}
const bool is_post = strcmp(jm->valuestring, "POST") == 0;
const char *body = (is_post && cJSON_IsString(jb)) ? jb->valuestring : "";
const int body_len = (int)strlen(body);
char url[200];
snprintf(url, sizeof(url), "http://%s%s", jh->valuestring, jp->valuestring);
esp_http_client_config_t ccfg = {};
ccfg.url = url;
ccfg.method = is_post ? HTTP_METHOD_POST : HTTP_METHOD_GET;
ccfg.timeout_ms = 4000;
esp_http_client_handle_t cl = esp_http_client_init(&ccfg);
if (!cl) {
cJSON_Delete(top);
result = send_error(req, "502 Bad Gateway", "could not start the request");
goto done;
}
esp_http_client_set_header(cl, "Content-Type", "text/plain");
esp_err_t err = esp_http_client_open(cl, is_post ? body_len : 0);
if (err == ESP_OK && is_post && body_len > 0) {
if (esp_http_client_write(cl, body, body_len) != body_len) {
err = ESP_FAIL;
}
}
int got = 0;
int status = 0;
if (err == ESP_OK && esp_http_client_fetch_headers(cl) >= 0) {
status = esp_http_client_get_status_code(cl);
int r;
while (got < 4095 && (r = esp_http_client_read(cl, out + got, 4095 - got)) > 0) {
got += r;
}
} else {
err = ESP_FAIL;
}
esp_http_client_close(cl);
esp_http_client_cleanup(cl);
cJSON_Delete(top);
if (err != ESP_OK) {
result = send_error(req, "502 Bad Gateway", "could not reach that device");
goto done;
}
out[got] = '\0';
cJSON *o = cJSON_CreateObject();
cJSON_AddNumberToObject(o, "status", status);
cJSON_AddStringToObject(o, "body", out);
result = send_json(req, o);
}
done:
free(in);
free(out);
return result;
}
// GET /api/devices: the LED drivers on this network, found by mDNS (they advertise app=led-strip).
// Includes this driver; the page leaves it out, since "This device" is already in the list.
static esp_err_t devices_get(httpd_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);
}
esp_err_t web_start(void)
{
httpd_config_t cfg = HTTPD_DEFAULT_CONFIG();
@@ -661,6 +907,8 @@ esp_err_t web_start(void)
add_uri(s_server, "/api/presets/defaults", HTTP_POST, presets_defaults_post);
add_uri(s_server, "/api/presets/order", HTTP_POST, presets_order_post);
add_uri(s_server, "/api/brightness", HTTP_POST, brightness_post);
add_uri(s_server, "/api/relay", HTTP_POST, relay_post);
add_uri(s_server, "/api/devices", HTTP_GET, devices_get);
ota_register(s_server);
ESP_LOGI(TAG, "Web UI on port 80");
return ESP_OK;