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:
1 parent
4b623bb156
commit
d32f3d69cf
8 files changed
+525
-11
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
idf_component_register(SRCS "main.cpp" "ws2812.cpp" "net.cpp" "settings.cpp" "web.cpp" "patterns.cpp" "presets.cpp"
|
||||
"effects_util.cpp" "effects_a.cpp" "effects_b.cpp" "effects_rig.cpp" "ota.c" "ddp.cpp"
|
||||
PRIV_REQUIRES esp_driver_rmt esp_driver_gpio esp_wifi esp_netif esp_event
|
||||
esp_timer nvs_flash esp_http_server cjson mdns esp_hw_support app_update esp_app_format lwip
|
||||
esp_timer nvs_flash esp_http_server esp_http_client cjson mdns esp_hw_support app_update esp_app_format lwip
|
||||
INCLUDE_DIRS "."
|
||||
EMBED_TXTFILES "../web/index.html" "../web/app.js" "../web/style.css")
|
||||
+3
-1
@@ -174,7 +174,9 @@ esp_err_t net_start(void)
|
||||
ESP_ERROR_CHECK(mdns_init());
|
||||
ESP_ERROR_CHECK(mdns_hostname_set(n.hostname));
|
||||
ESP_ERROR_CHECK(mdns_instance_name_set("LED controller"));
|
||||
ESP_ERROR_CHECK(mdns_service_add(NULL, "_http", "_tcp", 80, NULL, 0));
|
||||
// app=led-strip lets other drivers' discovery (GET /api/devices) pick out LED drivers from other HTTP devices
|
||||
static mdns_txt_item_t txt[] = { { "app", "led-strip" } };
|
||||
ESP_ERROR_CHECK(mdns_service_add(NULL, "_http", "_tcp", 80, txt, 1));
|
||||
ESP_LOGI(TAG, "mDNS: %s.local", n.hostname);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
+20
@@ -1,4 +1,5 @@
|
||||
#include "ota.h"
|
||||
#include "web.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -48,6 +49,7 @@ static esp_err_t fail(httpd_req_t *req, const char *status, const char *msg)
|
||||
ESP_LOGE(TAG, "%s", msg);
|
||||
httpd_resp_set_status(req, status);
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
web_allow_lan_origin(req);
|
||||
char buf[160];
|
||||
snprintf(buf, sizeof(buf), "{\"error\":\"%s\"}", msg);
|
||||
return httpd_resp_sendstr(req, buf);
|
||||
@@ -125,6 +127,7 @@ static esp_err_t ota_post_handler(httpd_req_t *req)
|
||||
|
||||
ESP_LOGI(TAG, "update ok, rebooting");
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
web_allow_lan_origin(req);
|
||||
httpd_resp_sendstr(req, "{\"message\":\"update written, rebooting\"}");
|
||||
|
||||
static esp_timer_handle_t t;
|
||||
@@ -151,6 +154,7 @@ static esp_err_t ota_get_handler(httpd_req_t *req)
|
||||
"{\"partition\":\"%s\",\"version\":\"%s\",\"built\":\"%s %s\",\"idf\":\"%s\",\"sha\":\"%s\"}",
|
||||
run ? run->label : "?", app->version, app->date, app->time, app->idf_ver, sha);
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
web_allow_lan_origin(req);
|
||||
return httpd_resp_sendstr(req, buf);
|
||||
}
|
||||
|
||||
@@ -158,6 +162,7 @@ static esp_err_t reboot_post_handler(httpd_req_t *req)
|
||||
{
|
||||
ESP_LOGI(TAG, "reboot requested");
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
web_allow_lan_origin(req);
|
||||
httpd_resp_sendstr(req, "{\"message\":\"rebooting\"}");
|
||||
|
||||
static esp_timer_handle_t t;
|
||||
@@ -170,14 +175,29 @@ static esp_err_t reboot_post_handler(httpd_req_t *req)
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
// Browser preflight for a firmware upload from another device's page (octet-stream is not a simple request)
|
||||
static esp_err_t ota_preflight_handler(httpd_req_t *req)
|
||||
{
|
||||
web_allow_lan_origin(req);
|
||||
httpd_resp_set_hdr(req, "Access-Control-Allow-Methods", "POST");
|
||||
httpd_resp_set_hdr(req, "Access-Control-Allow-Headers", "Content-Type");
|
||||
httpd_resp_set_hdr(req, "Access-Control-Max-Age", "600");
|
||||
httpd_resp_set_status(req, "204 No Content");
|
||||
return httpd_resp_send(req, NULL, 0);
|
||||
}
|
||||
|
||||
esp_err_t ota_register(httpd_handle_t server)
|
||||
{
|
||||
const httpd_uri_t post = { .uri = "/ota", .method = HTTP_POST, .handler = ota_post_handler };
|
||||
const httpd_uri_t get = { .uri = "/ota", .method = HTTP_GET, .handler = ota_get_handler };
|
||||
const httpd_uri_t preflight = { .uri = "/ota", .method = HTTP_OPTIONS, .handler = ota_preflight_handler };
|
||||
esp_err_t err = httpd_register_uri_handler(server, &post);
|
||||
if (err == ESP_OK) {
|
||||
err = httpd_register_uri_handler(server, &get);
|
||||
}
|
||||
if (err == ESP_OK) {
|
||||
err = httpd_register_uri_handler(server, &preflight);
|
||||
}
|
||||
const httpd_uri_t reboot = { .uri = "/reboot", .method = HTTP_POST, .handler = reboot_post_handler };
|
||||
if (err == ESP_OK) {
|
||||
err = httpd_register_uri_handler(server, &reboot);
|
||||
|
||||
+248
@@ -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;
|
||||
|
||||
+15
@@ -4,6 +4,21 @@
|
||||
#pragma once
|
||||
|
||||
#include "esp_err.h"
|
||||
#include "esp_http_server.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/** @brief Start the HTTP server on port 80 (UI and JSON API). */
|
||||
esp_err_t web_start(void);
|
||||
|
||||
/**
|
||||
* @brief Add Access-Control-Allow-Origin for a LAN or localhost page that asked (the Origin header).
|
||||
* Call before the response is sent. Other origins get no header, so the browser blocks them.
|
||||
*/
|
||||
void web_allow_lan_origin(httpd_req_t *req);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
Reference in new issue
Block a user