From d32f3d69cf8c669671cb1d50b923afce501cba93 Mon Sep 17 00:00:00 2001 From: jimmy Date: Wed, 11 Nov 2026 02:48:48 +1300 Subject: [PATCH] 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 --- main/CMakeLists.txt | 2 +- main/net.cpp | 4 +- main/ota.c | 20 ++++ main/web.cpp | 248 ++++++++++++++++++++++++++++++++++++++++++++ main/web.h | 15 +++ web/app.js | 221 +++++++++++++++++++++++++++++++++++++-- web/index.html | 25 ++++- web/style.css | 1 + 8 files changed, 525 insertions(+), 11 deletions(-) diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index d2ebdf1..013f2fa 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -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") diff --git a/main/net.cpp b/main/net.cpp index b9c61d3..fd3cc2a 100644 --- a/main/net.cpp +++ b/main/net.cpp @@ -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; } diff --git a/main/ota.c b/main/ota.c index caa350b..a96ddda 100644 --- a/main/ota.c +++ b/main/ota.c @@ -1,4 +1,5 @@ #include "ota.h" +#include "web.h" #include #include @@ -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); diff --git a/main/web.cpp b/main/web.cpp index c759a0c..945dca7 100644 --- a/main/web.cpp +++ b/main/web.cpp @@ -1,10 +1,13 @@ /* * 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" @@ -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://, 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"); +} + 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; diff --git a/main/web.h b/main/web.h index 4c1b11d..8ca586c 100644 --- a/main/web.h +++ b/main/web.h @@ -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 diff --git a/web/app.js b/web/app.js index 34dacfc..beaef0a 100644 --- a/web/app.js +++ b/web/app.js @@ -3,13 +3,61 @@ const $ = (id) => document.getElementById(id); const MAX_COLOURS = 8; + // The device being controlled: '' is this device, otherwise another driver's address (e.g. 10.1.1.50). + const DEVICES_KEY = 'led-driver-devices'; + const HOST_RE = /^[A-Za-z0-9.-]+(:\d{1,5})?$/; + let base = ''; + // Selecting ALL sends the changes below to every device at once; reads show this device. + const ALL = '*'; + const ALL_WRITES = ['/api/brightness', '/api/presets/select']; + async function api(path, opts) { + if (base === ALL) return fanOut(path, opts); + if (base) return relayTo(base, path, opts); + return direct(path, opts); + } + + // This device's own API + async function direct(path, opts) { const r = await fetch(path, opts); const j = await r.json().catch(() => ({})); if (!r.ok) throw new Error(j.error || r.statusText); return j; } + // Another device: this driver makes the call (POST /api/relay), so the browser only talks to this one. + async function relayTo(host, path, opts) { + const method = (opts && opts.method) || 'GET'; + const body = opts && typeof opts.body === 'string' ? opts.body : ''; + const r = await fetch('/api/relay', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ host, method, path, body }), + }); + const env = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(env.error || r.statusText); + let j = {}; + try { j = JSON.parse(env.body || '{}'); } catch (_) { j = {}; } + if (env.status < 200 || env.status >= 300) throw new Error(j.error || 'HTTP ' + env.status); + return j; + } + + // All devices: the same change goes to every device at once. Reads come from this device. + async function fanOut(path, opts) { + const method = (opts && opts.method) || 'GET'; + if (method === 'GET') return direct(path, opts); + if (!ALL_WRITES.includes(path)) { + throw new Error('Choose one device to change this. "All devices" only sets brightness and plays presets.'); + } + const hosts = ['', ...deviceChoices().map(([h]) => h)]; + const results = await Promise.allSettled(hosts.map((h) => (h ? relayTo(h, path, opts) : direct(path, opts)))); + const failed = results.filter((r) => r.status === 'rejected'); + if (failed.length) { + throw new Error(`${failed.length} of ${hosts.length} devices failed: ${failed[0].reason.message}`); + } + return results[0].value; + } + const post = (path, body) => api(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -675,6 +723,10 @@ $('fwMsg').textContent = 'Choose a .bin file first'; return; } + if (base) { + $('fwMsg').textContent = 'Firmware files are too large to relay. Open the device’s own address to update it.'; + return; + } if (!confirm(`Update to ${file.name} (${file.size} bytes)? The driver reboots afterwards.`)) return; $('fwUpload').disabled = true; $('fwMsg').textContent = 'Uploading…'; @@ -835,6 +887,165 @@ // ---- tabs and start-up ------------------------------------------------------------------------ // On phones the header menu is collapsed behind the ☰ button + // ---- other devices: one page, many drivers ---------------------------------------------------- + + function loadDevices() { + try { + const list = JSON.parse(localStorage.getItem(DEVICES_KEY) || '[]'); + return Array.isArray(list) ? list.filter((h) => typeof h === 'string' && HOST_RE.test(h)) : []; + } catch (_) { return []; } + } + + function saveDevices(list) { + try { localStorage.setItem(DEVICES_KEY, JSON.stringify(list)); } catch (_) { /* ignore */ } + } + + function refreshAll() { + loadStatus().catch((e) => { $('status').textContent = e.message; }); + loadPresets().catch((e) => { $('status').textContent = e.message; }); + loadWifi().catch(() => {}); + loadNetwork().catch(() => {}); + loadHardware().catch(() => {}); + loadFirmware().catch((e) => { $('fwInfo').textContent = e.message; }); + } + + // LED drivers found on the network by mDNS, from this device's /api/devices + let found = []; + let localName = ''; // this device's name (its hostname), shown in the dropdown + + // The dropdown: This device, every driver found on the network, and any added by hand. + function deviceChoices() { + const here = location.hostname; + const seen = new Set(); + const out = []; + const add = (host, label) => { + if (!host || host === here || seen.has(host)) return; + seen.add(host); + out.push([host, label]); + }; + found.filter((d) => d.ip !== here).forEach((d) => add(d.host, d.name)); + loadDevices().forEach((h) => add(h, h)); + // A device that drops off the network stays selected rather than vanishing from the list + if (base && base !== ALL && !seen.has(base)) out.push([base, base]); + return out; + } + + async function discoverDevices() { + try { + // Both asked of this device, which is the one the page came from + const [dr, sr] = await Promise.all([fetch('/api/devices'), fetch('/api/status')]); + const j = await dr.json(); + const st = await sr.json(); + const next = Array.isArray(j.devices) ? j.devices.filter((d) => d && d.host) : []; + const name = typeof st.hostname === 'string' ? st.hostname : ''; + if (JSON.stringify(next) !== JSON.stringify(found) || name !== localName) { + found = next; + localName = name; + renderDevices(); + } + } catch (_) { /* keep the list we have */ } + } + + function renderDevices() { + const list = loadDevices(); + const sel = $('deviceSelect'); + sel.textContent = ''; + const choices = deviceChoices(); + // All devices first, then this device by its name, then the others + const top = choices.length ? [[ALL, 'All devices']] : []; + [...top, ['', localName || 'This device'], ...choices].forEach(([value, label]) => { + const opt = document.createElement('option'); + opt.value = value; + opt.textContent = label; + sel.appendChild(opt); + }); + sel.value = base; + const box = $('devList'); + box.textContent = ''; + list.forEach((h) => { + const li = document.createElement('li'); + const name = document.createElement('span'); + name.textContent = h; + const remove = document.createElement('button'); + remove.type = 'button'; + remove.className = 'btn-secondary'; + remove.textContent = 'Remove'; + remove.addEventListener('click', () => removeDevice(h)); + li.append(name, remove); + box.appendChild(li); + }); + } + + function selectDevice(host) { + if (host === base) return; + base = host; + closeEditor(); + $('status').textContent = host === ALL ? `Controlling all ${deviceChoices().length + 1} devices` : ''; + renderDevices(); + refreshAll(); + } + + function removeDevice(host) { + saveDevices(loadDevices().filter((h) => h !== host)); + if (base === host) base = ''; + renderDevices(); + refreshAll(); + } + + // ---- sync presets: this device is the master ------------------------------------------------- + + async function syncPresets() { + const msg = $('syncMsg'); + const slaves = deviceChoices().map(([h]) => h); + if (!slaves.length) { + msg.textContent = 'No other devices found. Add one, or wait for discovery.'; + return; + } + if (!confirm(`Copy this device's presets to ${slaves.length} other device(s)? Same-name presets are replaced.`)) return; + msg.textContent = 'Syncing…'; + const master = await direct('/api/presets'); // always this device, even when another device is selected + const presets = master.presets || []; + const names = presets.map((p) => p.name); + const failed = []; + for (const host of slaves) { + try { + for (const p of presets) { + await relayTo(host, '/api/presets', { method: 'POST', body: JSON.stringify(p) }); + } + await relayTo(host, '/api/presets/order', { method: 'POST', body: JSON.stringify({ names }) }); + await relayTo(host, '/api/presets/startup', { method: 'POST', body: JSON.stringify({ name: master.startup || '' }) }); + } catch (e) { + failed.push(`${host}: ${e.message}`); + } + } + msg.textContent = failed.length + ? `Failed on ${failed.length} of ${slaves.length}. ${failed.join('; ')}` + : `Synced ${presets.length} preset(s) to ${slaves.length} device(s).`; + if (base) refreshAll(); // the presets list may have changed on the device being viewed + } + + $('syncPresets').addEventListener('click', () => { + syncPresets().catch((e) => { $('syncMsg').textContent = e.message; }); + }); + + $('deviceSelect').addEventListener('change', () => selectDevice($('deviceSelect').value)); + $('devAdd').addEventListener('submit', (ev) => { + ev.preventDefault(); + const host = $('devHost').value.trim().replace(/^https?:\/\//, '').replace(/\/+$/, ''); + if (!HOST_RE.test(host)) { + $('devMsg').textContent = 'Enter an address such as 10.1.1.50 or led-desk.local.'; + return; + } + const list = loadDevices(); + if (!list.includes(host)) list.push(host); + saveDevices(list); + $('devHost').value = ''; + $('devMsg').textContent = ''; + base = host; + renderDevices(); + refreshAll(); + }); + const header = document.querySelector('header'); const menuToggle = $('menuToggle'); const setMenu = (open) => { @@ -891,12 +1102,10 @@ renderColours(); updateOutputs(); - loadStatus().catch((e) => { $('status').textContent = e.message; }); - loadPresets().catch((e) => { $('status').textContent = e.message; }); - loadWifi().catch(() => {}); - loadNetwork().catch(() => {}); - loadHardware().catch(() => {}); - loadFirmware().catch((e) => { $('fwInfo').textContent = e.message; }); + renderDevices(); + refreshAll(); + discoverDevices(); + setInterval(discoverDevices, 60000); setInterval(() => { loadStatus().catch(() => {}); loadPresets().catch(() => {}); diff --git a/web/index.html b/web/index.html index d7ed2b8..8d7d5bb 100644 --- a/web/index.html +++ b/web/index.html @@ -17,10 +17,13 @@ -