feat(v2): move web UI into v2, remove legacy MicroPython app

Move the web assets and templates under v2/web, drop the old src/, lib/
and scripts, and update firmware, tools, docs and db files. Add the audio
page, LED test scripts and VPN autoconnect script.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Sonnet 5.5 committed 2026-11-02 20:30:02 +13:00
1 parent 6c16998691
commit 71bd320661
193 files changed
+5605 -18860

No files matched your search

+12 -1
View File
@@ -1,4 +1,14 @@
dependencies:
espressif/mdns:
component_hash: ef0766474b37459f6ad22461e453a8713e780e831a7c993b16919d817988dff6
dependencies:
- name: idf
require: private
version: '>=5.0'
source:
registry_url: https://components.espressif.com/
type: service
version: 1.14.1
idf:
source:
type: idf
@@ -14,7 +24,8 @@ dependencies:
type: service
version: 1.23.1
direct_dependencies:
- espressif/mdns
- joltwallet/littlefs
manifest_hash: 39931b5fd49af3f43a545f2b46eed14a91ad9a530706d1e14335b6dbea19a246
manifest_hash: ca18d7304afd7b13c5257461792fe9f4b54a044914fa18a550807cfc4eb8cf67
target: esp32s3
version: 2.0.0
+3 -3
View File
@@ -27,7 +27,7 @@ tools/build_web.sh
docker run --rm -v "$PWD":/project -w /project espressif/idf:v5.5.5 idf.py build
```
Expect `Project build complete`, the app well under its 2 MB slot, and `build/www.bin` present. Fix ownership if Docker left it root-owned: `docker run --rm -v "$PWD":/project espressif/idf:v5.5.5 chown -R 0:0 /project`.
Expect `Project build complete`, the app well under its 2 MB slot, with the web UI embedded (`www_dist/www.pack`). Fix ownership if Docker left it root-owned: `docker run --rm -v "$PWD":/project espressif/idf:v5.5.5 chown -R 0:0 /project`.
Flash with the S3 on USB (check which port it is; `ls /dev/ttyACM*`):
@@ -35,7 +35,7 @@ Flash with the S3 on USB (check which port it is; `ls /dev/ttyACM*`):
docker run --rm --device=/dev/ttyACM0 -v "$PWD":/project -w /project espressif/idf:v5.5.5 idf.py -p /dev/ttyACM0 flash
```
This writes the bootloader, partition table, app and the web UI image. Watch the log:
This writes the bootloader, partition table and app (the web UI is part of the app). Watch the log:
```bash
docker run --rm -it --device=/dev/ttyACM0 -v "$PWD":/project -w /project espressif/idf:v5.5.5 idf.py -p /dev/ttyACM0 monitor
@@ -282,7 +282,7 @@ Groups: the controller sends a driver its group list when the driver announces i
- **Devices show `last_ack_ms_ago: -1`:** the device record has no usable 12-character MAC in `address` or as its key.
- **`beats_sent` rises but `echoes` stays 0:** the driver is not in `bench` mode, or it has not yet heard a controller frame (it learns the controller's MAC from the first data or digest frame; wait a few seconds).
- **Resync never triggers:** the driver ignores a digest equal to its own version; confirm with `/status` that `link.ver` changed after the missed play.
- **Web UI is blank:** the `www` image was not built before flashing; run `tools/build_web.sh` and flash again.
- **Web UI is blank:** the web UI was not packed before the build; run `tools/build_web.sh` and build again (`make build` does this).
## 9. Cleanup
+5 -4
View File
@@ -2,9 +2,10 @@ idf_component_register(SRCS "main.c" "mic.c" "beat.c" "beat_dsp.c" "espnow_tx.c"
INCLUDE_DIRS "."
REQUIRES esp_eth esp_netif esp_event esp_driver_spi esp_driver_gpio nvs_flash app_update esp_app_format
esp_http_server esp_timer esp_driver_i2s esp_wifi esp_rom json esp_driver_gpio
PRIV_REQUIRES littlefs)
PRIV_REQUIRES littlefs mdns)
# Flash the gzipped web UI into the www partition (run tools/build_web.sh first)
if(EXISTS ${PROJECT_DIR}/www_dist)
littlefs_create_partition_image(www ${PROJECT_DIR}/www_dist FLASH_IN_PROJECT)
# The gzipped web UI is embedded in the app image (run tools/build_web.sh first)
if(NOT EXISTS ${PROJECT_DIR}/www_dist/www.pack)
message(FATAL_ERROR "www_dist/www.pack is missing: run v2/tools/build_web.sh (make build does)")
endif()
target_add_binary_data(${COMPONENT_LIB} ${PROJECT_DIR}/www_dist/www.pack BINARY)
+45
View File
@@ -198,6 +198,47 @@ static esp_err_t handle_profile_action(httpd_req_t *req, const char *id, const c
return not_implemented(req, action);
}
// Settings a driver keeps in its own settings.json and takes from a device_config message
static const char *const DEVICE_CONFIG_KEYS[] = { "max_brightness", "num_leds", "color_order", "startup_mode", "reversed" };
// The driver settings present in a device update, or NULL when it has none. Caller deletes the result.
static cJSON *device_config_from(const cJSON *body)
{
cJSON *dc = NULL;
for (size_t i = 0; i < sizeof(DEVICE_CONFIG_KEYS) / sizeof(DEVICE_CONFIG_KEYS[0]); i++) {
const cJSON *v = cJSON_GetObjectItem(body, DEVICE_CONFIG_KEYS[i]);
if (!v || cJSON_IsNull(v)) {
continue;
}
if (!dc) {
dc = cJSON_CreateObject();
}
cJSON_AddItemToObject(dc, DEVICE_CONFIG_KEYS[i], cJSON_Duplicate(v, true));
}
return dc;
}
// Send changed settings to an ESP-NOW driver; takes ownership of dc
static esp_err_t push_device_config(const cJSON *dev, cJSON *dc)
{
const cJSON *tr = cJSON_GetObjectItem(dev, "transport"), *addr = cJSON_GetObjectItem(dev, "address");
if (!cJSON_IsString(tr) || strcmp(tr->valuestring, "espnow") || !cJSON_IsString(addr)) {
cJSON_Delete(dc);
return ESP_ERR_INVALID_ARG;
}
cJSON *msg = cJSON_CreateObject();
cJSON_AddStringToObject(msg, "v", "1");
cJSON_AddItemToObject(msg, "device_config", dc);
cJSON_AddTrueToObject(msg, "save");
cJSON *messages = cJSON_CreateArray(), *targets = cJSON_CreateArray();
cJSON_AddItemToArray(messages, msg);
cJSON_AddItemToArray(targets, cJSON_CreateString(addr->valuestring));
esp_err_t err = engine_push(messages, targets);
cJSON_Delete(messages);
cJSON_Delete(targets);
return err;
}
static esp_err_t collection_handler_inner(httpd_req_t *req)
{
char seg[3][64];
@@ -425,9 +466,13 @@ static esp_err_t collection_handler_inner(httpd_req_t *req)
if (!body) {
return ESP_OK;
}
cJSON *dev_cfg = !strcmp(coll, "device") ? device_config_from(body) : NULL;
merge(rec, body);
cJSON_Delete(body);
store_save(coll);
if (dev_cfg) {
push_device_config(rec, dev_cfg); // before the group resend: a second message right behind another may not be delivered
}
if (!strcmp(coll, "zone") || !strcmp(coll, "device")) {
engine_groups_changed();
}
+1
View File
@@ -1,2 +1,3 @@
dependencies:
joltwallet/littlefs: "^1.19.0"
espressif/mdns: "^1.4.0"
+138
View File
@@ -17,6 +17,13 @@
#include "esp_http_server.h"
#include "esp_timer.h"
#include "esp_system.h"
#include "mdns.h"
#include "lwip/ip4_addr.h"
#include "lwip/etharp.h"
#include "lwip/netif.h"
#include "lwip/sockets.h"
#include "esp_netif_net_stack.h"
#include "cJSON.h"
#include "mic.h"
#include "beat.h"
#include "espnow_tx.h"
@@ -71,6 +78,126 @@ static esp_err_t status_get_handler(httpd_req_t *req)
return httpd_resp_sendstr(req, buf);
}
#define DEFAULT_HOSTNAME "led-controller"
static const char *settings_str(const char *key)
{
cJSON *v = cJSON_GetObjectItem(store_settings(), key);
return cJSON_IsString(v) && v->valuestring[0] ? v->valuestring : NULL;
}
// "static_ips" setting: a list of {ip, netmask, gw, dns} tried in order on every link-up. The first whose
// gateway answers ARP is kept; if none does, the controller falls back to DHCP.
static bool parse_static(cJSON *e, esp_netif_ip_info_t *info, esp_netif_dns_info_t *dns)
{
const char *ip = NULL, *mask = "255.255.255.0", *gw = NULL, *d = NULL;
cJSON *v;
if (!cJSON_IsObject(e)) return false;
if (cJSON_IsString(v = cJSON_GetObjectItem(e, "ip"))) ip = v->valuestring;
if (cJSON_IsString(v = cJSON_GetObjectItem(e, "netmask"))) mask = v->valuestring;
if (cJSON_IsString(v = cJSON_GetObjectItem(e, "gw"))) gw = v->valuestring;
if (cJSON_IsString(v = cJSON_GetObjectItem(e, "dns"))) d = v->valuestring;
memset(info, 0, sizeof(*info));
memset(dns, 0, sizeof(*dns));
if (!ip || esp_netif_str_to_ip4(ip, &info->ip) != ESP_OK || esp_netif_str_to_ip4(mask, &info->netmask) != ESP_OK ||
(gw && esp_netif_str_to_ip4(gw, &info->gw) != ESP_OK)) {
return false;
}
if (d && esp_netif_str_to_ip4(d, &dns->ip.u_addr.ip4) == ESP_OK) {
dns->ip.type = ESP_IPADDR_TYPE_V4;
} else if (gw) {
dns->ip.u_addr.ip4 = info->gw;
dns->ip.type = ESP_IPADDR_TYPE_V4;
}
return true;
}
// Poke the gateway so lwIP ARPs for it, then wait for the entry to show up
static bool gateway_answers(esp_netif_t *netif, const esp_ip4_addr_t *gw)
{
struct netif *nif = esp_netif_get_netif_impl(netif);
ip4_addr_t g = { .addr = gw->addr };
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (!nif || sock < 0) {
if (sock >= 0) close(sock);
return false;
}
struct sockaddr_in to = { .sin_family = AF_INET, .sin_port = htons(9), .sin_addr.s_addr = gw->addr };
bool ok = false;
for (int i = 0; i < 15 && !ok; i++) {
sendto(sock, "", 0, 0, (struct sockaddr *)&to, sizeof(to));
vTaskDelay(pdMS_TO_TICKS(100));
struct eth_addr *eth = NULL;
const ip4_addr_t *ipr = NULL;
ok = etharp_find_addr(nif, &g, &eth, &ipr) >= 0;
}
close(sock);
return ok;
}
static void static_ip_task(void *arg)
{
static bool running;
if (running) {
vTaskDelete(NULL);
}
running = true;
cJSON *list = cJSON_GetObjectItem(store_settings(), "static_ips");
esp_netif_dhcpc_stop(s_eth_netif);
bool done = false;
cJSON *e;
cJSON_ArrayForEach(e, list) {
esp_netif_ip_info_t info;
esp_netif_dns_info_t dns;
if (!parse_static(e, &info, &dns)) {
ESP_LOGW(TAG, "static_ips: skipping an invalid entry");
continue;
}
if (esp_netif_set_ip_info(s_eth_netif, &info) != ESP_OK) {
continue;
}
if (dns.ip.type == ESP_IPADDR_TYPE_V4) {
esp_netif_set_dns_info(s_eth_netif, ESP_NETIF_DNS_MAIN, &dns);
}
if (info.gw.addr == 0 || gateway_answers(s_eth_netif, &info.gw)) {
ESP_LOGI(TAG, "Static IP " IPSTR " (gw " IPSTR ")", IP2STR(&info.ip), IP2STR(&info.gw));
done = true;
break;
}
ESP_LOGI(TAG, "Static IP " IPSTR ": gateway " IPSTR " did not answer", IP2STR(&info.ip), IP2STR(&info.gw));
}
if (!done) {
ESP_LOGW(TAG, "No static IP matched this network, using DHCP");
esp_netif_ip_info_t none = { 0 };
esp_netif_set_ip_info(s_eth_netif, &none);
esp_netif_dhcpc_start(s_eth_netif);
}
running = false;
vTaskDelete(NULL);
}
static bool have_static_ips(void)
{
cJSON *l = cJSON_GetObjectItem(store_settings(), "static_ips");
return cJSON_IsArray(l) && cJSON_GetArraySize(l) > 0;
}
static void start_mdns(void)
{
const char *host = settings_str("hostname");
if (!host) {
host = DEFAULT_HOSTNAME;
}
if (mdns_init() != ESP_OK) {
ESP_LOGE(TAG, "mDNS init failed");
return;
}
mdns_hostname_set(host);
mdns_instance_name_set("LED controller");
mdns_service_add(NULL, "_http", "_tcp", 80, NULL, 0);
ESP_LOGI(TAG, "mDNS: %s.local", host);
}
static void start_webserver(void)
{
if (s_server) {
@@ -108,6 +235,9 @@ static void eth_event_handler(void *arg, esp_event_base_t event_base,
esp_eth_ioctl(eth_handle, ETH_CMD_G_SPEED, &speed);
esp_eth_ioctl(eth_handle, ETH_CMD_G_DUPLEX_MODE, &duplex);
ESP_LOGI(TAG, "Ethernet Link Up, MAC " MACSTR, MAC2STR(mac));
if (have_static_ips()) {
xTaskCreate(static_ip_task, "static_ip", 4096, NULL, 5, NULL);
}
ESP_LOGI(TAG, "%s Mbps %s Duplex",
speed == ETH_SPEED_100M ? "100" : "10",
duplex == ETH_DUPLEX_FULL ? "Full" : "Half");
@@ -139,6 +269,11 @@ static void got_ip_event_handler(void *arg, esp_event_base_t event_base,
// Server binds to all interfaces, so it keeps working across lease changes
start_webserver();
static bool mdns_started;
if (!mdns_started) {
mdns_started = true;
start_mdns();
}
}
static esp_err_t w5500_init(esp_eth_handle_t *eth_handle_out)
@@ -229,6 +364,9 @@ void app_main(void)
s_eth_netif = esp_netif_new(&netif_cfg);
ESP_ERROR_CHECK(esp_netif_attach(s_eth_netif, esp_eth_new_netif_glue(eth_handle)));
const char *host = settings_str("hostname");
esp_netif_set_hostname(s_eth_netif, host ? host : DEFAULT_HOSTNAME);
ESP_ERROR_CHECK(esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, &eth_event_handler, NULL));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &got_ip_event_handler, NULL));
+29 -3
View File
@@ -6,6 +6,7 @@
#include "esp_ota_ops.h"
#include "esp_app_format.h"
#include "esp_system.h"
#include <string.h>
#include "esp_timer.h"
static const char *TAG = "ota";
@@ -140,14 +141,35 @@ static esp_err_t ota_get_handler(httpd_req_t *req)
{
const esp_partition_t *run = esp_ota_get_running_partition();
const esp_app_desc_t *app = esp_app_get_description();
char buf[256];
// The build date is only recompiled with its own file, so the ELF hash is what tells two builds apart
char sha[17];
for (int i = 0; i < 8; i++) {
snprintf(sha + 2 * i, 3, "%02x", app->app_elf_sha256[i]);
}
char buf[288];
snprintf(buf, sizeof(buf),
"{\"partition\":\"%s\",\"version\":\"%s\",\"built\":\"%s %s\",\"idf\":\"%s\"}",
run ? run->label : "?", app->version, app->date, app->time, app->idf_ver);
"{\"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");
return httpd_resp_sendstr(req, buf);
}
static esp_err_t reboot_post_handler(httpd_req_t *req)
{
ESP_LOGI(TAG, "reboot requested");
httpd_resp_set_type(req, "application/json");
httpd_resp_sendstr(req, "{\"message\":\"rebooting\"}");
static esp_timer_handle_t t;
const esp_timer_create_args_t args = { .callback = reboot_cb, .name = "reboot" };
if (esp_timer_create(&args, &t) == ESP_OK) {
esp_timer_start_once(t, 500 * 1000);
} else {
esp_restart();
}
return ESP_OK;
}
esp_err_t ota_register(httpd_handle_t server)
{
const httpd_uri_t post = { .uri = "/ota", .method = HTTP_POST, .handler = ota_post_handler };
@@ -156,5 +178,9 @@ esp_err_t ota_register(httpd_handle_t server)
if (err == ESP_OK) {
err = httpd_register_uri_handler(server, &get);
}
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);
}
return err;
}
+2
View File
@@ -4,6 +4,8 @@
#include "esp_http_server.h"
// Register POST /ota (raw firmware .bin as the body) and GET /ota (running image info).
// The web UI is part of the image, so one upload updates both.
// POST /reboot restarts the board (replies first, reboots after 0.5 s).
// A good upload is written to the idle app slot, becomes the boot image and the board reboots.
esp_err_t ota_register(httpd_handle_t server);
+1 -1
View File
@@ -36,6 +36,7 @@ static esp_err_t mount(const char *label, const char *base)
.base_path = base,
.partition_label = label,
.format_if_mount_failed = true,
.grow_on_mount = true, // the db partition spans the rest of the flash; an older, smaller filesystem is extended in place
};
return esp_vfs_littlefs_register(&conf);
}
@@ -71,7 +72,6 @@ esp_err_t store_init(void)
{
s_lock = xSemaphoreCreateRecursiveMutex();
ESP_RETURN_ON_FALSE(s_lock, ESP_ERR_NO_MEM, TAG, "mutex");
ESP_RETURN_ON_ERROR(mount("www", "/www"), TAG, "mount www");
ESP_RETURN_ON_ERROR(mount("db", "/db"), TAG, "mount db");
for (size_t i = 0; i < N_COLL; i++) {
s_coll[i] = load_file(NAMES[i]);
+1 -1
View File
@@ -8,7 +8,7 @@
// id -> record, mirroring the Pi's db/*.json. Collections stay in memory and
// are written back (via a temp file and rename) whenever they change.
// Mount the www and db partitions and load every collection
// Mount the db partition and load every collection
esp_err_t store_init(void);
// Borrowed pointer to the collection object (id -> record); never NULL for a known name
+44 -26
View File
@@ -1,14 +1,12 @@
#include "web.h"
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include "esp_log.h"
static const char *TAG = "web";
#define CHUNK 2048
static const struct {
const char *ext;
const char *type;
@@ -34,37 +32,57 @@ static const char *mime_for(const char *path)
return "application/octet-stream";
}
// path is the URL-relative name, e.g. "static/zones.js"; the file on flash is "/www/<path>.gz"
// The web UI is one blob linked into the app image (www_dist/www.pack, see tools/build_web.sh):
// "WWW1", then per file u16 name length, u32 data length, the name, the gzipped data; a zero name
// length ends it.
extern const uint8_t www_pack_start[] asm("_binary_www_pack_start");
extern const uint8_t www_pack_end[] asm("_binary_www_pack_end");
static bool find_file(const char *path, const uint8_t **data, uint32_t *len)
{
const uint8_t *p = www_pack_start, *end = www_pack_end;
if (end - p < 6 || memcmp(p, "WWW1", 4) != 0) {
return false;
}
p += 4;
size_t want = strlen(path);
while (end - p >= 2) {
uint16_t nlen;
memcpy(&nlen, p, 2);
if (nlen == 0 || end - p < 6 + nlen) {
return false;
}
uint32_t dlen;
memcpy(&dlen, p + 2, 4);
const uint8_t *name = p + 6, *body = name + nlen;
if (end - body < (ptrdiff_t)dlen) {
return false;
}
if (nlen == want && memcmp(name, path, want) == 0) {
*data = body;
*len = dlen;
return true;
}
p = body + dlen;
}
return false;
}
// path is the URL-relative name, e.g. "static/zones.js"
static esp_err_t send_gz(httpd_req_t *req, const char *path, bool immutable)
{
char fs[128];
if (strstr(path, "..") || snprintf(fs, sizeof(fs), "/www/%s.gz", path) >= (int)sizeof(fs)) {
const uint8_t *data;
uint32_t len;
if (strstr(path, "..")) {
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "bad path");
}
FILE *f = fopen(fs, "rb");
if (!f) {
if (!find_file(path, &data, &len)) {
return httpd_resp_send_404(req);
}
httpd_resp_set_type(req, mime_for(path));
httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
httpd_resp_set_hdr(req, "Cache-Control", immutable ? "public, max-age=86400" : "no-cache");
char *buf = malloc(CHUNK);
if (!buf) {
fclose(f);
return httpd_resp_send_500(req);
}
esp_err_t ret = ESP_OK;
size_t n;
while (ret == ESP_OK && (n = fread(buf, 1, CHUNK, f)) > 0) {
ret = httpd_resp_send_chunk(req, buf, n);
}
if (ret == ESP_OK) {
ret = httpd_resp_send_chunk(req, NULL, 0);
}
free(buf);
fclose(f);
return ret;
return httpd_resp_send(req, (const char *)data, len);
}
esp_err_t web_send_page(httpd_req_t *req, const char *name)
+2 -2
View File
@@ -3,8 +3,8 @@
#include "esp_err.h"
#include "esp_http_server.h"
// Register /, /settings/page, /static/* and /favicon.ico. Files come from the
// www partition, stored as <path>.gz and sent with Content-Encoding: gzip.
// Register /, /audio, /static/* and /favicon.ico. Files come from the web UI blob embedded in the
// firmware (gzipped, sent with Content-Encoding: gzip).
esp_err_t web_register(httpd_handle_t server);
// Send one of the top-level pages (e.g. "settings.html")
+1 -2
View File
@@ -4,5 +4,4 @@ otadata, data, ota, 0xf000, 0x2000
phy_init, data, phy, 0x11000, 0x1000
ota_0, app, ota_0, 0x20000, 0x200000
ota_1, app, ota_1, 0x220000,0x200000
www, data, littlefs,0x420000,0x100000
db, data, littlefs,0x520000,0x100000
db, data, littlefs,0x520000,0xAE0000
1 # Name Type SubType Offset Size
4 phy_init data phy 0x11000 0x1000
5 ota_0 app ota_0 0x20000 0x200000
6 ota_1 app ota_1 0x220000 0x200000
7 www db data littlefs 0x420000 0x520000 0x100000 0xAE0000
db data littlefs 0x520000 0x100000
+508
View File
@@ -0,0 +1,508 @@
"""
Compact binary controller → led-driver messages (ESP-NOW friendly).
Header (5 bytes), same for v1 (legacy) and v2 (native binary):
0: version — 1 = legacy (JSON text blobs); 2 = native binary blobs
1: brightness — 0–127 scales to device 0–255; 128–255 = leave unchanged
2: byte length of presets section (0–255)
3: byte length of select section
4: byte length of default section
v2 presets blob (no JSON):
u8 preset_count
each preset:
u8 name_len; name utf-8
u8 pattern_len; pattern utf-8 (``p``)
u8 color_count; color_count × (u8 r, u8 g, u8 b)
u16 delay_le (``d``)
u8 preset_brightness (``b``)
u8 auto (0/1) (``a``)
i16 n1..n6 little-endian (``n1``–``n6``)
v2 select blob:
u8 entry_count
each:
u8 device_len; device utf-8
u8 preset_name_len; preset name utf-8
u8 has_step (0/1); optional u16 step_le
v2 default blob:
u8 default_name_len; name utf-8
u8 target_count
each: u8 len; target name utf-8
Legacy v1: sections are UTF-8 JSON text (see ``parse_binary_envelope_v1``).
Keep ``5 + lp + ls + ld`` ≤ 245 for a single ESP-NOW frame body.
"""
from __future__ import annotations
import json
import struct
from typing import Any, Dict, List, Optional, Tuple
BINARY_ENVELOPE_VERSION_1 = 1
BINARY_ENVELOPE_VERSION_2 = 2
HEADER_LEN = 5
def brightness_wire_from_0_255(value: int) -> int:
"""Map device brightness 0–255 to wire 0–127."""
v = max(0, min(255, int(value)))
return (v * 127 + 127) // 255
def brightness_0_255_from_wire(wire: int) -> int:
"""Map wire 0–127 to device brightness 0–255."""
w = max(0, min(127, int(wire)))
return min(255, (w * 255) // 127)
def _clamp_i16(x: int) -> int:
x = int(x)
return max(-32768, min(32767, x))
def _colors_to_rgb_list(colors: Any) -> List[Tuple[int, int, int]]:
out: List[Tuple[int, int, int]] = []
if not colors:
return out
for c in colors:
if isinstance(c, str):
h = c.strip().lstrip("#")
if len(h) >= 6:
out.append(
(int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16))
)
elif isinstance(c, (list, tuple)) and len(c) >= 3:
out.append((int(c[0]), int(c[1]), int(c[2])))
return out
def _pack_preset_dict(name: str, preset: Dict[str, Any]) -> bytes:
pname = name.encode("utf-8")
if len(pname) > 250:
raise ValueError("preset name too long")
pattern = str(preset.get("p") or preset.get("pattern", "off")).encode("utf-8")
if len(pattern) > 250:
raise ValueError("pattern string too long")
rgbs = _colors_to_rgb_list(preset.get("c") or preset.get("colors") or [])
if len(rgbs) > 255:
raise ValueError("too many colours")
delay = max(0, min(65535, int(preset.get("d") or preset.get("delay", 100))))
br = max(0, min(255, int(preset.get("b") or preset.get("brightness", 127))))
auto = 1 if preset.get("a", preset.get("auto", True)) else 0
parts = [
bytes([len(pname)]),
pname,
bytes([len(pattern)]),
pattern,
bytes([len(rgbs)]),
]
for r, g, b in rgbs:
parts.append(bytes([r & 255, g & 255, b & 255]))
n1 = _clamp_i16(preset.get("n1", 0))
n2 = _clamp_i16(preset.get("n2", 0))
n3 = _clamp_i16(preset.get("n3", 0))
n4 = _clamp_i16(preset.get("n4", 0))
n5 = _clamp_i16(preset.get("n5", 0))
n6 = _clamp_i16(preset.get("n6", 0))
parts.append(
struct.pack(
"<HBBhhhhhh",
delay,
br,
auto,
n1,
n2,
n3,
n4,
n5,
n6,
)
)
return b"".join(parts)
def _pack_presets_blob(presets: Dict[str, Any]) -> bytes:
items = [(k, v) for k, v in presets.items() if isinstance(v, dict)]
out = [bytes([len(items)])]
for name, pdata in items:
out.append(_pack_preset_dict(str(name), pdata))
return b"".join(out)
def _pack_select_blob(select: Dict[str, Any]) -> bytes:
out = [bytes([len(select)])]
for device, sel in select.items():
dev_b = str(device).encode("utf-8")
if len(dev_b) > 250:
raise ValueError("device name too long")
if isinstance(sel, (list, tuple)) and sel:
pn = str(sel[0]).encode("utf-8")
step = sel[1] if len(sel) > 1 else None
else:
pn = str(sel).encode("utf-8")
step = None
if len(pn) > 250:
raise ValueError("preset name too long")
if step is None:
out.append(
bytes([len(dev_b)])
+ dev_b
+ bytes([len(pn)])
+ pn
+ bytes([0])
)
else:
s = int(step)
if s < 0 or s > 65535:
raise ValueError("step out of range")
out.append(
bytes([len(dev_b)])
+ dev_b
+ bytes([len(pn)])
+ pn
+ bytes([1])
+ struct.pack("<H", s)
)
return b"".join(out)
def _pack_default_blob(default: str, targets: Optional[list]) -> bytes:
name_b = str(default).encode("utf-8")
if len(name_b) > 250:
raise ValueError("default name too long")
tlist = list(targets) if targets else []
if len(tlist) > 255:
raise ValueError("too many targets")
out = [bytes([len(name_b)]), name_b, bytes([len(tlist)])]
for t in tlist:
tb = str(t).encode("utf-8")
if len(tb) > 250:
raise ValueError("target name too long")
out.append(bytes([len(tb)]))
out.append(tb)
return b"".join(out)
def pack_binary_envelope_v2(
*,
presets: Optional[Dict[str, Any]] = None,
select: Optional[Dict[str, Any]] = None,
default: Optional[str] = None,
default_targets: Optional[list] = None,
brightness_0_255: Optional[int] = None,
) -> bytes:
"""Build a v2 envelope (native binary sections, no JSON)."""
presets_bytes = (
_pack_presets_blob(presets) if presets is not None and presets else b""
)
select_bytes = (
_pack_select_blob(select) if select is not None and select else b""
)
default_bytes = (
_pack_default_blob(default, default_targets)
if default is not None
else b""
)
lp = len(presets_bytes)
ls = len(select_bytes)
ld = len(default_bytes)
if lp > 255 or ls > 255 or ld > 255:
raise ValueError("binary envelope section exceeds 255 bytes")
br_wire = (
255
if brightness_0_255 is None
else brightness_wire_from_0_255(brightness_0_255)
)
header = bytes([BINARY_ENVELOPE_VERSION_2, br_wire, lp, ls, ld])
return header + presets_bytes + select_bytes + default_bytes
def pack_binary_envelope_v1(
*,
presets: Optional[Dict[str, Any]] = None,
select: Optional[Dict[str, Any]] = None,
default: Optional[str] = None,
default_targets: Optional[list] = None,
brightness_0_255: Optional[int] = None,
) -> bytes:
"""Legacy: JSON UTF-8 fragments (version byte 1). Prefer ``pack_binary_envelope_v2``."""
if presets is None:
presets_bytes = b""
else:
presets_bytes = json.dumps(presets, separators=(",", ":")).encode("utf-8")
if select is None:
select_bytes = b""
else:
select_bytes = json.dumps(select, separators=(",", ":")).encode("utf-8")
default_obj: Optional[Dict[str, Any]] = None
if default is not None:
default_obj = {
"default": default,
"targets": list(default_targets) if default_targets else [],
}
default_bytes = (
json.dumps(default_obj, separators=(",", ":")).encode("utf-8")
if default_obj is not None
else b""
)
lp = len(presets_bytes)
ls = len(select_bytes)
ld = len(default_bytes)
if lp > 255 or ls > 255 or ld > 255:
raise ValueError("binary envelope fragment exceeds 255 bytes")
br_wire = (
255
if brightness_0_255 is None
else brightness_wire_from_0_255(brightness_0_255)
)
header = bytes([BINARY_ENVELOPE_VERSION_1, br_wire, lp, ls, ld])
return header + presets_bytes + select_bytes + default_bytes
def _decode_preset_record(
buf: bytes, off: int
) -> Tuple[str, Dict[str, Any], int]:
if off + 1 > len(buf):
raise ValueError("truncated")
nl = buf[off]
off += 1
if off + nl > len(buf):
raise ValueError("truncated")
name = buf[off : off + nl].decode("utf-8")
off += nl
if off + 1 > len(buf):
raise ValueError("truncated")
pl = buf[off]
off += 1
if off + pl > len(buf):
raise ValueError("truncated")
pattern = buf[off : off + pl].decode("utf-8")
off += pl
if off + 1 > len(buf):
raise ValueError("truncated")
nc = buf[off]
off += 1
if off + nc * 3 > len(buf):
raise ValueError("truncated")
colors: List[str] = []
for _ in range(nc):
r, g, b = buf[off], buf[off + 1], buf[off + 2]
off += 3
colors.append(f"#{r:02x}{g:02x}{b:02x}")
if off + 16 > len(buf):
raise ValueError("truncated")
delay, br, auto, n1, n2, n3, n4, n5, n6 = struct.unpack_from(
"<HBBhhhhhh", buf, off
)
off += 16
preset = {
"p": pattern,
"c": colors,
"d": delay,
"b": br,
"a": bool(auto),
"n1": n1,
"n2": n2,
"n3": n3,
"n4": n4,
"n5": n5,
"n6": n6,
}
return name, preset, off
def _decode_presets_blob(chunk: bytes) -> Dict[str, Any]:
if not chunk:
return {}
off = 0
if off + 1 > len(chunk):
raise ValueError("truncated")
count = chunk[off]
off += 1
out: Dict[str, Any] = {}
for _ in range(count):
name, preset, off = _decode_preset_record(chunk, off)
out[name] = preset
if off != len(chunk):
raise ValueError("presets blob length mismatch")
return out
def _decode_select_blob(chunk: bytes) -> Dict[str, Any]:
if not chunk:
return {}
off = 0
if off + 1 > len(chunk):
raise ValueError("truncated")
count = chunk[off]
off += 1
out: Dict[str, Any] = {}
for _ in range(count):
if off + 1 > len(chunk):
raise ValueError("truncated")
dl = chunk[off]
off += 1
if off + dl > len(chunk):
raise ValueError("truncated")
device = chunk[off : off + dl].decode("utf-8")
off += dl
if off + 1 > len(chunk):
raise ValueError("truncated")
pl = chunk[off]
off += 1
if off + pl > len(chunk):
raise ValueError("truncated")
pname = chunk[off : off + pl].decode("utf-8")
off += pl
if off + 1 > len(chunk):
raise ValueError("truncated")
has_step = chunk[off]
off += 1
if has_step:
if off + 2 > len(chunk):
raise ValueError("truncated")
step = struct.unpack_from("<H", chunk, off)[0]
off += 2
out[device] = [pname, step]
else:
out[device] = [pname]
if off != len(chunk):
raise ValueError("select blob length mismatch")
return out
def _decode_default_blob(chunk: bytes) -> Tuple[Optional[str], list]:
if not chunk:
return None, []
off = 0
if off + 1 > len(chunk):
raise ValueError("truncated")
nl = chunk[off]
off += 1
if off + nl > len(chunk):
raise ValueError("truncated")
default_name = chunk[off : off + nl].decode("utf-8") if nl else ""
off += nl
if off + 1 > len(chunk):
raise ValueError("truncated")
nt = chunk[off]
off += 1
targets: List[str] = []
for _ in range(nt):
if off + 1 > len(chunk):
raise ValueError("truncated")
tl = chunk[off]
off += 1
if off + tl > len(chunk):
raise ValueError("truncated")
targets.append(chunk[off : off + tl].decode("utf-8"))
off += tl
if off != len(chunk):
raise ValueError("default blob length mismatch")
return default_name, targets
def parse_binary_envelope_v2(buf: bytes) -> Optional[Dict[str, Any]]:
"""Decode native-binary v2 envelope into the v1 API dict shape."""
if not isinstance(buf, (bytes, bytearray)) or len(buf) < HEADER_LEN:
return None
if buf[0] != BINARY_ENVELOPE_VERSION_2:
return None
lp, ls, ld = buf[2], buf[3], buf[4]
need = HEADER_LEN + lp + ls + ld
if len(buf) != need:
return None
off = HEADER_LEN
presets_chunk = buf[off : off + lp]
off += lp
select_chunk = buf[off : off + ls]
off += ls
default_chunk = buf[off : off + ld]
data: Dict[str, Any] = {"v": "1"}
br = buf[1]
if br < 128:
data["b"] = brightness_0_255_from_wire(br)
try:
if lp:
data["presets"] = _decode_presets_blob(bytes(presets_chunk))
if ls:
data["select"] = _decode_select_blob(bytes(select_chunk))
if ld:
dname, targets = _decode_default_blob(bytes(default_chunk))
data["default"] = dname
data["targets"] = targets
except (ValueError, UnicodeError):
return None
return data
def parse_binary_envelope_v1(buf: bytes) -> Optional[Dict[str, Any]]:
"""
Decode legacy v1 bytes (JSON text blobs) into a v1 API dict.
Returns None if ``buf`` is not a valid v1 envelope.
"""
if not isinstance(buf, (bytes, bytearray)) or len(buf) < HEADER_LEN:
return None
if buf[0] != BINARY_ENVELOPE_VERSION_1:
return None
lp, ls, ld = buf[2], buf[3], buf[4]
need = HEADER_LEN + lp + ls + ld
if len(buf) != need:
return None
off = HEADER_LEN
presets_chunk = buf[off : off + lp]
off += lp
select_chunk = buf[off : off + ls]
off += ls
default_chunk = buf[off : off + ld]
data: Dict[str, Any] = {"v": "1"}
br = buf[1]
if br < 128:
data["b"] = brightness_0_255_from_wire(br)
if lp:
try:
data["presets"] = json.loads(presets_chunk.decode("utf-8"))
except (ValueError, UnicodeError):
return None
if ls:
try:
data["select"] = json.loads(select_chunk.decode("utf-8"))
except (ValueError, UnicodeError):
return None
if ld:
try:
extra = json.loads(default_chunk.decode("utf-8"))
except (ValueError, UnicodeError):
return None
if isinstance(extra, dict):
for k, v in extra.items():
data[k] = v
return data
def parse_binary_envelope(buf: bytes) -> Optional[Dict[str, Any]]:
"""Try v2 (native binary), then v1 (JSON fragments)."""
d = parse_binary_envelope_v2(buf)
if d is not None:
return d
return parse_binary_envelope_v1(buf)
+1 -3
View File
@@ -1,6 +1,4 @@
import sys
sys.path.insert(0, "../../src")
from util.binary_envelope import pack_binary_envelope_v2
from binary_envelope import pack_binary_envelope_v2
p = {"p":"chase","c":["#ff0000","#0f8"],"d":120,"b":200,"a":False,"n1":5,"n2":-3,"n3":0,"n4":7,"n5":0,"n6":300}
p2 = {"pattern":"on","colors":["#102030"],"delay":0,"brightness":0,"auto":True}
a = pack_binary_envelope_v2(presets={"7":p,"8":p2}, brightness_0_255=128).hex()
+26 -20
View File
@@ -1,19 +1,16 @@
#!/usr/bin/env bash
# Minify and gzip the web UI into v2/www_dist for the `www` LittleFS partition.
# Usage: tools/build_web.sh (needs node/npx; WWW_MAX = partition size in bytes)
# Minify and gzip the web UI into v2/www_dist and pack it into www_dist/www.pack, which the
# firmware embeds (main/CMakeLists.txt). Usage: tools/build_web.sh (needs node/npx; WWW_MAX = size limit in bytes)
set -euo pipefail
cd "$(dirname "$0")/.."
SRC=../src
SRC=web
OUT=www_dist
MAX=${WWW_MAX:-1048576}
MAX=${WWW_MAX:-524288}
rm -rf "$OUT"; mkdir -p "$OUT/static"
# Legacy files the v2 UI does not load
SKIP=" app.js main.js rgb-slider.js styles.css "
for f in "$SRC"/static/*; do
[[ -f $f ]] || continue
b=$(basename "$f"); [[ $SKIP == *" $b "* ]] && continue
b=$(basename "$f")
case $b in
*.min.js) cp "$f" "$OUT/static/$b" ;;
*.js|*.css) npx --yes esbuild@0.25.0 "$f" --minify --target=es2019 --legal-comments=none \
@@ -21,20 +18,10 @@ for f in "$SRC"/static/*; do
*) cp "$f" "$OUT/static/$b" ;;
esac
done
# The Pi does not serve /audio, so the Audio menu entries are added for this build only
# (desktop button row and the mobile dropdown, both just before Help).
tmp=$(mktemp -d)
sed -e "s|<button class=\"btn btn-secondary\" id=\"help-btn\">Help</button>|<button class=\"btn btn-secondary\" id=\"audio-btn\" onclick=\"location.href='/audio'\">Audio</button>\n&|" \
-e "s|<button type=\"button\" data-target=\"help-btn\">Help</button>|<button type=\"button\" data-target=\"audio-btn\">Audio</button>\n&|" \
"$SRC/templates/index.html" > "$tmp/index.html"
cp "$SRC/templates/settings.html" "$tmp/settings.html"
grep -q 'id="audio-btn"' "$tmp/index.html" && [ "$(grep -c 'audio-btn' "$tmp/index.html")" -eq 2 ] \
|| { echo "ERROR: could not add the Audio menu entries to index.html" >&2; exit 1; }
for p in index settings; do
npx --yes html-minifier-terser@7.2.0 --collapse-whitespace --remove-comments \
--minify-css true --minify-js true -o "$OUT/$p.html" "$tmp/$p.html"
--minify-css true --minify-js true -o "$OUT/$p.html" "$SRC/templates/$p.html"
done
rm -rf "$tmp"
# Live audio and beat page (served at /audio)
npx --yes html-minifier-terser@7.2.0 --collapse-whitespace --remove-comments \
@@ -46,4 +33,23 @@ find "$OUT" -name '*.gz' -exec gzip -t {} \;
total=$(find "$OUT" -name '*.gz' -printf '%s\n' | paste -sd+ | bc)
echo "www_dist: $(find "$OUT" -name '*.gz' | wc -l) files, $total bytes (limit $MAX)"
(( total <= MAX )) || { echo "ERROR: web UI exceeds www partition" >&2; exit 1; }
(( total <= MAX )) || { echo "ERROR: web UI exceeds the size limit" >&2; exit 1; }
# One blob for the firmware: "WWW1", then per file u16 name length, u32 data length, name (no .gz),
# data; a zero name length ends it. Little-endian, read by main/web.c.
python3 - "$OUT" <<'PY'
import os, struct, sys
root = sys.argv[1]
out = bytearray(b"WWW1")
for dirpath, _, names in sorted(os.walk(root)):
for n in sorted(names):
if not n.endswith(".gz"):
continue
full = os.path.join(dirpath, n)
name = os.path.relpath(full, root)[:-3].encode()
data = open(full, "rb").read()
out += struct.pack("<HI", len(name), len(data)) + name + data
out += struct.pack("<H", 0)
open(os.path.join(root, "www.pack"), "wb").write(out)
print("www.pack: %d bytes" % len(out))
PY
+44 -15
View File
@@ -1,26 +1,55 @@
#!/usr/bin/env python3
"""Upload a firmware image to the controller over Ethernet.
"""Upload the firmware (which includes the web UI) to the controller over Ethernet.
ota.py <host> [build/led_controller_v2.bin]
ota.py <host> [firmware.bin]
Default is build/led_controller_v2.bin next to this script. The board reboots into the new image.
"""
import http.client
import json
import os
import sys
import time
host = sys.argv[1] if len(sys.argv) > 1 else sys.exit(__doc__)
path = sys.argv[2] if len(sys.argv) > 2 else os.path.join(os.path.dirname(__file__), "..", "build", "led_controller_v2.bin")
size = os.path.getsize(path)
build = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "build")
fw = sys.argv[2] if len(sys.argv) > 2 else os.path.join(build, "led_controller_v2.bin")
conn = http.client.HTTPConnection(host, 80, timeout=60)
conn.request("GET", "/ota")
print("running:", conn.getresponse().read().decode())
print(f"uploading {path} ({size} bytes)")
with open(path, "rb") as f:
conn.request("POST", "/ota", body=f, headers={"Content-Length": str(size),
"Content-Type": "application/octet-stream"})
r = conn.getresponse()
body = r.read().decode()
print(r.status, body)
sys.exit(0 if r.status == 200 else 1)
def info():
try:
c = http.client.HTTPConnection(host, 80, timeout=5)
c.request("GET", "/ota")
r = c.getresponse()
return json.loads(r.read().decode()) if r.status == 200 else None
except (OSError, ValueError):
return None
def upload(path, url):
size = os.path.getsize(path)
print(f"uploading {path} ({size} bytes) to {url}")
c = http.client.HTTPConnection(host, 80, timeout=120)
with open(path, "rb") as f:
c.request("POST", url, body=f, headers={"Content-Length": str(size),
"Content-Type": "application/octet-stream"})
r = c.getresponse()
body = r.read().decode()
print(r.status, body)
if r.status != 200:
sys.exit(1)
time.sleep(3)
for _ in range(30):
i = info()
if i:
print("back up on", i["partition"])
return
time.sleep(1)
sys.exit("controller did not come back within 30 s")
before = info()
print("running:", before)
if before is None:
sys.exit("no OTA endpoint (is this the v2 controller?)")
upload(fw, "/ota")
+188
View File
@@ -0,0 +1,188 @@
// Audio modal: live beat indicators and level from the controller's microphone detector, plus a
// simulated beat (a fixed BPM sent to the drivers, with the microphone ignored while it runs).
document.addEventListener('DOMContentLoaded', () => {
const modal = document.getElementById('audio-modal');
const openBtn = document.getElementById('audio-btn');
if (!modal || !openBtn) return;
const el = (id) => document.getElementById(id);
const beatBtn = el('audio-modal-beat-sync');
const bpmValue = el('audio-bpm-value');
const beatReadout = el('audio-modal-beat-readout');
const barPhase = el('audio-bar-phase-value');
const levelBar = el('audio-input-level-bar');
const levelReadout = el('audio-level-readout');
const simInput = el('audio-simulated-bpm');
const simStatus = el('audio-sim-status');
const simStart = el('audio-sim-start-btn');
const simStop = el('audio-sim-stop-btn');
const SIM_MIN = 60;
const SIM_MAX = 200;
let events = null;
let pollTimer = null;
let simRunning = false;
let simBpm = 120;
let simTimer = null;
let simTick = 0;
const clampSim = (n) => Math.max(SIM_MIN, Math.min(SIM_MAX, Math.round(Number(n) || 120)));
function flash(simulated) {
const cls = simulated ? 'flash-simulated' : 'flash';
beatBtn.classList.add(cls);
setTimeout(() => beatBtn.classList.remove(cls), 90);
}
function showBar(bar, meter, sure) {
if (!bar) {
barPhase.textContent = '';
return;
}
barPhase.textContent = `${bar}/${meter}`;
barPhase.classList.toggle('is-downbeat', bar === 1);
beatBtn.classList.toggle('guess', !sure);
}
function showBpm(bpm, simulated) {
bpmValue.textContent = bpm ? bpm.toFixed(simulated ? 0 : 1) : '--';
beatBtn.classList.toggle('audio-simulated', simulated);
}
// --- detector events -------------------------------------------------------------------
function openEvents() {
if (events || !window.EventSource) return;
events = new EventSource('/beats');
events.addEventListener('beat', (e) => {
if (simRunning) return;
const s = JSON.parse(e.data);
flash(false);
showBpm(s.bpm, false);
beatReadout.textContent = `#${s.n}`;
showBar(s.bar, s.meter, s.sure);
});
events.addEventListener('tempo', (e) => {
if (simRunning) return;
const s = JSON.parse(e.data);
showBpm(s.locked ? s.bpm : 0, false);
});
}
function closeEvents() {
if (events) {
events.close();
events = null;
}
}
// --- level and simulation state --------------------------------------------------------
async function poll() {
try {
const s = await (await fetch('/status', { cache: 'no-store' })).json();
const pct = Math.max(0, Math.min(100, ((s.mic_rms_dbfs + 90) / 90) * 100));
levelBar.style.width = `${pct}%`;
levelBar.parentElement.setAttribute('aria-valuenow', String(Math.round(pct)));
levelReadout.textContent = `${s.mic_rms_dbfs.toFixed(1)} dBFS · ${s.mic_spl_db.toFixed(0)} dB`;
const t = await (await fetch('/test/beats', { cache: 'no-store' })).json();
setSimRunning(!!t.running);
} catch (e) {
/* controller briefly unreachable */
}
if (modal.classList.contains('active')) pollTimer = setTimeout(poll, 500);
}
function setSimRunning(on) {
if (on === simRunning && (on === (simTimer !== null))) return;
simRunning = on;
simStart.disabled = on;
simStop.disabled = !on;
simStatus.textContent = on ? `Sending ${simBpm} BPM to the drivers; the microphone is ignored.` : '';
clearInterval(simTimer);
simTimer = null;
if (on) {
// The controller does not echo generated beats back, so the indicator runs on its own clock
simTick = 0;
showBpm(simBpm, true);
simTimer = setInterval(() => {
simTick++;
flash(true);
beatReadout.textContent = `#${simTick}`;
showBar(((simTick - 1) % 4) + 1, 4, true);
}, 60000 / simBpm);
} else {
showBpm(0, false);
beatReadout.textContent = '';
showBar(0);
}
}
async function startSim() {
simBpm = clampSim(simInput.value);
simInput.value = simBpm;
simStatus.textContent = '';
const res = await fetch('/test/beats', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ bpm: simBpm, count: 0 }),
});
if (!res.ok) {
simStatus.textContent = 'The controller refused that BPM.';
return;
}
setSimRunning(false);
setSimRunning(true);
fetch('/settings/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ audio_simulated_bpm: simBpm }),
}).catch(() => {});
}
async function stopSim() {
await fetch('/test/beats/stop', { method: 'POST' });
setSimRunning(false);
}
function tap() {
fetch('/tap', { method: 'POST' }).catch(() => {});
}
async function loadSimBpm() {
try {
const s = await (await fetch('/settings', { cache: 'no-store' })).json();
if (s.audio_simulated_bpm != null) simInput.value = clampSim(s.audio_simulated_bpm);
} catch (e) {
/* keep the default */
}
}
// --- open and close --------------------------------------------------------------------
function open() {
modal.classList.add('active');
simStop.disabled = true;
loadSimBpm();
openEvents();
clearTimeout(pollTimer);
poll();
}
function close() {
modal.classList.remove('active');
closeEvents();
clearTimeout(pollTimer);
// The simulation keeps running on the controller; only the local indicator stops
clearInterval(simTimer);
simTimer = null;
}
openBtn.addEventListener('click', open);
el('audio-close-btn').addEventListener('click', close);
simStart.addEventListener('click', startSim);
simStop.addEventListener('click', stopSim);
el('audio-tap-btn').addEventListener('click', tap);
beatBtn.addEventListener('click', tap);
document.addEventListener('keydown', (e) => {
if (!modal.classList.contains('active') || e.repeat) return;
if ((e.key === 't' || e.key === 'T') && !/INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) tap();
});
});
+194
View File
@@ -0,0 +1,194 @@
document.addEventListener('DOMContentLoaded', () => {
const paletteButton = document.getElementById('color-palette-btn');
const paletteModal = document.getElementById('color-palette-modal');
const closeButton = document.getElementById('color-palette-close-btn');
const paletteContainer = document.getElementById('palette-container');
const paletteNewColor = document.getElementById('palette-new-color');
const profileNameDisplay = document.getElementById('palette-current-profile-name');
if (!paletteButton || !paletteModal || !paletteContainer) {
return;
}
let currentProfileId = null;
let currentPaletteId = null;
let currentPalette = [];
let currentProfileName = null;
const renderPalette = () => {
paletteContainer.innerHTML = '';
if (!currentPalette.length) {
const empty = document.createElement('p');
empty.className = 'muted-text';
empty.textContent = 'No colors in palette.';
paletteContainer.appendChild(empty);
return;
}
currentPalette.forEach((color, index) => {
const row = document.createElement('div');
row.className = 'profiles-row';
row.dataset.color = color;
row.style.cssText = 'display: flex; align-items: center; gap: 1rem;';
// Ensure no text content
row.textContent = '';
const swatch = document.createElement('div');
swatch.style.cssText = `
width: 64px;
height: 64px;
border-radius: 8px;
background-color: ${color};
border: 2px solid #4a4a4a;
cursor: pointer;
flex-shrink: 0;
box-shadow: 0 2px 4px rgba(0,0,0,0.3);
`;
swatch.title = color; // Show hex code on hover only
swatch.setAttribute('aria-label', `Color ${color}`);
const removeButton = document.createElement('button');
removeButton.className = 'btn btn-danger btn-small';
removeButton.textContent = 'Remove';
removeButton.style.fontSize = '0.8rem'; // Restore font size for button
removeButton.addEventListener('click', async (e) => {
e.stopPropagation();
const updated = currentPalette.filter((_, i) => i !== index);
await savePalette(updated);
});
row.appendChild(swatch);
row.appendChild(removeButton);
paletteContainer.appendChild(row);
});
};
const loadPalette = async () => {
try {
const currentResponse = await fetch('/profiles/current', {
headers: { Accept: 'application/json' },
});
if (!currentResponse.ok) {
throw new Error('Failed to load current profile');
}
const currentData = await currentResponse.json();
currentProfileId = currentData.id || null;
const profile = currentData.profile || null;
currentProfileName = profile ? profile.name : null;
if (profileNameDisplay) {
profileNameDisplay.textContent = currentProfileName || currentProfileId || 'None';
}
if (!currentProfileId || !profile) {
currentPalette = [];
renderPalette();
return;
}
// Prefer palette_id-based storage; fall back to legacy inline palette.
currentPaletteId = profile.palette_id || profile.paletteId || null;
if (currentPaletteId) {
try {
const palResponse = await fetch(`/palettes/${currentPaletteId}`, {
headers: { Accept: 'application/json' },
});
if (palResponse.ok) {
const palData = await palResponse.json();
currentPalette = (palData.colors) || [];
} else {
currentPalette = [];
}
} catch (e) {
console.error('Failed to load palette by id:', e);
currentPalette = [];
}
} else {
// Legacy: palette stored directly on profile
currentPalette = profile.palette || profile.color_palette || [];
}
renderPalette();
} catch (error) {
console.error('Failed to load palette:', error);
currentPalette = [];
renderPalette();
}
};
const savePalette = async (newPalette) => {
if (!currentProfileId) {
alert('No profile selected.');
return;
}
try {
// Ensure we have a palette ID for this profile.
if (!currentPaletteId) {
const createResponse = await fetch('/palettes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ colors: newPalette }),
});
if (!createResponse.ok) {
throw new Error('Failed to create palette');
}
const pal = await createResponse.json();
currentPaletteId = pal.id || Object.keys(pal)[0];
// Link the new palette to the current profile.
const linkResponse = await fetch('/profiles/current', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
palette_id: currentPaletteId,
}),
});
if (!linkResponse.ok) {
throw new Error('Failed to link palette to profile');
}
} else {
// Update existing palette colors
const updateResponse = await fetch(`/palettes/${currentPaletteId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ colors: newPalette }),
});
if (!updateResponse.ok) {
throw new Error('Failed to save palette');
}
}
currentPalette = newPalette;
renderPalette();
} catch (error) {
console.error('Failed to save palette:', error);
alert('Failed to save palette.');
}
};
const openModal = () => {
paletteModal.classList.add('active');
loadPalette();
};
const closeModal = () => {
paletteModal.classList.remove('active');
};
paletteButton.addEventListener('click', openModal);
if (closeButton) {
closeButton.addEventListener('click', closeModal);
}
if (paletteNewColor) {
const addSelectedColor = async () => {
const color = paletteNewColor.value;
if (!color) {
return;
}
if (currentPalette.includes(color)) {
alert('Color already in palette.');
return;
}
await savePalette([...currentPalette, color]);
};
// Add when the picker closes (user confirms selection).
paletteNewColor.addEventListener('change', addSelectedColor);
}
});
+471
View File
@@ -0,0 +1,471 @@
// Device registry: name, id (storage key), type (led), transport (wifi|espnow), address
const HEX_BOX_COUNT = 12;
/** Last TCP snapshot from WebSocket (so we can apply after async list render). */
let lastTcpSnapshotIps = null;
/** Match server-side ``normalize_tcp_peer_ip`` for WS events vs registry rows. */
function normalizeWifiAddressForMatch(addr) {
let s = String(addr || '').trim();
if (s.toLowerCase().startsWith('::ffff:')) {
s = s.slice(7);
}
return s;
}
const DEVICES_MODAL_POLL_MS = 1000;
let devicesModalLiveTimer = null;
function stopDevicesModalLiveRefresh() {
if (devicesModalLiveTimer != null) {
clearInterval(devicesModalLiveTimer);
devicesModalLiveTimer = null;
}
}
/**
* Refetch registry and re-render the list (no loading spinner). Keeps scroll position.
* Used while the devices modal stays open so new TCP devices, renames, and removals appear live.
*/
async function refreshDevicesListQuiet() {
const modal = document.getElementById('devices-modal');
if (!modal || !modal.classList.contains('active')) return;
const container = document.getElementById('devices-list-modal');
if (!container) return;
const prevTop = container.scrollTop;
try {
const res = await fetch('/devices', { headers: { Accept: 'application/json' } });
if (!res.ok) return;
const data = await res.json();
renderDevicesList(data || {});
container.scrollTop = prevTop;
} catch (_) {
/* ignore */
}
}
function startDevicesModalLiveRefresh() {
stopDevicesModalLiveRefresh();
devicesModalLiveTimer = setInterval(() => {
refreshDevicesListQuiet();
}, DEVICES_MODAL_POLL_MS);
}
function updateWifiRowDot(row, connected) {
const dot = row.querySelector('.device-status-dot');
if (!dot) return;
if ((row.dataset.deviceTransport || '') !== 'wifi') return;
dot.classList.remove('device-status-dot--online', 'device-status-dot--offline', 'device-status-dot--unknown');
if (connected) {
dot.classList.add('device-status-dot--online');
dot.title = 'Connected (Wi-Fi TCP session)';
} else {
dot.classList.add('device-status-dot--offline');
dot.title = 'Not connected (no Wi-Fi TCP session)';
}
dot.setAttribute('aria-label', dot.title);
}
function applyTcpSnapshot(ips) {
const set = new Set(
(ips || []).map((x) => normalizeWifiAddressForMatch(x)).filter(Boolean),
);
const container = document.getElementById('devices-list-modal');
if (!container) return;
container.querySelectorAll('.profiles-row[data-device-transport="wifi"]').forEach((row) => {
const addr = normalizeWifiAddressForMatch(row.dataset.deviceAddress);
updateWifiRowDot(row, set.has(addr));
});
}
/** Keep cached snapshot aligned with incremental WS events (connect/disconnect). */
function mergeTcpSnapshotPresence(ip, connected) {
const n = normalizeWifiAddressForMatch(ip);
if (!n) return;
const prev = lastTcpSnapshotIps;
const set = new Set(
(Array.isArray(prev) ? prev : []).map((x) => normalizeWifiAddressForMatch(x)).filter(Boolean),
);
if (connected) {
set.add(n);
} else {
set.delete(n);
}
lastTcpSnapshotIps = Array.from(set);
}
function makeHexAddressBoxes(container) {
if (!container || container.querySelector('.hex-addr-box')) return;
container.innerHTML = '';
for (let i = 0; i < HEX_BOX_COUNT; i++) {
const input = document.createElement('input');
input.type = 'text';
input.className = 'hex-addr-box';
input.maxLength = 1;
input.autocomplete = 'off';
input.setAttribute('data-index', i);
input.setAttribute('inputmode', 'numeric');
input.setAttribute('aria-label', `Hex digit ${i + 1}`);
input.addEventListener('input', (e) => {
const v = e.target.value.replace(/[^0-9a-fA-F]/g, '');
e.target.value = v;
if (v && e.target.nextElementSibling && e.target.nextElementSibling.classList.contains('hex-addr-box')) {
e.target.nextElementSibling.focus();
}
});
input.addEventListener('keydown', (e) => {
if (e.key === 'Backspace' && !e.target.value && e.target.previousElementSibling) {
e.target.previousElementSibling.focus();
}
});
input.addEventListener('paste', (e) => {
e.preventDefault();
const pasted = (e.clipboardData.getData('text') || '').replace(/[^0-9a-fA-F]/g, '').slice(0, HEX_BOX_COUNT);
const boxes = container.querySelectorAll('.hex-addr-box');
for (let j = 0; j < pasted.length && j < boxes.length; j++) {
boxes[j].value = pasted[j];
}
if (pasted.length > 0) {
const nextIdx = Math.min(pasted.length, boxes.length - 1);
boxes[nextIdx].focus();
}
});
container.appendChild(input);
}
}
function setAddressToBoxes(container, addrStr) {
if (!container) return;
const s = (addrStr || '').replace(/[^0-9a-fA-F]/g, '').slice(0, HEX_BOX_COUNT);
const boxes = container.querySelectorAll('.hex-addr-box');
boxes.forEach((b, i) => {
b.value = s[i] || '';
});
}
function applyTransportVisibility(transport) {
const isWifi = transport === 'wifi';
const esp = document.getElementById('edit-device-address-espnow');
const wifiWrap = document.getElementById('edit-device-address-wifi-wrap');
if (esp) esp.hidden = isWifi;
if (wifiWrap) wifiWrap.hidden = !isWifi;
}
function getAddressForPayload(transport) {
if (transport === 'wifi') {
const el = document.getElementById('edit-device-address-wifi');
const v = (el && el.value.trim()) || '';
return v || null;
}
const boxEl = document.getElementById('edit-device-address-boxes');
if (!boxEl) return null;
const boxes = boxEl.querySelectorAll('.hex-addr-box');
const hex = Array.from(boxes).map((b) => b.value).join('').toLowerCase();
return hex || null;
}
async function loadDevicesModal() {
const container = document.getElementById('devices-list-modal');
if (!container) return;
if (typeof window.getEspnowSocket === 'function') {
window.getEspnowSocket();
}
container.innerHTML = '<span class="muted-text">Loading...</span>';
try {
const response = await fetch('/devices', { headers: { Accept: 'application/json' } });
if (!response.ok) throw new Error('Failed to load devices');
const devices = await response.json();
renderDevicesList(devices || {});
} catch (e) {
console.error('loadDevicesModal:', e);
container.innerHTML = '<span class="muted-text">Failed to load devices.</span>';
}
}
function renderDevicesList(devices) {
const container = document.getElementById('devices-list-modal');
if (!container) return;
container.innerHTML = '';
const ids = Object.keys(devices).filter((k) => devices[k] && typeof devices[k] === 'object');
if (ids.length === 0) {
const p = document.createElement('p');
p.className = 'muted-text';
p.textContent = 'No devices yet. Wi-Fi drivers will appear here when they connect over TCP.';
container.appendChild(p);
return;
}
ids.forEach((devId) => {
const dev = devices[devId];
const t = (dev && dev.type) || 'led';
const tr = (dev && dev.transport) || 'espnow';
const addrRaw = (dev && dev.address) != null ? String(dev.address).trim() : '';
const addrDisplay = addrRaw || '—';
const row = document.createElement('div');
row.className = 'profiles-row';
row.style.display = 'flex';
row.style.alignItems = 'center';
row.style.gap = '0.5rem';
row.style.flexWrap = 'wrap';
row.dataset.deviceId = devId;
row.dataset.deviceTransport = tr;
row.dataset.deviceAddress = addrRaw;
const dot = document.createElement('span');
dot.className = 'device-status-dot';
dot.setAttribute('role', 'img');
const live = dev && Object.prototype.hasOwnProperty.call(dev, 'connected') ? dev.connected : null;
if (live === true) {
dot.classList.add('device-status-dot--online');
dot.title = 'Connected (Wi-Fi TCP session)';
dot.setAttribute('aria-label', dot.title);
} else if (live === false) {
dot.classList.add('device-status-dot--offline');
dot.title = 'Not connected (no Wi-Fi TCP session)';
dot.setAttribute('aria-label', dot.title);
} else {
dot.classList.add('device-status-dot--unknown');
dot.title = 'ESP-NOW — TCP status does not apply';
dot.setAttribute('aria-label', dot.title);
}
const label = document.createElement('span');
label.textContent = (dev && dev.name) || devId;
label.style.flex = '1';
label.style.minWidth = '100px';
const macEl = document.createElement('code');
macEl.className = 'device-row-mac';
macEl.textContent = devId;
macEl.title = 'MAC (registry id)';
const meta = document.createElement('span');
meta.className = 'muted-text';
meta.style.fontSize = '0.85em';
meta.textContent = `${t} · ${tr} · ${addrDisplay}`;
const editBtn = document.createElement('button');
editBtn.className = 'btn btn-secondary btn-small';
editBtn.textContent = 'Edit';
editBtn.addEventListener('click', () => openEditDeviceModal(devId, dev));
const identifyBtn = document.createElement('button');
identifyBtn.className = 'btn btn-primary btn-small';
identifyBtn.type = 'button';
identifyBtn.textContent = 'Identify';
identifyBtn.title = 'Red blink at 10 Hz (~50% brightness) for 2 s, then off (not saved as a preset)';
identifyBtn.addEventListener('click', async () => {
try {
const res = await fetch(`/devices/${encodeURIComponent(devId)}/identify`, {
method: 'POST',
credentials: 'same-origin',
headers: { Accept: 'application/json' },
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
alert(data.error || 'Identify failed');
return;
}
} catch (err) {
console.error(err);
alert('Identify failed');
}
});
const deleteBtn = document.createElement('button');
deleteBtn.className = 'btn btn-secondary btn-small';
deleteBtn.textContent = 'Delete';
deleteBtn.addEventListener('click', async () => {
if (!confirm(`Delete device "${(dev && dev.name) || devId}"?`)) return;
try {
const res = await fetch(`/devices/${encodeURIComponent(devId)}`, { method: 'DELETE' });
if (res.ok) await loadDevicesModal();
else {
const data = await res.json().catch(() => ({}));
alert(data.error || 'Delete failed');
}
} catch (err) {
console.error(err);
alert('Delete failed');
}
});
row.appendChild(dot);
row.appendChild(label);
row.appendChild(macEl);
row.appendChild(meta);
row.appendChild(editBtn);
row.appendChild(identifyBtn);
row.appendChild(deleteBtn);
container.appendChild(row);
});
// Do not re-apply lastTcpSnapshotIps here: it is only updated on WS open and
// device_tcp events; re-applying after each /devices poll overwrites correct
// API "connected" with a stale list and leaves Wi-Fi rows stuck online.
}
function openEditDeviceModal(devId, dev) {
const modal = document.getElementById('edit-device-modal');
const idInput = document.getElementById('edit-device-id');
const storageLabel = document.getElementById('edit-device-storage-id');
const nameInput = document.getElementById('edit-device-name');
const typeSel = document.getElementById('edit-device-type');
const transportSel = document.getElementById('edit-device-transport');
const addressBoxes = document.getElementById('edit-device-address-boxes');
const wifiInput = document.getElementById('edit-device-address-wifi');
if (!modal || !idInput) return;
idInput.value = devId;
if (storageLabel) storageLabel.textContent = devId;
if (nameInput) nameInput.value = (dev && dev.name) || '';
if (typeSel) typeSel.value = (dev && dev.type) || 'led';
const tr = (dev && dev.transport) || 'espnow';
if (transportSel) transportSel.value = tr;
applyTransportVisibility(tr);
setAddressToBoxes(addressBoxes, tr === 'espnow' ? ((dev && dev.address) || '') : '');
if (wifiInput) wifiInput.value = tr === 'wifi' ? ((dev && dev.address) || '') : '';
DEVICE_SETTING_FIELDS.forEach((f) => {
const el = document.getElementById(f.id);
if (el) el.value = dev && dev[f.key] != null ? String(dev[f.key]) : '';
});
modal.classList.add('active');
}
// Driver settings edited in the device dialog: key on the device record, input id, parser (null = leave unchanged)
const DEVICE_SETTING_FIELDS = [
{ key: 'num_leds', id: 'edit-device-num-leds', parse: (v) => Math.max(1, Math.min(2048, Math.round(Number(v)) || 1)) },
{ key: 'color_order', id: 'edit-device-color-order', parse: (v) => v },
{ key: 'startup_mode', id: 'edit-device-startup-mode', parse: (v) => v },
{ key: 'reversed', id: 'edit-device-reversed', parse: (v) => v === 'true' },
{ key: 'max_brightness', id: 'edit-device-max-brightness', parse: (v) => Math.max(0, Math.min(255, Math.round(Number(v)) || 0)) },
];
function readDeviceSettings() {
const out = {};
DEVICE_SETTING_FIELDS.forEach((f) => {
const el = document.getElementById(f.id);
const raw = el ? el.value.trim() : '';
if (raw !== '') out[f.key] = f.parse(raw);
});
return out;
}
async function updateDevice(devId, name, type, transport, address, settings) {
try {
const res = await fetch(`/devices/${encodeURIComponent(devId)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
type: type || 'led',
transport: transport || 'espnow',
address,
...(settings || {}),
}),
});
const data = await res.json().catch(() => ({}));
if (res.ok) {
await loadDevicesModal();
return true;
}
alert(data.error || 'Failed to update device');
return false;
} catch (e) {
console.error('updateDevice:', e);
alert('Failed to update device');
return false;
}
}
document.addEventListener('DOMContentLoaded', () => {
window.addEventListener('deviceTcpStatus', (ev) => {
const { ip, connected } = ev.detail || {};
if (ip == null || typeof connected !== 'boolean') return;
mergeTcpSnapshotPresence(ip, connected);
const norm = normalizeWifiAddressForMatch(ip);
const container = document.getElementById('devices-list-modal');
if (!container) return;
container.querySelectorAll('.profiles-row[data-device-transport="wifi"]').forEach((row) => {
if (normalizeWifiAddressForMatch(row.dataset.deviceAddress) === norm) {
updateWifiRowDot(row, connected);
}
});
});
window.addEventListener('deviceTcpSnapshot', (ev) => {
const ips = ev.detail && ev.detail.connectedIps;
lastTcpSnapshotIps = ips;
applyTcpSnapshot(ips);
});
window.addEventListener('deviceTcpWsOpen', () => {
refreshDevicesListQuiet();
});
makeHexAddressBoxes(document.getElementById('edit-device-address-boxes'));
const transportEdit = document.getElementById('edit-device-transport');
if (transportEdit) {
transportEdit.addEventListener('change', () => {
applyTransportVisibility(transportEdit.value);
});
}
const devicesBtn = document.getElementById('devices-btn');
const devicesModal = document.getElementById('devices-modal');
const devicesCloseBtn = document.getElementById('devices-close-btn');
const editForm = document.getElementById('edit-device-form');
const editCloseBtn = document.getElementById('edit-device-close-btn');
const editDeviceModal = document.getElementById('edit-device-modal');
if (devicesBtn && devicesModal) {
devicesBtn.addEventListener('click', () => {
devicesModal.classList.add('active');
if (typeof window.getEspnowSocket === 'function') {
window.getEspnowSocket();
}
loadDevicesModal();
startDevicesModalLiveRefresh();
});
}
if (devicesCloseBtn) {
devicesCloseBtn.addEventListener('click', () => {
if (devicesModal) devicesModal.classList.remove('active');
});
}
const devicesModalEl = document.getElementById('devices-modal');
if (devicesModalEl) {
new MutationObserver(() => {
if (!devicesModalEl.classList.contains('active')) {
stopDevicesModalLiveRefresh();
}
}).observe(devicesModalEl, { attributes: true, attributeFilter: ['class'] });
}
if (editForm) {
editForm.addEventListener('submit', async (e) => {
e.preventDefault();
const idInput = document.getElementById('edit-device-id');
const nameInput = document.getElementById('edit-device-name');
const typeSel = document.getElementById('edit-device-type');
const transportSel = document.getElementById('edit-device-transport');
const devId = idInput && idInput.value;
if (!devId) return;
const transport = (transportSel && transportSel.value) || 'espnow';
const address = getAddressForPayload(transport);
const ok = await updateDevice(
devId,
nameInput ? nameInput.value.trim() : '',
(typeSel && typeSel.value) || 'led',
transport,
address,
readDeviceSettings()
);
if (ok) editDeviceModal.classList.remove('active');
});
}
if (editCloseBtn) {
editCloseBtn.addEventListener('click', () => editDeviceModal && editDeviceModal.classList.remove('active'));
}
});
+295
View File
@@ -0,0 +1,295 @@
document.addEventListener('DOMContentLoaded', () => {
// Help modal
const helpBtn = document.getElementById('help-btn');
const helpModal = document.getElementById('help-modal');
const helpCloseBtn = document.getElementById('help-close-btn');
const mainMenuBtn = document.getElementById('main-menu-btn');
const mainMenuDropdown = document.getElementById('main-menu-dropdown');
if (helpBtn && helpModal) {
helpBtn.addEventListener('click', () => {
helpModal.classList.add('active');
});
}
if (helpCloseBtn && helpModal) {
helpCloseBtn.addEventListener('click', () => {
helpModal.classList.remove('active');
});
}
// Mobile main menu: forward clicks to existing header buttons
if (mainMenuBtn && mainMenuDropdown) {
mainMenuBtn.addEventListener('click', () => {
mainMenuDropdown.classList.toggle('open');
});
mainMenuDropdown.addEventListener('click', (event) => {
const target = event.target;
if (target && target.matches('button[data-target]')) {
const id = target.getAttribute('data-target');
const realBtn = document.getElementById(id);
if (realBtn) {
realBtn.click();
}
mainMenuDropdown.classList.remove('open');
}
});
}
// Settings modal wiring (reusing existing settings endpoints).
const settingsButton = document.getElementById('settings-btn');
const settingsModal = document.getElementById('settings-modal');
const settingsCloseButton = document.getElementById('settings-close-btn');
const showSettingsMessage = (text, type = 'success') => {
const messageEl = document.getElementById('settings-message');
if (!messageEl) return;
messageEl.textContent = text;
messageEl.className = `message ${type} show`;
setTimeout(() => {
messageEl.classList.remove('show');
}, 5000);
};
async function loadDeviceSettings() {
try {
const response = await fetch('/settings');
const data = await response.json();
const nameInput = document.getElementById('device-name-input');
if (nameInput && data && typeof data === 'object') {
nameInput.value = data.device_name || 'led-controller';
}
const chInput = document.getElementById('wifi-channel-input');
if (chInput && data && typeof data === 'object') {
const ch = data.wifi_channel;
chInput.value =
ch !== undefined && ch !== null && ch !== '' ? String(ch) : '6';
}
const hostInput = document.getElementById('hostname-input');
if (hostInput && staticIpsList && data && typeof data === 'object') {
hostInput.value = data.hostname || '';
staticIpsList.innerHTML = '';
(Array.isArray(data.static_ips) ? data.static_ips : []).forEach(addStaticIpRow);
}
} catch (error) {
console.error('Error loading device settings:', error);
}
}
const staticIpsList = document.getElementById('static-ips-list');
const STATIC_IP_FIELDS = [
['ip', 'IP address', '192.168.1.50'],
['netmask', 'Netmask', '255.255.255.0'],
['gw', 'Gateway', '192.168.1.1'],
['dns', 'DNS (optional)', 'gateway'],
];
function addStaticIpRow(entry = {}) {
if (!staticIpsList) return;
const row = document.createElement('div');
row.className = 'static-ip-row';
row.style.cssText = 'display:flex;flex-wrap:wrap;gap:0.5rem;margin:0.5rem 0;align-items:center;';
STATIC_IP_FIELDS.forEach(([key, label, placeholder]) => {
const input = document.createElement('input');
input.type = 'text';
input.dataset.key = key;
input.placeholder = `${label} (${placeholder})`;
input.title = label;
input.value = entry[key] || '';
input.style.cssText = 'flex:1 1 9rem;min-width:0;';
row.appendChild(input);
});
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'btn btn-secondary';
remove.textContent = 'Remove';
remove.addEventListener('click', () => row.remove());
row.appendChild(remove);
staticIpsList.appendChild(row);
}
const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
const validIp = (v) => {
const m = IPV4.exec(v);
return !!m && m.slice(1).every((o) => Number(o) <= 255);
};
function readStaticIps() {
const out = [];
for (const row of staticIpsList.querySelectorAll('.static-ip-row')) {
const entry = {};
row.querySelectorAll('input').forEach((i) => {
const v = i.value.trim();
if (v) entry[i.dataset.key] = v;
});
if (!Object.keys(entry).length) continue;
if (!entry.ip) throw new Error('Every static IP needs an IP address');
for (const [k, v] of Object.entries(entry)) {
if (!validIp(v)) throw new Error(`"${v}" is not a valid ${k} address`);
}
out.push(entry);
}
return out;
}
const addIpButton = document.getElementById('static-ip-add-btn');
if (addIpButton) addIpButton.addEventListener('click', () => addStaticIpRow());
async function loadAPStatus() {
try {
const response = await fetch('/settings/wifi/ap');
const config = await response.json();
const statusEl = document.getElementById('ap-status');
if (!statusEl) return;
if (config.active) {
statusEl.innerHTML = `
<h4>AP Status: <span class="status-connected">Active</span></h4>
<p><strong>SSID:</strong> ${config.ssid || 'N/A'}</p>
<p><strong>Channel:</strong> ${config.channel || 'Auto'}</p>
<p><strong>IP Address:</strong> ${config.ip || 'N/A'}</p>
`;
} else {
statusEl.innerHTML = `
<h4>AP Status: <span class="status-disconnected">Inactive</span></h4>
<p>Access Point is not currently active</p>
`;
}
if (config.saved_ssid) document.getElementById('ap-ssid').value = config.saved_ssid;
if (config.saved_channel) document.getElementById('ap-channel').value = config.saved_channel;
} catch (error) {
console.error('Error loading AP status:', error);
}
}
if (settingsButton && settingsModal) {
settingsButton.addEventListener('click', () => {
settingsModal.classList.add('active');
// Load current WiFi status/config when opening
loadDeviceSettings();
loadAPStatus();
});
}
if (settingsCloseButton && settingsModal) {
settingsCloseButton.addEventListener('click', () => {
settingsModal.classList.remove('active');
});
}
const deviceForm = document.getElementById('device-form');
if (deviceForm) {
deviceForm.addEventListener('submit', async (e) => {
e.preventDefault();
const nameInput = document.getElementById('device-name-input');
const deviceName = nameInput ? nameInput.value.trim() : '';
if (!deviceName) {
showSettingsMessage('Device name is required', 'error');
return;
}
const chRaw = document.getElementById('wifi-channel-input')
? document.getElementById('wifi-channel-input').value
: '6';
const wifiChannel = parseInt(chRaw, 10);
if (Number.isNaN(wifiChannel) || wifiChannel < 1 || wifiChannel > 11) {
showSettingsMessage('WiFi channel must be between 1 and 11', 'error');
return;
}
try {
const response = await fetch('/settings/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
device_name: deviceName,
wifi_channel: wifiChannel,
}),
});
const result = await response.json();
if (response.ok) {
showSettingsMessage(
'Device settings saved. They will apply on next restart where relevant.',
'success',
);
} else {
showSettingsMessage(`Error: ${result.error || 'Failed to save device name'}`, 'error');
}
} catch (error) {
showSettingsMessage(`Error: ${error.message}`, 'error');
}
});
}
const networkForm = document.getElementById('network-form');
if (networkForm) {
networkForm.addEventListener('submit', async (e) => {
e.preventDefault();
const hostname = document.getElementById('hostname-input').value.trim();
if (hostname && !/^[A-Za-z0-9-]+$/.test(hostname)) {
showSettingsMessage('Hostname may only contain letters, digits and hyphens', 'error');
return;
}
let staticIps;
try {
staticIps = readStaticIps();
} catch (error) {
showSettingsMessage(error.message, 'error');
return;
}
try {
const response = await fetch('/settings/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ hostname, static_ips: staticIps }),
});
const result = await response.json();
if (response.ok) {
showSettingsMessage('Network settings saved. Restart the controller to apply them.', 'success');
} else {
showSettingsMessage(`Error: ${result.error || 'Failed to save network settings'}`, 'error');
}
} catch (error) {
showSettingsMessage(`Error: ${error.message}`, 'error');
}
});
}
const apForm = document.getElementById('ap-form');
if (apForm) {
apForm.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = {
ssid: document.getElementById('ap-ssid').value,
password: document.getElementById('ap-password').value,
channel: document.getElementById('ap-channel').value || null,
};
if (formData.password && formData.password.length > 0 && formData.password.length < 8) {
showSettingsMessage('AP password must be at least 8 characters', 'error');
return;
}
if (formData.channel) {
formData.channel = parseInt(formData.channel, 10);
if (formData.channel < 1 || formData.channel > 11) {
showSettingsMessage('Channel must be between 1 and 11', 'error');
return;
}
}
try {
const response = await fetch('/settings/wifi/ap', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData),
});
const result = await response.json();
if (response.ok) {
showSettingsMessage('Access Point configured successfully!', 'success');
setTimeout(loadAPStatus, 1000);
} else {
showSettingsMessage(`Error: ${result.error || 'Failed to configure AP'}`, 'error');
}
} catch (error) {
showSettingsMessage(`Error: ${error.message}`, 'error');
}
});
}
});
+1
View File
@@ -0,0 +1 @@
var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=dn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true,historyRestoreAsHxRequest:true,reportValidityOfForms:false},parseInterval:null,location:location,_:null,version:"2.0.8"};Q.onLoad=V;Q.process=Ft;Q.on=xe;Q.off=be;Q.trigger=ae;Q.ajax=Ln;Q.find=f;Q.findAll=x;Q.closest=g;Q.remove=_;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=ze;Q.defineExtension=_n;Q.removeExtension=zn;Q.logAll=j;Q.logNone=$;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:se,canAccessLocalStorage:X,findThisElement:Se,filterValues:yn,swap:ze,hasAttribute:s,getAttributeValue:a,getClosestAttributeValue:ne,getClosestMatch:q,getExpressionVars:Rn,getHeaders:mn,getInputValues:dn,getInternalData:oe,getSwapSpecification:bn,getTriggerSpecs:st,getTarget:Ee,makeFragment:D,mergeObjects:le,makeSettleInfo:Sn,oobSwap:Te,querySelectorExt:ue,settleImmediately:Yt,shouldCancel:ht,triggerEvent:ae,triggerErrorEvent:fe,withExtensions:Vt};const de=["get","post","put","delete","patch"];const R=de.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function a(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function te(){return document}function y(e,t){return e.getRootNode?e.getRootNode({composed:t}):te()}function q(e,t){while(e&&!t(e)){e=u(e)}return e||null}function o(e,t,n){const r=a(t,n);const o=a(t,"hx-disinherit");var i=a(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function ne(t,n){let r=null;q(t,function(e){return!!(r=o(t,ce(e),n))});if(r!=="unset"){return r}}function h(e,t){return e instanceof Element&&e.matches(t)}function A(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function L(e){if("parseHTMLUnsafe"in Document){return Document.parseHTMLUnsafe(e)}const t=new DOMParser;return t.parseFromString(e,"text/html")}function N(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function r(e){const t=te().createElement("script");ie(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function i(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(i(e)){const t=r(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){H(e)}finally{e.remove()}}})}function D(e){const t=e.replace(/<head(\s[^>]*)?>[\s\S]*?<\/head>/i,"");const n=A(t);let r;if(n==="html"){r=new DocumentFragment;const i=L(e);N(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=L(t);N(r,i.body);r.title=i.title}else{const i=L('<body><template class="internal-htmx-wrapper">'+t+"</template></body>");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function re(e){if(e){e()}}function t(e,t){return Object.protoLine truncated
+255
View File
@@ -0,0 +1,255 @@
document.addEventListener('DOMContentLoaded', () => {
const openBtn = document.getElementById('led-tool-btn');
const modal = document.getElementById('led-tool-modal');
const closeBtn = document.getElementById('led-tool-close-btn');
const refreshPortsBtn = document.getElementById('led-tool-refresh-ports-btn');
const form = document.getElementById('led-tool-form');
const readBtn = document.getElementById('led-tool-read-btn');
const resetBtn = document.getElementById('led-tool-reset-btn');
const portSelect = document.getElementById('led-tool-port');
const outputEl = document.getElementById('led-tool-output');
const messageEl = document.getElementById('led-tool-message');
if (!openBtn || !modal || !form || !portSelect || !outputEl || !messageEl) {
return;
}
const showMessage = (text, type = 'success') => {
messageEl.textContent = text;
messageEl.className = `message ${type} show`;
};
const setOutput = (text) => {
outputEl.value = text || '';
};
const parseApiResponse = async (response) => {
const bodyText = await response.text();
let data = null;
try {
data = bodyText ? JSON.parse(bodyText) : {};
} catch (error) {
data = { error: bodyText || `HTTP ${response.status}` };
}
return data;
};
const setFieldValue = (id, value) => {
const el = document.getElementById(id);
if (!el) return;
if (value === undefined || value === null) return;
el.value = String(value);
};
const populateFormFromSettings = (settings) => {
if (!settings || typeof settings !== 'object') return false;
setFieldValue('led-tool-name', settings.name);
setFieldValue('led-tool-num-leds', settings.num_leds);
setFieldValue('led-tool-led-pin', settings.led_pin);
setFieldValue('led-tool-brightness', settings.brightness);
setFieldValue('led-tool-transport', settings.transport_type);
setFieldValue('led-tool-ssid', settings.ssid);
setFieldValue('led-tool-password', settings.password);
setFieldValue('led-tool-wifi-channel', settings.wifi_channel);
setFieldValue('led-tool-default', settings.default);
return true;
};
const loadPorts = async () => {
const defaultPort = '/dev/ttyACM0';
try {
const response = await fetch('/led-tool/ports');
const data = await response.json();
const previous = portSelect.value;
portSelect.innerHTML = '<option value="">Select a serial port</option>';
for (const port of data.ports || []) {
const option = document.createElement('option');
option.value = port.device;
option.textContent = `${port.device} - ${port.description || 'Unknown'}`;
portSelect.appendChild(option);
}
if (previous) {
portSelect.value = previous;
} else if ((data.ports || []).some((p) => p.device === defaultPort)) {
portSelect.value = defaultPort;
} else {
const fallback = document.createElement('option');
fallback.value = defaultPort;
fallback.textContent = `${defaultPort} - default`;
portSelect.appendChild(fallback);
portSelect.value = defaultPort;
}
if (!data.led_cli_exists) {
showMessage('led-tool/cli.py was not found on the host.', 'error');
} else if ((data.ports || []).length === 0) {
showMessage('No serial ports found.', 'error');
} else {
showMessage(`Found ${(data.ports || []).length} serial port(s).`, 'success');
}
} catch (error) {
showMessage(`Failed to read serial ports: ${error.message}`, 'error');
}
};
openBtn.addEventListener('click', () => {
modal.classList.add('active');
loadPorts();
});
if (closeBtn) {
closeBtn.addEventListener('click', () => {
modal.classList.remove('active');
});
}
if (refreshPortsBtn) {
refreshPortsBtn.addEventListener('click', () => {
loadPorts();
});
}
if (readBtn) {
readBtn.addEventListener('click', async () => {
const port = portSelect.value.trim();
if (!port) {
showMessage('Select a serial port first.', 'error');
return;
}
setOutput('Reading settings from device...');
showMessage('Reading settings over USB...', 'success');
try {
const response = await fetch(`/led-tool/settings?port=${encodeURIComponent(port)}`);
const data = await parseApiResponse(response);
if (!response.ok) {
showMessage(data.error || 'Read failed.', 'error');
setOutput(data.error || 'Request failed.');
return;
}
const output = [
`exit code: ${data.returncode}`,
'',
'stdout:',
data.stdout || '(none)',
'',
'stderr:',
data.stderr || '(none)',
].join('\n');
setOutput(output);
if (data.ok) {
const populated = populateFormFromSettings(data.settings);
if (populated) {
showMessage('Settings read and fields populated.', 'success');
} else {
showMessage('Settings read successfully.', 'success');
}
} else {
showMessage('Read completed with errors. Check output.', 'error');
}
} catch (error) {
showMessage(`Request failed: ${error.message}`, 'error');
setOutput(error.message);
}
});
}
if (resetBtn) {
resetBtn.addEventListener('click', async () => {
const port = portSelect.value.trim();
if (!port) {
showMessage('Select a serial port first.', 'error');
return;
}
setOutput('Resetting device and following output...');
showMessage('Resetting device over USB...', 'success');
try {
const response = await fetch('/led-tool/reset', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ port }),
});
const data = await parseApiResponse(response);
if (!response.ok) {
showMessage(data.error || 'Reset failed.', 'error');
setOutput(data.error || 'Request failed.');
return;
}
const output = [
`exit code: ${data.returncode}`,
'',
'stdout:',
data.stdout || '(none)',
'',
'stderr:',
data.stderr || '(none)',
].join('\n');
setOutput(output);
if (data.ok) {
showMessage('Device reset complete.', 'success');
} else {
showMessage('Reset completed with errors. Check output.', 'error');
}
} catch (error) {
showMessage(`Request failed: ${error.message}`, 'error');
setOutput(error.message);
}
});
}
form.addEventListener('submit', async (event) => {
event.preventDefault();
const port = portSelect.value.trim();
if (!port) {
showMessage('Select a serial port first.', 'error');
return;
}
const payload = {
port,
name: document.getElementById('led-tool-name')?.value?.trim() || '',
num_leds: document.getElementById('led-tool-num-leds')?.value?.trim() || '',
led_pin: document.getElementById('led-tool-led-pin')?.value?.trim() || '',
brightness: document.getElementById('led-tool-brightness')?.value?.trim() || '',
transport: document.getElementById('led-tool-transport')?.value?.trim() || '',
ssid: document.getElementById('led-tool-ssid')?.value?.trim() || '',
password: document.getElementById('led-tool-password')?.value?.trim() || '',
wifi_channel: document.getElementById('led-tool-wifi-channel')?.value?.trim() || '',
default: document.getElementById('led-tool-default')?.value?.trim() || '',
};
setOutput('Running led-tool command...');
showMessage('Running command over USB...', 'success');
try {
const response = await fetch('/led-tool/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
const data = await parseApiResponse(response);
if (!response.ok) {
showMessage(data.error || 'Command failed.', 'error');
setOutput(data.error || 'Request failed.');
return;
}
const output = [
`exit code: ${data.returncode}`,
'',
'stdout:',
data.stdout || '(none)',
'',
'stderr:',
data.stderr || '(none)',
].join('\n');
setOutput(output);
if (data.ok) {
showMessage('Settings applied via USB.', 'success');
} else {
showMessage('Command completed with errors. Check output.', 'error');
}
} catch (error) {
showMessage(`Request failed: ${error.message}`, 'error');
setOutput(error.message);
}
});
});
+80
View File
@@ -0,0 +1,80 @@
// Client-side search filter for modal lists (devices, zones, presets).
// Hides .profiles-row children whose text doesn't match; re-applies when the list re-renders.
function rowSearchText(row) {
const parts = [];
row.querySelectorAll('*').forEach((el) => {
if (el.closest('button, .btn')) return;
if (el.children.length === 0 && el.textContent) parts.push(el.textContent);
});
if (row.dataset.deviceId) parts.push(row.dataset.deviceId);
if (row.dataset.deviceAddress) parts.push(row.dataset.deviceAddress);
return parts.join(' ').toLowerCase();
}
function applyListSearch(list, query) {
const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
let shown = 0;
let total = 0;
list.querySelectorAll(':scope > .profiles-row').forEach((row) => {
total += 1;
const text = rowSearchText(row);
const match = terms.every((t) => text.includes(t));
row.classList.toggle('list-search-hidden', !match);
if (match) shown += 1;
});
let empty = list.querySelector(':scope > .list-search-empty');
if (total > 0 && shown === 0 && terms.length) {
if (!empty) {
empty = document.createElement('p');
empty.className = 'muted-text list-search-empty';
empty.textContent = 'No matches.';
list.appendChild(empty);
}
} else if (empty) {
empty.remove();
}
}
function initListSearch(inputId, listId, modalId) {
const input = document.getElementById(inputId);
const list = document.getElementById(listId);
if (!input || !list) return;
let applying = false;
const run = () => {
applying = true;
applyListSearch(list, input.value);
observer.takeRecords();
applying = false;
};
const observer = new MutationObserver(() => {
if (!applying) run();
});
observer.observe(list, { childList: true });
input.addEventListener('input', run);
input.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && input.value) {
e.stopPropagation();
input.value = '';
run();
}
});
// Clear the search each time the modal is opened.
const modal = modalId && document.getElementById(modalId);
if (modal) {
new MutationObserver(() => {
if (modal.classList.contains('active') && input.value) {
input.value = '';
run();
}
}).observe(modal, { attributes: true, attributeFilter: ['class'] });
}
}
document.addEventListener('DOMContentLoaded', () => {
initListSearch('devices-search', 'devices-list-modal', 'devices-modal');
initListSearch('zones-search', 'zones-list-modal', 'zones-modal');
initListSearch('presets-search', 'presets-list', 'presets-modal');
});
+219
View File
@@ -0,0 +1,219 @@
// Pixel outputs (db/output.json): DDP, Art-Net, sACN, USB-DMX fixtures the Pi renders for.
const OUTPUT_PROTOCOL_LABELS = {
ddp: 'DDP',
artnet: 'Art-Net',
sacn: 'sACN',
dmx_serial: 'USB-DMX',
};
async function fetchOutputs() {
const res = await fetch('/outputs', { headers: { Accept: 'application/json' } });
if (!res.ok) throw new Error('Failed to load outputs');
return res.json();
}
function outputSummary(out) {
const proto = OUTPUT_PROTOCOL_LABELS[out.protocol] || out.protocol;
let where = '';
if (out.protocol === 'dmx_serial') {
where = `${out.serial_port || '?'} ch ${out.channel || 1}`;
} else {
where = out.host || (out.protocol === 'sacn' ? 'multicast' : 'broadcast');
if (out.port) where += `:${out.port}`;
if (out.protocol !== 'ddp' && out.universe != null) where += ` u${out.universe}`;
}
return `${proto} · ${where} · ${out.pixel_count} px${out.enabled === false ? ' · disabled' : ''}`;
}
function renderOutputsList(outputs) {
const container = document.getElementById('outputs-list-modal');
if (!container) return;
container.innerHTML = '';
const ids = Object.keys(outputs || {});
if (ids.length === 0) {
const p = document.createElement('p');
p.className = 'muted-text';
p.textContent = 'No outputs yet.';
container.appendChild(p);
return;
}
ids.forEach((id) => {
const out = outputs[id];
const row = document.createElement('div');
row.className = 'profiles-row';
row.style.display = 'flex';
row.style.alignItems = 'center';
row.style.gap = '0.5rem';
row.style.flexWrap = 'wrap';
const label = document.createElement('span');
label.style.flex = '1';
label.innerHTML = '';
const name = document.createElement('strong');
name.textContent = out.name;
const meta = document.createElement('span');
meta.className = 'muted-text';
meta.textContent = ` ${outputSummary(out)}`;
label.appendChild(name);
label.appendChild(meta);
const testBtn = document.createElement('button');
testBtn.type = 'button';
testBtn.className = 'btn btn-secondary btn-small';
testBtn.textContent = 'Test';
testBtn.title = 'Red, green, blue, white, then black';
testBtn.addEventListener('click', async () => {
testBtn.disabled = true;
testBtn.textContent = 'Testing…';
try {
const res = await fetch(`/outputs/${encodeURIComponent(id)}/test`, { method: 'POST' });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || res.statusText);
const st = data.status || {};
testBtn.textContent = st.errors ? `Errors: ${st.errors}` : 'Sent';
if (st.last_error) testBtn.title = st.last_error;
} catch (e) {
testBtn.textContent = 'Failed';
testBtn.title = String(e.message || e);
} finally {
testBtn.disabled = false;
setTimeout(() => { testBtn.textContent = 'Test'; }, 2500);
}
});
const editBtn = document.createElement('button');
editBtn.type = 'button';
editBtn.className = 'btn btn-secondary btn-small';
editBtn.textContent = 'Edit';
editBtn.addEventListener('click', () => openOutputEditor(id, out));
const delBtn = document.createElement('button');
delBtn.type = 'button';
delBtn.className = 'btn btn-danger btn-small';
delBtn.textContent = 'Delete';
delBtn.addEventListener('click', async () => {
if (!confirm(`Delete output "${out.name}"?`)) return;
const res = await fetch(`/outputs/${encodeURIComponent(id)}`, { method: 'DELETE' });
if (!res.ok) {
alert('Failed to delete output.');
return;
}
loadOutputsModal();
});
row.append(label, testBtn, editBtn, delBtn);
container.appendChild(row);
});
}
async function loadOutputsModal() {
const container = document.getElementById('outputs-list-modal');
try {
renderOutputsList(await fetchOutputs());
} catch (e) {
if (container) container.textContent = 'Failed to load outputs.';
}
}
function syncOutputProtocolFields() {
const proto = document.getElementById('edit-output-protocol').value;
document.querySelectorAll('#edit-output-form .engine-field').forEach((el) => {
const list = (el.dataset.protocols || '').split(/\s+/);
el.hidden = !list.includes(proto);
});
}
function setOutputField(id, value) {
const el = document.getElementById(id);
if (!el) return;
if (el.type === 'checkbox') el.checked = !!value;
else el.value = value == null ? '' : value;
}
function openOutputEditor(id, out) {
const o = out || {
name: '', protocol: 'ddp', pixel_count: 60, pixel_offset: 0, color_order: 'rgb',
brightness: 255, fps: 40, channel: 1, dmx_mode: 'enttec_pro', enabled: true, reverse: false,
};
document.getElementById('edit-output-title').textContent = id ? 'Edit output' : 'Add output';
setOutputField('edit-output-id', id || '');
setOutputField('edit-output-name', o.name);
setOutputField('edit-output-protocol', o.protocol);
setOutputField('edit-output-host', o.host);
setOutputField('edit-output-port', o.port);
setOutputField('edit-output-universe', o.universe);
setOutputField('edit-output-serial-port', o.serial_port);
setOutputField('edit-output-dmx-mode', o.dmx_mode || 'enttec_pro');
setOutputField('edit-output-channel', o.channel || 1);
setOutputField('edit-output-pixel-count', o.pixel_count);
setOutputField('edit-output-pixel-offset', o.pixel_offset || 0);
setOutputField('edit-output-color-order', o.color_order || 'rgb');
setOutputField('edit-output-brightness', o.brightness == null ? 255 : o.brightness);
setOutputField('edit-output-fps', o.fps || 40);
setOutputField('edit-output-reverse', o.reverse);
setOutputField('edit-output-enabled', o.enabled !== false);
const err = document.getElementById('edit-output-error');
err.hidden = true;
syncOutputProtocolFields();
document.getElementById('edit-output-modal').classList.add('active');
}
function readOutputForm() {
const val = (id) => document.getElementById(id).value.trim();
const num = (id) => (val(id) === '' ? null : Number(val(id)));
return {
name: val('edit-output-name'),
protocol: val('edit-output-protocol'),
host: val('edit-output-host'),
port: num('edit-output-port'),
universe: num('edit-output-universe'),
serial_port: val('edit-output-serial-port'),
dmx_mode: val('edit-output-dmx-mode'),
channel: num('edit-output-channel') || 1,
pixel_count: num('edit-output-pixel-count'),
pixel_offset: num('edit-output-pixel-offset') || 0,
color_order: val('edit-output-color-order'),
brightness: num('edit-output-brightness'),
fps: num('edit-output-fps'),
reverse: document.getElementById('edit-output-reverse').checked,
enabled: document.getElementById('edit-output-enabled').checked,
};
}
document.addEventListener('DOMContentLoaded', () => {
const btn = document.getElementById('outputs-btn');
const modal = document.getElementById('outputs-modal');
const editModal = document.getElementById('edit-output-modal');
const form = document.getElementById('edit-output-form');
if (!btn || !modal || !form) return;
btn.addEventListener('click', () => {
modal.classList.add('active');
loadOutputsModal();
});
document.getElementById('outputs-close-btn').addEventListener('click', () => modal.classList.remove('active'));
document.getElementById('output-add-btn').addEventListener('click', () => openOutputEditor(null, null));
document.getElementById('edit-output-close-btn').addEventListener('click', () => editModal.classList.remove('active'));
document.getElementById('edit-output-protocol').addEventListener('change', syncOutputProtocolFields);
form.addEventListener('submit', async (e) => {
e.preventDefault();
const id = document.getElementById('edit-output-id').value;
const err = document.getElementById('edit-output-error');
err.hidden = true;
const res = await fetch(id ? `/outputs/${encodeURIComponent(id)}` : '/outputs', {
method: id ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(readOutputForm()),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
err.textContent = data.error || 'Save failed';
err.hidden = false;
return;
}
editModal.classList.remove('active');
loadOutputsModal();
});
});
+582
View File
@@ -0,0 +1,582 @@
document.addEventListener('DOMContentLoaded', () => {
const patternsButton = document.getElementById('patterns-btn');
const patternsModal = document.getElementById('patterns-modal');
const patternsCloseButton = document.getElementById('patterns-close-btn');
const patternsList = document.getElementById('patterns-list');
const patternAddButton = document.getElementById('pattern-add-btn');
const patternSendAllButton = document.getElementById('pattern-send-all-btn');
const patternEditorModal = document.getElementById('pattern-editor-modal');
const patternEditorCloseButton = document.getElementById('pattern-editor-close-btn');
const patternCreateBtn = document.getElementById('pattern-create-btn');
const patternCreateName = document.getElementById('pattern-create-name');
const patternCreateMinDelay = document.getElementById('pattern-create-min-delay');
const patternCreateMaxDelay = document.getElementById('pattern-create-max-delay');
const patternCreateMaxColors = document.getElementById('pattern-create-max-colors');
const patternCreateFile = document.getElementById('pattern-create-file');
const patternCreateCode = document.getElementById('pattern-create-code');
const patternCreateOverwrite = document.getElementById('pattern-create-overwrite');
const patternCreateN = [1, 2, 3, 4, 5, 6, 7, 8].map((i) =>
document.getElementById(`pattern-create-n${i}`),
);
const patternCreateNSection = document.getElementById('pattern-create-n-section');
const patternCreateNEmpty = document.getElementById('pattern-create-n-empty');
if (!patternsButton || !patternsModal || !patternsList) {
return;
}
const coercePresetInt = (v, def = 0) => {
if (typeof v === 'number' && Number.isFinite(v)) {
return v;
}
const t = parseInt(String(v), 10);
return Number.isFinite(t) ? t : def;
};
const getCurrentProfileId = async () => {
try {
const response = await fetch('/profiles/current', { headers: { Accept: 'application/json' } });
if (!response.ok) {
return null;
}
const data = await response.json();
return data && (data.id || (data.profile && data.profile.id)) ? String(data.id || data.profile.id) : null;
} catch (_) {
return null;
}
};
const filterPresetsForCurrentProfile = async (presetsObj) => {
const scoped = presetsObj && typeof presetsObj === 'object' ? presetsObj : {};
const currentProfileId = await getCurrentProfileId();
if (!currentProfileId) {
return scoped;
}
return Object.fromEntries(
Object.entries(scoped).filter(([, preset]) => {
if (!preset || typeof preset !== 'object') return false;
if (!('profile_id' in preset)) return true;
return String(preset.profile_id) === String(currentProfileId);
}),
);
};
const tabDeviceNamesFromSection = (section) => {
if (typeof window.parseTabDeviceNames === 'function') {
return window.parseTabDeviceNames(section);
}
const namesAttr = section && section.getAttribute('data-device-names');
return namesAttr
? namesAttr.split(',').map((n) => n.trim()).filter((n) => n.length > 0)
: [];
};
const postDriverSequence = async (sequence, targetMacs, delayS = 0.05) => {
const body = {
sequence,
targets: Array.isArray(targetMacs) && targetMacs.length ? [...new Set(targetMacs)] : undefined,
delay_s: delayS,
};
const res = await fetch('/presets/push', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
credentials: 'same-origin',
body: JSON.stringify(body),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error((err && err.error) || res.statusText || 'Send failed');
}
return res.json().catch(() => ({}));
};
const nReadableStringFromMeta = (meta, key) => {
if (!meta || typeof meta !== 'object') {
return '';
}
const pm = meta.parameter_mappings;
if (pm && typeof pm === 'object' && typeof pm[key] === 'string') {
const s = pm[key].trim();
if (s) {
return s;
}
}
if (typeof meta[key] === 'string') {
return meta[key].trim();
}
return '';
};
const setPatternEditorNFields = (mode, data) => {
const meta = data && typeof data === 'object' ? data : {};
let visible = 0;
const grid = patternCreateNSection && patternCreateNSection.querySelector('.n-params-grid');
const h3 = patternCreateNSection && patternCreateNSection.querySelector('h3');
for (let i = 1; i <= 8; i += 1) {
const key = `n${i}`;
const labelEl = document.querySelector(`label[for="pattern-create-${key}"]`);
const inputEl = document.getElementById(`pattern-create-${key}`);
const groupEl = labelEl ? labelEl.closest('.n-param-group') : null;
if (mode === 'create') {
if (labelEl) {
labelEl.textContent = `${key}:`;
labelEl.style.display = '';
}
if (inputEl) {
inputEl.value = '';
inputEl.placeholder = 'Readable name (optional)';
inputEl.removeAttribute('aria-label');
}
if (groupEl) {
groupEl.style.display = '';
}
continue;
}
const readable = nReadableStringFromMeta(meta, key);
const show = Boolean(readable);
if (labelEl) {
labelEl.textContent = '';
labelEl.style.display = 'none';
}
if (inputEl) {
inputEl.value = show ? readable : '';
inputEl.placeholder = '';
if (show) {
inputEl.setAttribute('aria-label', readable);
} else {
inputEl.removeAttribute('aria-label');
inputEl.value = '';
}
}
if (groupEl) {
groupEl.style.display = show ? '' : 'none';
}
if (show) {
visible += 1;
}
}
if (mode === 'create') {
if (patternCreateNEmpty) {
patternCreateNEmpty.style.display = 'none';
}
if (grid) {
grid.style.display = '';
}
if (h3) {
h3.style.display = '';
}
if (patternCreateNSection) {
patternCreateNSection.style.display = '';
}
return;
}
if (patternCreateNEmpty) {
patternCreateNEmpty.style.display = visible === 0 ? '' : 'none';
}
if (grid) {
grid.style.display = visible === 0 ? 'none' : '';
}
if (h3) {
h3.style.display = visible === 0 ? 'none' : '';
}
};
const readFileAsText = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result || ''));
reader.onerror = () => reject(reader.error || new Error('read failed'));
reader.readAsText(file);
});
const collectCreatePayload = async () => {
const name = patternCreateName ? patternCreateName.value.trim() : '';
if (!name) {
throw new Error('Pattern name is required.');
}
let code = '';
const fileInput = patternCreateFile && patternCreateFile.files && patternCreateFile.files[0];
if (fileInput) {
code = await readFileAsText(fileInput);
} else if (patternCreateCode && patternCreateCode.value.trim()) {
code = patternCreateCode.value;
}
if (!code.trim()) {
throw new Error('Choose a .py file or paste source code.');
}
const payload = {
name,
code,
min_delay: parseInt(patternCreateMinDelay && patternCreateMinDelay.value, 10) || 0,
max_delay: parseInt(patternCreateMaxDelay && patternCreateMaxDelay.value, 10) || 0,
max_colors: parseInt(patternCreateMaxColors && patternCreateMaxColors.value, 10) || 0,
overwrite: !!(patternCreateOverwrite && patternCreateOverwrite.checked),
};
patternCreateN.forEach((el, idx) => {
const key = `n${idx + 1}`;
if (el && el.value.trim()) {
payload[key] = el.value.trim();
}
});
return payload;
};
const resetCreateForm = () => {
if (patternCreateName) patternCreateName.value = '';
if (patternCreateFile) patternCreateFile.value = '';
if (patternCreateCode) patternCreateCode.value = '';
if (patternCreateMinDelay) patternCreateMinDelay.value = '10';
if (patternCreateMaxDelay) patternCreateMaxDelay.value = '10000';
if (patternCreateMaxColors) patternCreateMaxColors.value = '10';
patternCreateN.forEach((el) => {
if (el) el.value = '';
});
if (patternCreateOverwrite) patternCreateOverwrite.checked = true;
setPatternEditorNFields('create', {});
};
if (patternCreateBtn) {
patternCreateBtn.addEventListener('click', async () => {
try {
const payload = await collectCreatePayload();
const response = await fetch('/patterns/driver', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(payload),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error((data && data.error) || 'Create failed');
}
alert(data.message || 'Pattern created.');
resetCreateForm();
if (patternEditorModal) {
patternEditorModal.classList.remove('active');
}
await loadPatterns();
} catch (e) {
console.error('Create pattern failed:', e);
alert(e.message || 'Failed to create pattern.');
}
});
}
/** on/off are implemented in driver firmware (presets.py), not as OTA ``.py`` files. */
const FIRMWARE_BUILTIN_PATTERNS = new Set(['on', 'off']);
const isFirmwareBuiltinPattern = (patternName) => {
const id = String(patternName || '')
.trim()
.replace(/\.py$/i, '')
.toLowerCase();
return FIRMWARE_BUILTIN_PATTERNS.has(id);
};
const sendPatternToDevices = async (patternName) => {
const response = await fetch(`/patterns/${encodeURIComponent(patternName)}/send`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({}),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error((data && data.error) || 'Failed to send pattern');
}
const sentCount = data && typeof data.sent_count === 'number' ? data.sent_count : null;
if (sentCount === null) {
alert(`Sent "${patternName}" to devices.`);
} else {
alert(`Sent "${patternName}" to ${sentCount} device(s).`);
}
};
const loadPatternMetadata = async (patternName, fallbackData) => {
const raw = String(patternName || '').trim();
const norm = raw.endsWith('.py') ? raw.slice(0, -3).trim() : raw;
try {
const response = await fetch('/patterns/definitions', {
cache: 'no-store',
headers: { Accept: 'application/json' },
});
if (!response.ok) {
throw new Error('Failed to load pattern definitions');
}
const definitions = await response.json();
if (definitions && typeof definitions === 'object') {
if (definitions[raw]) {
return definitions[raw];
}
if (norm && definitions[norm]) {
return definitions[norm];
}
if (norm) {
const lower = norm.toLowerCase();
const matched = Object.keys(definitions).find(
(k) => String(k).toLowerCase() === lower,
);
if (matched) {
return definitions[matched];
}
}
}
} catch (error) {
console.error('Load pattern definitions failed:', error);
}
return fallbackData || {};
};
const loadPatternIntoEditor = async (patternName, fallbackData) => {
const data = await loadPatternMetadata(patternName, fallbackData);
if (patternCreateName) {
patternCreateName.value = patternName;
}
if (patternCreateMinDelay) {
patternCreateMinDelay.value =
data && data.min_delay !== undefined ? String(data.min_delay) : '10';
}
if (patternCreateMaxDelay) {
patternCreateMaxDelay.value =
data && data.max_delay !== undefined ? String(data.max_delay) : '10000';
}
if (patternCreateMaxColors) {
patternCreateMaxColors.value =
data && data.max_colors !== undefined ? String(data.max_colors) : '10';
}
setPatternEditorNFields('edit', data);
if (patternCreateOverwrite) {
patternCreateOverwrite.checked = true;
}
if (patternCreateFile) {
patternCreateFile.value = '';
}
try {
const raw = String(patternName || '').trim();
const fileSegment = /\.py$/i.test(raw) ? raw : `${raw}.py`;
const response = await fetch(`/patterns/ota/file/${encodeURIComponent(fileSegment)}`, {
headers: { Accept: 'text/plain' },
});
if (!response.ok) {
throw new Error('Failed to load pattern file');
}
const source = await response.text();
if (patternCreateCode) {
patternCreateCode.value = source || '';
patternCreateCode.focus();
}
} catch (error) {
console.error('Load pattern source failed:', error);
alert('Could not load pattern source into editor.');
}
};
const renderPatterns = (patterns) => {
patternsList.innerHTML = '';
const entries = Object.entries(patterns || {});
if (!entries.length) {
const empty = document.createElement('p');
empty.className = 'muted-text';
empty.textContent = 'No patterns found.';
patternsList.appendChild(empty);
return;
}
entries.forEach(([patternName, data]) => {
const row = document.createElement('div');
row.className = 'profiles-row';
const label = document.createElement('span');
label.textContent = patternName;
row.appendChild(label);
if (isFirmwareBuiltinPattern(patternName)) {
const note = document.createElement('span');
note.className = 'muted-text';
note.style.fontSize = '0.85em';
note.textContent = 'Built-in (no OTA module)';
row.appendChild(note);
} else {
const sendBtn = document.createElement('button');
sendBtn.className = 'btn btn-primary btn-small';
sendBtn.textContent = 'Send';
sendBtn.addEventListener('click', async () => {
try {
await sendPatternToDevices(patternName);
} catch (error) {
console.error('Send pattern failed:', error);
alert(error.message || 'Failed to send pattern.');
}
});
const editBtn = document.createElement('button');
editBtn.className = 'btn btn-secondary btn-small';
editBtn.textContent = 'Edit';
editBtn.addEventListener('click', async () => {
if (patternEditorModal) {
patternEditorModal.classList.add('active');
}
await loadPatternIntoEditor(patternName, data || {});
});
row.appendChild(editBtn);
row.appendChild(sendBtn);
}
patternsList.appendChild(row);
});
};
async function loadPatterns() {
patternsList.innerHTML = '';
const loading = document.createElement('p');
loading.className = 'muted-text';
loading.textContent = 'Loading patterns...';
patternsList.appendChild(loading);
try {
const response = await fetch('/patterns', {
cache: 'no-store',
headers: { Accept: 'application/json' },
});
if (!response.ok) {
throw new Error('Failed to load patterns');
}
const patterns = await response.json();
renderPatterns(patterns);
} catch (error) {
console.error('Load patterns failed:', error);
patternsList.innerHTML = '';
const errorMessage = document.createElement('p');
errorMessage.className = 'muted-text';
errorMessage.textContent = 'Failed to load patterns.';
patternsList.appendChild(errorMessage);
}
}
const openModal = () => {
patternsModal.classList.add('active');
loadPatterns();
};
const closeModal = () => {
patternsModal.classList.remove('active');
};
patternsButton.addEventListener('click', openModal);
if (patternAddButton) {
patternAddButton.addEventListener('click', () => {
resetCreateForm();
if (patternEditorModal) {
patternEditorModal.classList.add('active');
}
});
}
if (patternEditorCloseButton) {
patternEditorCloseButton.addEventListener('click', () => {
if (patternEditorModal) {
patternEditorModal.classList.remove('active');
}
});
}
if (patternsCloseButton) {
patternsCloseButton.addEventListener('click', closeModal);
}
if (patternSendAllButton) {
patternSendAllButton.addEventListener('click', async () => {
const section = document.querySelector('.presets-section[data-zone-id]');
const zoneId = section ? section.dataset.zoneId : null;
if (!zoneId) {
alert('Could not determine current zone.');
return;
}
const deviceNames = tabDeviceNamesFromSection(section);
if (!deviceNames.length) {
alert('No devices found in the current zone.');
return;
}
try {
const [zoneRes, presetsRes] = await Promise.all([
fetch(`/zones/${zoneId}`, { headers: { Accept: 'application/json' } }),
fetch('/presets', { headers: { Accept: 'application/json' } }),
]);
if (!zoneRes.ok || !presetsRes.ok) {
throw new Error('Failed to load zone presets');
}
const zoneData = await zoneRes.json();
const allPresetsRaw = await presetsRes.json();
const allPresets = await filterPresetsForCurrentProfile(allPresetsRaw);
const zonePresetIds = Array.isArray(zoneData.presets_flat)
? zoneData.presets_flat.map((id) => String(id))
: [];
if (!zonePresetIds.length) {
alert('No presets found in this zone.');
return;
}
const wirePresets = {};
zonePresetIds.forEach((presetId) => {
const preset = allPresets[presetId];
if (!preset) {
return;
}
const colors = Array.isArray(preset.colors) && preset.colors.length
? preset.colors
: ['#FFFFFF'];
wirePresets[presetId] = {
pattern: preset.pattern || 'off',
colors,
delay: typeof preset.delay === 'number' ? preset.delay : 100,
brightness: typeof preset.brightness === 'number'
? preset.brightness
: (typeof preset.br === 'number' ? preset.br : 127),
auto: typeof preset.auto === 'boolean' ? preset.auto : true,
n1: coercePresetInt(preset.n1),
n2: coercePresetInt(preset.n2),
n3: coercePresetInt(preset.n3),
n4: coercePresetInt(preset.n4),
n5: coercePresetInt(preset.n5),
n6: coercePresetInt(preset.n6),
};
});
if (!Object.keys(wirePresets).length) {
alert('No matching presets found to send.');
return;
}
const select = {};
deviceNames.forEach((name) => {
if (name) {
select[name] = zonePresetIds.slice();
}
});
const targetMacs =
typeof window.tabsManager !== 'undefined' &&
typeof window.tabsManager.resolveTabDeviceMacs === 'function'
? await window.tabsManager.resolveTabDeviceMacs(deviceNames)
: [];
const sequence = [
{ v: '1', clear_presets: true, save: true },
{ v: '1', presets: wirePresets, save: true },
];
if (Object.keys(select).length) {
sequence.push({ v: '1', select });
}
await postDriverSequence(sequence, targetMacs, 0.05);
} catch (error) {
console.error('Send all patterns failed:', error);
alert('Failed to send all patterns.');
}
});
}
});
File diff suppressed because it is too large. Load diff
+297
View File
@@ -0,0 +1,297 @@
document.addEventListener("DOMContentLoaded", () => {
const profilesButton = document.getElementById("profiles-btn");
const profilesModal = document.getElementById("profiles-modal");
const profilesCloseButton = document.getElementById("profiles-close-btn");
const profilesList = document.getElementById("profiles-list");
const newProfileInput = document.getElementById("new-profile-name");
const newProfileSeedDjInput = document.getElementById("new-profile-seed-dj");
const createProfileButton = document.getElementById("create-profile-btn");
if (!profilesButton || !profilesModal || !profilesList) {
return;
}
const isEditModeActive = () => {
const toggle = document.querySelector('.ui-mode-toggle');
return !!(toggle && toggle.getAttribute('aria-pressed') === 'true');
};
const updateProfileEditorControlsVisibility = () => {
const editMode = isEditModeActive();
const actions = profilesModal.querySelector('.profiles-actions');
if (actions) {
actions.style.display = editMode ? '' : 'none';
}
};
const openModal = () => {
profilesModal.classList.add("active");
updateProfileEditorControlsVisibility();
loadProfiles();
};
const closeModal = () => {
profilesModal.classList.remove("active");
};
const refreshTabsForActiveProfile = async () => {
// Clear stale current zone so zone controller falls back to first zone of applied profile.
document.cookie = "current_zone=; path=/; max-age=0";
if (window.tabsManager && typeof window.tabsManager.loadTabs === "function") {
await window.tabsManager.loadTabs();
}
if (window.tabsManager && typeof window.tabsManager.loadTabsModal === "function") {
await window.tabsManager.loadTabsModal();
}
};
const renderProfiles = (profiles, currentProfileId) => {
profilesList.innerHTML = "";
let entries = [];
if (Array.isArray(profiles)) {
entries = profiles.map((profileId) => [profileId, {}]);
} else if (profiles && typeof profiles === "object") {
// Make sure we're iterating over profile entries, not metadata
entries = Object.entries(profiles).filter(([key]) => {
// Skip metadata keys like 'current_profile_id' if they exist
return key !== 'current_profile_id' && key !== 'profiles';
});
}
if (entries.length === 0) {
const empty = document.createElement("p");
empty.className = "muted-text";
empty.textContent = "No profiles found.";
profilesList.appendChild(empty);
return;
}
const editMode = isEditModeActive();
entries.forEach(([profileId, profile]) => {
const row = document.createElement("div");
row.className = "profiles-row";
const label = document.createElement("span");
label.textContent = (profile && profile.name) || profileId;
if (String(profileId) === String(currentProfileId)) {
label.textContent = `✓ ${label.textContent}`;
label.style.fontWeight = "bold";
label.style.color = "#FFD700";
}
const applyButton = document.createElement("button");
applyButton.className = "btn btn-secondary btn-small profiles-apply-btn";
applyButton.textContent = "Apply";
applyButton.addEventListener("click", async () => {
try {
const response = await fetch(`/profiles/${profileId}/apply`, {
method: "POST",
headers: { Accept: "application/json" },
});
if (!response.ok) {
throw new Error("Failed to apply profile");
}
await loadProfiles();
await refreshTabsForActiveProfile();
} catch (error) {
console.error("Apply profile failed:", error);
alert("Failed to apply profile.");
}
});
const cloneButton = document.createElement("button");
cloneButton.className = "btn btn-secondary btn-small";
cloneButton.textContent = "Clone";
cloneButton.addEventListener("click", async () => {
const baseName = (profile && profile.name) || profileId;
const suggested = `${baseName}`;
const name = prompt("New profile name:", suggested);
if (name === null) {
return;
}
const trimmed = String(name).trim();
if (!trimmed) {
alert("Profile name cannot be empty.");
return;
}
try {
const response = await fetch(`/profiles/${profileId}/clone`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ name: trimmed }),
});
if (!response.ok) {
throw new Error("Failed to clone profile");
}
const data = await response.json().catch(() => null);
let newProfileId = null;
if (data && typeof data === "object") {
if (data.id) {
newProfileId = String(data.id);
} else {
const ids = Object.keys(data);
if (ids.length > 0) {
newProfileId = String(ids[0]);
}
}
}
if (newProfileId) {
await fetch(`/profiles/${newProfileId}/apply`, {
method: "POST",
headers: { Accept: "application/json" },
});
}
await loadProfiles();
await refreshTabsForActiveProfile();
} catch (error) {
console.error("Clone profile failed:", error);
alert("Failed to clone profile.");
}
});
const deleteButton = document.createElement("button");
deleteButton.className = "btn btn-danger btn-small";
deleteButton.textContent = "Delete";
deleteButton.addEventListener("click", async () => {
const confirmed = confirm(`Delete profile "${label.textContent}"?`);
if (!confirmed) {
return;
}
try {
const response = await fetch(`/profiles/${profileId}`, {
method: "DELETE",
headers: { Accept: "application/json" },
});
if (!response.ok) {
throw new Error("Failed to delete profile");
}
await loadProfiles();
} catch (error) {
console.error("Delete profile failed:", error);
alert("Failed to delete profile.");
}
});
row.appendChild(label);
row.appendChild(applyButton);
if (editMode) {
row.appendChild(cloneButton);
row.appendChild(deleteButton);
}
profilesList.appendChild(row);
});
};
const loadProfiles = async () => {
profilesList.innerHTML = "";
const loading = document.createElement("p");
loading.className = "muted-text";
loading.textContent = "Loading profiles...";
profilesList.appendChild(loading);
try {
const response = await fetch("/profiles", {
headers: { Accept: "application/json" },
});
if (!response.ok) {
throw new Error("Failed to load profiles");
}
const data = await response.json();
// Handle both old format (just profiles object) and new format (with current_profile_id)
const profiles = data.profiles || data;
const currentProfileId = data.current_profile_id || null;
renderProfiles(profiles, currentProfileId);
} catch (error) {
console.error("Load profiles failed:", error);
profilesList.innerHTML = "";
const errorMessage = document.createElement("p");
errorMessage.className = "muted-text";
errorMessage.textContent = "Failed to load profiles.";
profilesList.appendChild(errorMessage);
}
};
const createProfile = async () => {
if (!isEditModeActive()) {
return;
}
if (!newProfileInput) {
return;
}
const name = newProfileInput.value.trim();
if (!name) {
alert("Profile name cannot be empty.");
return;
}
try {
const response = await fetch("/profiles", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name,
seed_dj_zone: !!(newProfileSeedDjInput && newProfileSeedDjInput.checked),
}),
});
if (!response.ok) {
throw new Error("Failed to create profile");
}
const data = await response.json().catch(() => null);
let newProfileId = null;
if (data && typeof data === "object") {
if (data.id) {
newProfileId = String(data.id);
} else {
const ids = Object.keys(data);
if (ids.length > 0) {
newProfileId = String(ids[0]);
}
}
}
if (newProfileId) {
await fetch(`/profiles/${newProfileId}/apply`, {
method: "POST",
headers: { Accept: "application/json" },
});
}
newProfileInput.value = "";
if (newProfileSeedDjInput) {
newProfileSeedDjInput.checked = false;
}
await loadProfiles();
await refreshTabsForActiveProfile();
} catch (error) {
console.error("Create profile failed:", error);
alert("Failed to create profile.");
}
};
profilesButton.addEventListener("click", openModal);
if (profilesCloseButton) {
profilesCloseButton.addEventListener("click", closeModal);
}
if (createProfileButton) {
createProfileButton.addEventListener("click", createProfile);
}
if (newProfileInput) {
newProfileInput.addEventListener("keypress", (event) => {
if (event.key === "Enter") {
createProfile();
}
});
}
// Keep modal controls in sync with run/edit mode.
document.querySelectorAll('.ui-mode-toggle').forEach((btn) => {
btn.addEventListener('click', () => {
if (profilesModal.classList.contains('active')) {
updateProfileEditorControlsVisibility();
loadProfiles();
}
});
});
});
+296
View File
@@ -0,0 +1,296 @@
// Sequences: timed preset chains per zone, run by the Pi-side engine.
const SEQUENCES_POLL_MS = 1000;
let sequencesPollTimer = null;
async function fetchJson(url) {
const res = await fetch(url, { headers: { Accept: 'application/json' }, credentials: 'same-origin' });
if (!res.ok) throw new Error(`${url}: ${res.status}`);
return res.json();
}
async function loadSequenceContext() {
const [sequences, status, zonesData, presets] = await Promise.all([
fetchJson('/sequences'),
fetchJson('/sequences/status'),
fetchJson('/zones'),
fetchJson('/presets'),
]);
const order = Array.isArray(zonesData.zone_order) ? zonesData.zone_order : [];
const zones = {};
order.forEach((zid) => {
if (zonesData.zones && zonesData.zones[zid]) zones[zid] = zonesData.zones[zid];
});
return { sequences, status, zones, presets };
}
function stepSummary(seq, presets, state) {
const steps = seq.steps || [];
const total = steps.reduce((s, st) => s + Number(st.duration_s || 0), 0);
let text = `${steps.length} step${steps.length === 1 ? '' : 's'} · ${total.toFixed(1)} s`;
text += seq.loop ? (seq.repeat_count ? ` · ×${seq.repeat_count}` : ' · loop') : ' · once';
if (state && state.running) {
const p = presets[state.preset_id];
text += ` · ▶ step ${state.step_index + 1}${p ? ` (${p.name})` : ''}`;
}
return text;
}
function renderSequencesList(ctx) {
const container = document.getElementById('sequences-list-modal');
if (!container) return;
const editMode = typeof isEditModeActive === 'function' && isEditModeActive();
container.innerHTML = '';
const ids = Object.keys(ctx.sequences || {}).filter((id) => {
const z = ctx.sequences[id].zone_id;
return z == null || ctx.zones[z]; // only this profile's zones (plus unassigned)
});
if (ids.length === 0) {
const p = document.createElement('p');
p.className = 'muted-text';
p.textContent = 'No sequences yet.';
container.appendChild(p);
return;
}
ids.forEach((id) => {
const seq = ctx.sequences[id];
const state = ctx.status[id];
const running = !!(state && state.running);
const zone = ctx.zones[seq.zone_id];
const row = document.createElement('div');
row.className = 'profiles-row';
row.style.display = 'flex';
row.style.alignItems = 'center';
row.style.gap = '0.5rem';
row.style.flexWrap = 'wrap';
const label = document.createElement('span');
label.style.flex = '1';
const name = document.createElement('strong');
name.textContent = seq.name || `Sequence ${id}`;
const meta = document.createElement('span');
meta.className = 'muted-text';
meta.textContent = ` ${zone ? zone.name : 'no zone'} · ${stepSummary(seq, ctx.presets, state)}`;
label.append(name, meta);
const playBtn = document.createElement('button');
playBtn.type = 'button';
playBtn.className = running ? 'btn btn-danger btn-small' : 'btn btn-primary btn-small';
playBtn.textContent = running ? 'Stop' : 'Play';
playBtn.disabled = !zone || !(seq.steps || []).length;
playBtn.addEventListener('click', async () => {
playBtn.disabled = true;
const res = await fetch(`/sequences/${encodeURIComponent(id)}/${running ? 'stop' : 'play'}`, {
method: 'POST', credentials: 'same-origin',
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
alert(data.error || 'Failed');
}
refreshSequencesList();
});
row.append(label, playBtn);
if (editMode) {
const editBtn = document.createElement('button');
editBtn.type = 'button';
editBtn.className = 'btn btn-secondary btn-small';
editBtn.textContent = 'Edit';
editBtn.addEventListener('click', () => openSequenceEditor(id, seq, ctx));
const delBtn = document.createElement('button');
delBtn.type = 'button';
delBtn.className = 'btn btn-danger btn-small';
delBtn.textContent = 'Delete';
delBtn.addEventListener('click', async () => {
if (!confirm(`Delete sequence "${seq.name}"?`)) return;
await fetch(`/sequences/${encodeURIComponent(id)}`, { method: 'DELETE' });
refreshSequencesList();
});
row.append(editBtn, delBtn);
}
container.appendChild(row);
});
}
let lastSequenceCtx = null;
async function refreshSequencesList() {
try {
lastSequenceCtx = await loadSequenceContext();
renderSequencesList(lastSequenceCtx);
} catch (e) {
const container = document.getElementById('sequences-list-modal');
if (container && !lastSequenceCtx) container.textContent = 'Failed to load sequences.';
}
}
function stopSequencesPoll() {
if (sequencesPollTimer != null) {
clearInterval(sequencesPollTimer);
sequencesPollTimer = null;
}
}
function addStepRow(presets, step) {
const container = document.getElementById('edit-sequence-steps');
const row = document.createElement('div');
row.className = 'engine-step-row';
const select = document.createElement('select');
select.className = 'engine-step-preset';
Object.entries(presets || {}).forEach(([pid, p]) => {
const opt = document.createElement('option');
opt.value = pid;
opt.textContent = p.name || pid;
select.appendChild(opt);
});
if (step && step.preset_id != null) select.value = String(step.preset_id);
const dur = document.createElement('input');
dur.type = 'number';
dur.min = '0.5';
dur.max = '600';
dur.step = '0.5';
dur.className = 'engine-step-duration';
dur.value = step && step.duration_s != null ? step.duration_s : 5;
dur.title = 'Seconds';
const unit = document.createElement('span');
unit.className = 'muted-text';
unit.textContent = 's';
const mk = (text, title, fn) => {
const b = document.createElement('button');
b.type = 'button';
b.className = 'btn btn-secondary btn-small';
b.textContent = text;
b.title = title;
b.addEventListener('click', fn);
return b;
};
const up = mk('↑', 'Move up', () => { if (row.previousElementSibling) container.insertBefore(row, row.previousElementSibling); });
const down = mk('↓', 'Move down', () => { if (row.nextElementSibling) container.insertBefore(row.nextElementSibling, row); });
const del = mk('✕', 'Remove step', () => row.remove());
row.append(select, dur, unit, up, down, del);
container.appendChild(row);
}
function openSequenceEditor(id, seq, ctx) {
const s = seq || { name: '', zone_id: null, loop: true, repeat_count: 0, steps: [] };
document.getElementById('edit-sequence-title').textContent = id ? 'Edit sequence' : 'New sequence';
document.getElementById('edit-sequence-id').value = id || '';
document.getElementById('edit-sequence-name').value = s.name || '';
const zoneSel = document.getElementById('edit-sequence-zone');
zoneSel.innerHTML = '';
Object.entries(ctx.zones).forEach(([zid, z]) => {
const opt = document.createElement('option');
opt.value = zid;
opt.textContent = z.name || zid;
zoneSel.appendChild(opt);
});
const currentZone = s.zone_id
|| (window.zonesManager && window.zonesManager.getCurrentZoneId && window.zonesManager.getCurrentZoneId());
if (currentZone && ctx.zones[currentZone]) zoneSel.value = String(currentZone);
document.getElementById('edit-sequence-loop').checked = s.loop !== false;
document.getElementById('edit-sequence-repeat').value = s.repeat_count || 0;
const steps = document.getElementById('edit-sequence-steps');
steps.innerHTML = '';
(s.steps || []).forEach((st) => addStepRow(ctx.presets, st));
if (!(s.steps || []).length) addStepRow(ctx.presets, null);
document.getElementById('edit-sequence-error').hidden = true;
document.getElementById('edit-sequence-modal').classList.add('active');
}
function readSequenceForm() {
const steps = [];
document.querySelectorAll('#edit-sequence-steps .engine-step-row').forEach((row) => {
const pid = row.querySelector('.engine-step-preset').value;
const dur = Number(row.querySelector('.engine-step-duration').value);
if (pid) steps.push({ preset_id: pid, duration_s: Number.isFinite(dur) ? dur : 5 });
});
return {
name: document.getElementById('edit-sequence-name').value.trim(),
zone_id: document.getElementById('edit-sequence-zone').value || null,
loop: document.getElementById('edit-sequence-loop').checked,
repeat_count: Number(document.getElementById('edit-sequence-repeat').value) || 0,
steps,
};
}
// Tell the engine a preset was picked on a zone: renders it on the zone's pixel
// outputs and stops any sequence there. ESP32s were already sent the preset
// by presets.js, so the engine leaves them alone (drivers: false).
async function notifyEngineZonePlay(zoneId, presetId) {
if (!zoneId || !presetId) return;
try {
await fetch(`/zones/${encodeURIComponent(zoneId)}/play`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ preset_id: String(presetId), drivers: false }),
});
} catch (e) {
console.warn('Engine zone play failed:', e);
}
}
window.notifyEngineZonePlay = notifyEngineZonePlay;
document.addEventListener('DOMContentLoaded', () => {
const btn = document.getElementById('sequences-btn');
const modal = document.getElementById('sequences-modal');
const editModal = document.getElementById('edit-sequence-modal');
const form = document.getElementById('edit-sequence-form');
if (!btn || !modal || !form) return;
btn.addEventListener('click', () => {
modal.classList.add('active');
refreshSequencesList();
stopSequencesPoll();
sequencesPollTimer = setInterval(refreshSequencesList, SEQUENCES_POLL_MS);
});
document.getElementById('sequences-close-btn').addEventListener('click', () => {
modal.classList.remove('active');
});
new MutationObserver(() => {
if (!modal.classList.contains('active')) stopSequencesPoll();
}).observe(modal, { attributes: true, attributeFilter: ['class'] });
document.getElementById('sequence-add-btn').addEventListener('click', async () => {
const ctx = lastSequenceCtx || await loadSequenceContext();
openSequenceEditor(null, null, ctx);
});
document.getElementById('edit-sequence-add-step-btn').addEventListener('click', () => {
addStepRow((lastSequenceCtx && lastSequenceCtx.presets) || {}, null);
});
document.getElementById('edit-sequence-close-btn').addEventListener('click', () => {
editModal.classList.remove('active');
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
const id = document.getElementById('edit-sequence-id').value;
const err = document.getElementById('edit-sequence-error');
err.hidden = true;
const body = readSequenceForm();
if (!body.steps.length) {
err.textContent = 'Add at least one step.';
err.hidden = false;
return;
}
const res = await fetch(id ? `/sequences/${encodeURIComponent(id)}` : '/sequences', {
method: id ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
err.textContent = data.error || 'Save failed';
err.hidden = false;
return;
}
editModal.classList.remove('active');
refreshSequencesList();
});
});
File diff suppressed because it is too large. Load diff
+262
View File
@@ -0,0 +1,262 @@
document.addEventListener('DOMContentLoaded', () => {
let selectedIndex = null;
const getTab = async (zoneId) => {
const response = await fetch(`/zones/${zoneId}`, {
headers: { Accept: 'application/json' },
});
if (!response.ok) {
throw new Error('No zone found');
}
return response.json();
};
const saveTabColors = async (zoneId, colors) => {
const response = await fetch(`/zones/${zoneId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ colors }),
});
if (!response.ok) {
throw new Error('Failed to save zone colors');
}
return response.json();
};
const renderPalette = (paletteContainer, colors, onColorChange, onRemoveColor, onReorder) => {
paletteContainer.innerHTML = '';
if (!colors.length) {
const empty = document.createElement('div');
empty.className = 'muted-text';
empty.textContent = 'No colors in palette.';
paletteContainer.appendChild(empty);
return;
}
colors.forEach((color, index) => {
const swatch = document.createElement('div');
swatch.className = 'color-swatch';
swatch.draggable = true;
swatch.dataset.index = String(index);
if (index === selectedIndex) {
swatch.classList.add('selected');
}
const preview = document.createElement('div');
preview.className = 'color-swatch-preview';
preview.style.backgroundColor = color;
const label = document.createElement('span');
label.className = 'color-swatch-label';
label.textContent = color;
const colorPicker = document.createElement('input');
colorPicker.type = 'color';
colorPicker.className = 'color-picker-input';
colorPicker.value = color;
colorPicker.addEventListener('change', async (event) => {
const newColor = event.target.value;
await onColorChange(index, newColor);
});
const removeButton = document.createElement('button');
removeButton.className = 'btn btn-danger btn-small';
removeButton.textContent = 'Remove';
removeButton.addEventListener('click', async (event) => {
event.stopPropagation();
await onRemoveColor(index);
});
swatch.addEventListener('dragstart', (event) => {
event.dataTransfer.setData('text/plain', String(index));
event.dataTransfer.effectAllowed = 'move';
});
swatch.addEventListener('dragover', (event) => {
event.preventDefault();
event.dataTransfer.dropEffect = 'move';
});
swatch.addEventListener('drop', async (event) => {
event.preventDefault();
const fromIndex = parseInt(event.dataTransfer.getData('text/plain'), 10);
const toIndex = parseInt(swatch.dataset.index || '-1', 10);
if (Number.isNaN(fromIndex) || Number.isNaN(toIndex) || fromIndex === toIndex) {
return;
}
await onReorder(fromIndex, toIndex);
});
swatch.appendChild(preview);
swatch.appendChild(label);
swatch.appendChild(colorPicker);
swatch.appendChild(removeButton);
swatch.addEventListener('click', () => {
selectedIndex = index;
renderPalette(paletteContainer, colors, onColorChange, onRemoveColor, onReorder);
colorPicker.click();
});
paletteContainer.appendChild(swatch);
});
};
const initTabPalette = async () => {
const paletteContainer = document.getElementById('color-palette');
const addButton = document.getElementById('zone-color-add-btn');
const addFromPaletteButton = document.getElementById('zone-color-add-from-palette-btn');
const colorInput = document.getElementById('zone-color-input');
if (!paletteContainer || !addButton || !colorInput) {
return;
}
const zoneId = paletteContainer.dataset.zoneId;
if (!zoneId) {
renderPalette(paletteContainer, []);
return;
}
let tabData;
try {
tabData = await getTab(zoneId);
} catch (error) {
renderPalette(paletteContainer, []);
return;
}
let colors = tabData.colors || [];
if (!Array.isArray(colors)) {
colors = [];
}
const onRemoveColor = async (index) => {
if (index === null || index < 0 || index >= colors.length) {
alert('Select a color to remove.');
return;
}
try {
const updated = colors.filter((_, i) => i !== index);
const saved = await saveTabColors(zoneId, updated);
colors = saved.colors || updated;
selectedIndex = null;
renderPalette(paletteContainer, colors, onColorChange, onRemoveColor, onReorder);
} catch (error) {
console.error('Failed to remove color:', error);
alert('Failed to remove color.');
}
};
const onReorder = async (fromIndex, toIndex) => {
if (fromIndex < 0 || fromIndex >= colors.length || toIndex < 0 || toIndex >= colors.length) {
return;
}
try {
const updated = [...colors];
const [moved] = updated.splice(fromIndex, 1);
updated.splice(toIndex, 0, moved);
const saved = await saveTabColors(zoneId, updated);
colors = saved.colors || updated;
selectedIndex = toIndex;
renderPalette(paletteContainer, colors, onColorChange, onRemoveColor, onReorder);
} catch (error) {
console.error('Failed to reorder colors:', error);
alert('Failed to reorder colors.');
}
};
const onColorChange = async (index, newColor) => {
if (!newColor || index < 0 || index >= colors.length) {
return;
}
try {
const updated = [...colors];
updated[index] = newColor;
const saved = await saveTabColors(zoneId, updated);
colors = saved.colors || updated;
selectedIndex = index;
renderPalette(paletteContainer, colors, onColorChange, onRemoveColor, onReorder);
} catch (error) {
console.error('Failed to update color:', error);
alert('Failed to update color.');
}
};
renderPalette(paletteContainer, colors, onColorChange, onRemoveColor, onReorder);
addButton.onclick = async () => {
const newColor = colorInput.value;
if (!newColor) {
return;
}
if (colors.includes(newColor)) {
alert('Color already in palette.');
return;
}
try {
const updated = [...colors, newColor];
const saved = await saveTabColors(zoneId, updated);
colors = saved.colors || updated;
selectedIndex = colors.length - 1;
renderPalette(paletteContainer, colors, onColorChange, onRemoveColor, onReorder);
} catch (error) {
console.error('Failed to add color:', error);
alert('Failed to add color.');
}
};
if (addFromPaletteButton) {
addFromPaletteButton.onclick = () => {
const openButton = document.getElementById('color-palette-btn');
if (openButton) {
openButton.click();
}
const modal = document.getElementById('color-palette-modal');
const modalList = document.getElementById('palette-container');
if (modal) {
modal.classList.add('active');
}
if (!modalList) {
return;
}
const handlePick = async (event) => {
const row = event.target.closest('[data-color]');
if (!row) {
return;
}
const picked = row.dataset.color;
if (!picked) {
return;
}
try {
if (!colors.includes(picked)) {
const updated = [...colors, picked];
const saved = await saveTabColors(zoneId, updated);
colors = saved.colors || updated;
selectedIndex = colors.indexOf(picked);
renderPalette(paletteContainer, colors, onColorChange, onRemoveColor, onReorder);
}
if (modal) {
modal.classList.remove('active');
}
} catch (error) {
console.error('Failed to add palette color:', error);
alert('Failed to add palette color.');
} finally {
modalList.removeEventListener('click', handlePick);
}
};
modalList.addEventListener('click', handlePick);
};
}
};
document.body.addEventListener('htmx:afterSwap', (event) => {
if (event.target && event.target.id === 'zone-content') {
selectedIndex = null;
initTabPalette();
}
});
initTabPalette();
});
File diff suppressed because it is too large. Load diff
+763
View File
@@ -0,0 +1,763 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LED Controller - Zone Mode</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<div class="app-container">
<header>
<div class="zones-container">
<div id="zones-list">
Loading zones...
</div>
</div>
<div class="header-actions">
<div class="header-brightness-control">
<label for="header-brightness-slider">Brightness</label>
<input type="range" id="header-brightness-slider" min="0" max="255" value="255">
</div>
<button class="btn btn-secondary" id="profiles-btn">Profiles</button>
<button class="btn btn-secondary edit-mode-only" id="devices-btn">Devices</button>
<button class="btn btn-secondary edit-mode-only" id="outputs-btn">Outputs</button>
<button class="btn btn-secondary" id="sequences-btn">Sequences</button>
<button class="btn btn-secondary edit-mode-only" id="zones-btn">Zones</button>
<button class="btn btn-secondary edit-mode-only" id="presets-btn">Presets</button>
<button class="btn btn-secondary edit-mode-only" id="patterns-btn">Patterns</button>
<button class="btn btn-secondary edit-mode-only" id="color-palette-btn">Colour Palette</button>
<button class="btn btn-secondary edit-mode-only" id="send-profile-presets-btn">Send Presets</button>
<button class="btn btn-secondary edit-mode-only" id="led-tool-btn">LED Tool</button>
<button class="btn btn-secondary" id="audio-btn">Audio</button>
<button class="btn btn-secondary" id="settings-btn">Settings</button>
<button class="btn btn-secondary" id="help-btn">Help</button>
<button type="button" class="btn btn-secondary ui-mode-toggle" id="ui-mode-toggle" aria-pressed="false" title="Switch preset strip mode — label is the mode you will switch to">Edit mode</button>
</div>
<div class="header-menu-mobile">
<button class="btn btn-secondary" id="main-menu-btn">Menu</button>
<div id="main-menu-dropdown" class="main-menu-dropdown">
<button type="button" class="ui-mode-toggle" id="ui-mode-toggle-mobile" aria-pressed="false">Edit mode</button>
<div class="menu-brightness-control">
<label for="menu-brightness-slider">Brightness</label>
<input type="range" id="menu-brightness-slider" min="0" max="255" value="255">
</div>
<button type="button" data-target="profiles-btn">Profiles</button>
<button type="button" class="edit-mode-only" data-target="devices-btn">Devices</button>
<button type="button" class="edit-mode-only" data-target="outputs-btn">Outputs</button>
<button type="button" data-target="sequences-btn">Sequences</button>
<button type="button" class="edit-mode-only" data-target="zones-btn">Tabs</button>
<button type="button" class="edit-mode-only" data-target="presets-btn">Presets</button>
<button type="button" class="edit-mode-only" data-target="patterns-btn">Patterns</button>
<button type="button" class="edit-mode-only" data-target="color-palette-btn">Colour Palette</button>
<button type="button" class="edit-mode-only" data-target="send-profile-presets-btn">Send Presets</button>
<button type="button" class="edit-mode-only" data-target="led-tool-btn">LED Tool</button>
<button type="button" data-target="audio-btn">Audio</button>
<button type="button" data-target="settings-btn">Settings</button>
<button type="button" data-target="help-btn">Help</button>
</div>
</div>
</header>
<div class="main-content">
<div id="zone-content" class="zone-content">
<div class="zone-content-placeholder">
Select a zone to get started
</div>
</div>
</div>
</div>
<!-- Tabs Modal -->
<div id="zones-modal" class="modal">
<div class="modal-content">
<h2>Tabs</h2>
<div class="profiles-actions zone-modal-create-row">
<input type="text" id="new-zone-name" placeholder="Zone name">
<button class="btn btn-primary" id="create-zone-btn">Create</button>
</div>
<input type="search" id="zones-search" class="list-search-input" placeholder="Search zones…" autocomplete="off">
<div id="zones-list-modal" class="profiles-list"></div>
<div class="modal-actions">
<button class="btn btn-secondary" id="zones-close-btn">Close</button>
</div>
</div>
</div>
<!-- Edit Zone Modal -->
<div id="edit-zone-modal" class="modal">
<div class="modal-content">
<h2>Edit Zone</h2>
<form id="edit-zone-form">
<input type="hidden" id="edit-zone-id">
<div class="modal-actions" style="margin-bottom: 1rem;">
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-secondary" onclick="document.getElementById('edit-zone-modal').classList.remove('active')">Close</button>
</div>
<label>Zone Name:</label>
<input type="text" id="edit-zone-name" placeholder="Enter zone name" required>
<label class="zone-devices-label">Devices in this zone</label>
<div id="edit-zone-devices-editor" class="zone-devices-editor"></div>
<label class="zone-presets-section-label">Presets on this zone</label>
<div id="edit-zone-presets-current" class="profiles-list edit-zone-presets-scroll"></div>
<label class="zone-presets-section-label">Add presets to this zone</label>
<div id="edit-zone-presets-list" class="profiles-list edit-zone-presets-scroll"></div>
</form>
</div>
</div>
<!-- Profiles Modal -->
<div id="profiles-modal" class="modal">
<div class="modal-content">
<h2>Profiles</h2>
<div class="profiles-actions">
<input type="text" id="new-profile-name" placeholder="Profile name">
<button class="btn btn-primary" id="create-profile-btn">Create</button>
</div>
<div class="form-group" style="margin-top: 0.5rem; margin-bottom: 0;">
<label style="display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0;">
<input type="checkbox" id="new-profile-seed-dj">
DJ zone
</label>
</div>
<div id="profiles-list" class="profiles-list"></div>
<div class="modal-actions">
<button class="btn btn-secondary" id="profiles-close-btn">Close</button>
</div>
</div>
</div>
<!-- Devices Modal (registry: Wi-Fi drivers appear when they connect over TCP) -->
<div id="devices-modal" class="modal">
<div class="modal-content">
<h2>Devices</h2>
<input type="search" id="devices-search" class="list-search-input" placeholder="Search devices…" autocomplete="off">
<div id="devices-list-modal" class="profiles-list"></div>
<div class="modal-actions">
<button type="button" class="btn btn-secondary" id="devices-close-btn">Close</button>
</div>
</div>
</div>
<div id="edit-device-modal" class="modal">
<div class="modal-content">
<h2>Edit device</h2>
<form id="edit-device-form">
<input type="hidden" id="edit-device-id">
<p class="muted-text" style="margin-bottom:0.75rem;">MAC (id): <code id="edit-device-storage-id"></code></p>
<label for="edit-device-name">Name</label>
<input type="text" id="edit-device-name" required autocomplete="off">
<label for="edit-device-type" style="margin-top:0.75rem;display:block;">Type</label>
<select id="edit-device-type">
<option value="led">LED</option>
</select>
<label for="edit-device-transport" style="margin-top:0.75rem;display:block;">Transport</label>
<select id="edit-device-transport">
<option value="espnow">ESP-NOW</option>
<option value="wifi">WiFi</option>
</select>
<div id="edit-device-address-espnow" style="margin-top:0.75rem;">
<label class="device-field-label">MAC (12 hex, optional)</label>
<div id="edit-device-address-boxes" class="hex-address-row" aria-label="MAC address"></div>
</div>
<div id="edit-device-address-wifi-wrap" style="margin-top:0.75rem;" hidden>
<label for="edit-device-address-wifi">Address (IP or hostname)</label>
<input type="text" id="edit-device-address-wifi" placeholder="192.168.1.50" autocomplete="off">
</div>
<p class="muted-text" style="margin:0.75rem 0 0;">Driver settings (ESP-NOW drivers; sent when you save, and the driver keeps them). Leave blank to keep the driver's value.</p>
<label for="edit-device-num-leds" style="margin-top:0.5rem;display:block;">LEDs</label>
<input type="number" id="edit-device-num-leds" min="1" max="2048" step="1" placeholder="unchanged">
<label for="edit-device-color-order" style="margin-top:0.75rem;display:block;">Colour order</label>
<select id="edit-device-color-order">
<option value="">unchanged</option>
<option value="rgb">RGB</option><option value="rbg">RBG</option><option value="grb">GRB</option>
<option value="gbr">GBR</option><option value="brg">BRG</option><option value="bgr">BGR</option>
</select>
<label for="edit-device-startup-mode" style="margin-top:0.75rem;display:block;">At power-on</label>
<select id="edit-device-startup-mode">
<option value="">unchanged</option>
<option value="default">Default preset</option>
<option value="last">Last preset</option>
<option value="off">Off</option>
</select>
<label for="edit-device-reversed" style="margin-top:0.75rem;display:block;">Reversed</label>
<select id="edit-device-reversed">
<option value="">unchanged</option>
<option value="false">No</option>
<option value="true">Yes</option>
</select>
<label for="edit-device-max-brightness" style="margin-top:0.75rem;display:block;">Max brightness (0-255)</label>
<input type="number" id="edit-device-max-brightness" min="0" max="255" step="1" placeholder="255 (no limit)">
<div class="modal-actions">
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-secondary" id="edit-device-close-btn">Cancel</button>
</div>
</form>
</div>
</div>
<!-- Outputs Modal (pixel outputs rendered on the Pi: DDP, Art-Net, sACN, USB-DMX) -->
<div id="outputs-modal" class="modal">
<div class="modal-content">
<h2>Outputs</h2>
<p class="muted-text">Pixel outputs the Pi renders for. Add an output's name to a zone's devices to drive it with that zone's presets.</p>
<div id="outputs-list-modal" class="profiles-list"></div>
<div class="modal-actions">
<button type="button" class="btn btn-primary" id="output-add-btn">Add output</button>
<button type="button" class="btn btn-secondary" id="outputs-close-btn">Close</button>
</div>
</div>
</div>
<div id="edit-output-modal" class="modal">
<div class="modal-content">
<h2 id="edit-output-title">Output</h2>
<form id="edit-output-form" class="engine-form">
<input type="hidden" id="edit-output-id">
<label for="edit-output-name">Name</label>
<input type="text" id="edit-output-name" required autocomplete="off">
<label for="edit-output-protocol">Protocol</label>
<select id="edit-output-protocol">
<option value="ddp">DDP</option>
<option value="artnet">Art-Net</option>
<option value="sacn">sACN (E1.31)</option>
<option value="dmx_serial">USB-DMX</option>
</select>
<div class="engine-field" data-protocols="ddp artnet sacn">
<label for="edit-output-host">Host</label>
<input type="text" id="edit-output-host" placeholder="192.168.1.60 (blank = broadcast / multicast)" autocomplete="off">
</div>
<div class="engine-field" data-protocols="ddp artnet sacn">
<label for="edit-output-port">Port (blank = default)</label>
<input type="number" id="edit-output-port" min="1" max="65535">
</div>
<div class="engine-field" data-protocols="artnet sacn">
<label for="edit-output-universe">Start universe</label>
<input type="number" id="edit-output-universe" min="0" max="63999">
</div>
<div class="engine-field" data-protocols="dmx_serial">
<label for="edit-output-serial-port">Serial port</label>
<input type="text" id="edit-output-serial-port" placeholder="/dev/ttyUSB0" autocomplete="off">
</div>
<div class="engine-field" data-protocols="dmx_serial">
<label for="edit-output-dmx-mode">Interface</label>
<select id="edit-output-dmx-mode">
<option value="enttec_pro">Enttec DMX USB Pro</option>
<option value="open_dmx">Open DMX (FTDI)</option>
</select>
</div>
<div class="engine-field" data-protocols="dmx_serial">
<label for="edit-output-channel">Start channel</label>
<input type="number" id="edit-output-channel" min="1" max="512" value="1">
</div>
<label for="edit-output-pixel-count">Pixels</label>
<input type="number" id="edit-output-pixel-count" min="1" value="60">
<label for="edit-output-pixel-offset">Pixel offset in zone frame</label>
<input type="number" id="edit-output-pixel-offset" min="0" value="0">
<label for="edit-output-color-order">Colour order</label>
<select id="edit-output-color-order">
<option value="rgb">RGB</option>
<option value="grb">GRB</option>
<option value="brg">BRG</option>
<option value="rbg">RBG</option>
<option value="gbr">GBR</option>
<option value="bgr">BGR</option>
</select>
<label for="edit-output-brightness">Brightness (0–255)</label>
<input type="number" id="edit-output-brightness" min="0" max="255" value="255">
<label for="edit-output-fps">Max FPS</label>
<input type="number" id="edit-output-fps" min="1" max="120" value="40">
<label class="engine-check"><input type="checkbox" id="edit-output-reverse"> Reverse</label>
<label class="engine-check"><input type="checkbox" id="edit-output-enabled" checked> Enabled</label>
<p id="edit-output-error" class="engine-error" hidden></p>
<div class="modal-actions">
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-secondary" id="edit-output-close-btn">Cancel</button>
</div>
</form>
</div>
</div>
<!-- Sequences Modal (timed preset chains per zone, run on the Pi) -->
<div id="sequences-modal" class="modal">
<div class="modal-content">
<h2>Sequences</h2>
<div id="sequences-list-modal" class="profiles-list"></div>
<div class="modal-actions">
<button type="button" class="btn btn-primary edit-mode-only" id="sequence-add-btn">New sequence</button>
<button type="button" class="btn btn-secondary" id="sequences-close-btn">Close</button>
</div>
</div>
</div>
<div id="edit-sequence-modal" class="modal">
<div class="modal-content">
<h2 id="edit-sequence-title">Sequence</h2>
<form id="edit-sequence-form" class="engine-form">
<input type="hidden" id="edit-sequence-id">
<label for="edit-sequence-name">Name</label>
<input type="text" id="edit-sequence-name" required autocomplete="off">
<label for="edit-sequence-zone">Zone</label>
<select id="edit-sequence-zone" required></select>
<label class="engine-check"><input type="checkbox" id="edit-sequence-loop" checked> Loop</label>
<label for="edit-sequence-repeat">Repeat count (0 = forever, when looping)</label>
<input type="number" id="edit-sequence-repeat" min="0" value="0">
<h3 class="engine-subheading">Steps</h3>
<div id="edit-sequence-steps" class="engine-steps"></div>
<button type="button" class="btn btn-secondary" id="edit-sequence-add-step-btn">Add step</button>
<p id="edit-sequence-error" class="engine-error" hidden></p>
<div class="modal-actions">
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-secondary" id="edit-sequence-close-btn">Cancel</button>
</div>
</form>
</div>
</div>
<!-- Presets Modal -->
<div id="presets-modal" class="modal">
<div class="modal-content">
<h2>Presets</h2>
<div class="modal-actions">
<button class="btn btn-primary" id="preset-add-btn">Add</button>
<button class="btn btn-danger" id="preset-clear-device-btn">Clear Device Presets</button>
</div>
<input type="search" id="presets-search" class="list-search-input" placeholder="Search presets…" autocomplete="off">
<div id="presets-list" class="profiles-list"></div>
<div class="modal-actions">
<button class="btn btn-secondary" id="presets-close-btn">Close</button>
</div>
</div>
</div>
<!-- Preset Editor Modal -->
<div id="preset-editor-modal" class="modal">
<div class="modal-content">
<h2>Preset</h2>
<div class="profiles-actions">
<input type="text" id="preset-name-input" placeholder="Preset name">
<select id="preset-pattern-input">
<option value="">Pattern</option>
</select>
</div>
<label>Colours</label>
<div id="preset-colors-container" class="preset-colors-container"></div>
<div class="profiles-actions">
<input type="color" id="preset-new-color" value="#ffffff" title="Choose colour (auto-adds)">
<button class="btn btn-secondary btn-small" id="preset-add-from-palette-btn">From Palette</button>
</div>
<div class="profiles-actions">
<div class="preset-editor-field">
<label for="preset-brightness-input">Brightness (0–255)</label>
<input type="number" id="preset-brightness-input" placeholder="Brightness" min="0" max="255" value="0">
</div>
<div class="preset-editor-field">
<label for="preset-delay-input">Delay (ms)</label>
<input type="number" id="preset-delay-input" placeholder="Delay" min="0" max="10000" value="0">
</div>
</div>
<div class="n-params-grid">
<div class="n-param-group">
<label for="preset-n1-input" id="preset-n1-label">n1:</label>
<input type="number" id="preset-n1-input" min="0" max="255" value="0" class="n-input">
</div>
<div class="n-param-group">
<label for="preset-n2-input" id="preset-n2-label">n2:</label>
<input type="number" id="preset-n2-input" min="0" max="255" value="0" class="n-input">
</div>
<div class="n-param-group">
<label for="preset-n3-input" id="preset-n3-label">n3:</label>
<input type="number" id="preset-n3-input" min="0" max="255" value="0" class="n-input">
</div>
<div class="n-param-group">
<label for="preset-n4-input" id="preset-n4-label">n4:</label>
<input type="number" id="preset-n4-input" min="0" max="255" value="0" class="n-input">
</div>
<div class="n-param-group">
<label for="preset-n5-input" id="preset-n5-label">n5:</label>
<input type="number" id="preset-n5-input" min="0" max="255" value="0" class="n-input">
</div>
<div class="n-param-group">
<label for="preset-n6-input" id="preset-n6-label">n6:</label>
<input type="number" id="preset-n6-input" min="0" max="255" value="0" class="n-input">
</div>
<div class="n-param-group">
<label for="preset-n7-input" id="preset-n7-label">n7:</label>
<input type="number" id="preset-n7-input" min="0" max="255" value="0" class="n-input">
</div>
<div class="n-param-group">
<label for="preset-n8-input" id="preset-n8-label">n8:</label>
<input type="number" id="preset-n8-input" min="0" max="255" value="0" class="n-input">
</div>
</div>
<div class="modal-actions preset-editor-modal-actions">
<button class="btn btn-secondary" id="preset-send-btn">Try</button>
<button class="btn btn-secondary" id="preset-default-btn">Default</button>
<button type="button" class="btn btn-danger" id="preset-remove-from-zone-btn" hidden>Remove from zone</button>
<button class="btn btn-primary" id="preset-save-btn">Save &amp; Send</button>
<button class="btn btn-secondary" id="preset-editor-close-btn">Close</button>
</div>
</div>
</div>
<!-- Patterns Modal -->
<div id="patterns-modal" class="modal">
<div class="modal-content">
<h2>Patterns</h2>
<div class="modal-actions">
<button type="button" class="btn btn-primary" id="pattern-add-btn">Add</button>
<button type="button" class="btn btn-secondary" id="pattern-send-all-btn">Send All Patterns</button>
</div>
<div id="patterns-list" class="profiles-list"></div>
<div class="modal-actions">
<button class="btn btn-secondary" id="patterns-close-btn">Close</button>
</div>
</div>
</div>
<!-- Pattern Editor Modal -->
<div id="pattern-editor-modal" class="modal">
<div class="modal-content">
<h2>Pattern</h2>
<p class="muted-text" style="margin: 0 0 0.75rem 0;">Add a driver <code>.py</code> file and editor metadata (stored in the pattern database).</p>
<div class="profiles-row" style="flex-wrap: wrap; gap: 0.5rem; margin-bottom: 0.5rem;">
<label for="pattern-create-name" style="min-width: 7rem;">Name</label>
<input type="text" id="pattern-create-name" class="preset-name-like" placeholder="e.g. sparkle" pattern="[a-zA-Z_][a-zA-Z0-9_]*" style="flex: 1; min-width: 12rem;" autocomplete="off">
</div>
<div id="pattern-create-n-section" class="n-params-section" style="margin-bottom: 0.5rem;">
<h3 class="muted-text">Readable parameter names</h3>
<p id="pattern-create-n-empty" class="muted-text" style="display: none; margin: 0 0 0.5rem 0;">No parameter names are stored for this pattern.</p>
<div class="n-params-grid">
<div class="n-param-group">
<label for="pattern-create-n1"></label>
<input type="text" id="pattern-create-n1" class="n-input pattern-n-readable-input" placeholder="" autocomplete="off">
</div>
<div class="n-param-group">
<label for="pattern-create-n2"></label>
<input type="text" id="pattern-create-n2" class="n-input pattern-n-readable-input" placeholder="" autocomplete="off">
</div>
<div class="n-param-group">
<label for="pattern-create-n3"></label>
<input type="text" id="pattern-create-n3" class="n-input pattern-n-readable-input" placeholder="" autocomplete="off">
</div>
<div class="n-param-group">
<label for="pattern-create-n4"></label>
<input type="text" id="pattern-create-n4" class="n-input pattern-n-readable-input" placeholder="" autocomplete="off">
</div>
<div class="n-param-group">
<label for="pattern-create-n5"></label>
<input type="text" id="pattern-create-n5" class="n-input pattern-n-readable-input" placeholder="" autocomplete="off">
</div>
<div class="n-param-group">
<label for="pattern-create-n6"></label>
<input type="text" id="pattern-create-n6" class="n-input pattern-n-readable-input" placeholder="" autocomplete="off">
</div>
<div class="n-param-group">
<label for="pattern-create-n7"></label>
<input type="text" id="pattern-create-n7" class="n-input pattern-n-readable-input" placeholder="" autocomplete="off">
</div>
<div class="n-param-group">
<label for="pattern-create-n8"></label>
<input type="text" id="pattern-create-n8" class="n-input pattern-n-readable-input" placeholder="" autocomplete="off">
</div>
</div>
</div>
<div class="profiles-row pattern-editor-meta-row" style="flex-wrap: wrap; gap: 0.5rem; margin-bottom: 0.5rem;">
<label for="pattern-create-min-delay" style="min-width: 7rem;">Min delay (ms)</label>
<input type="number" id="pattern-create-min-delay" min="0" value="10">
<label for="pattern-create-max-delay">Max delay (ms)</label>
<input type="number" id="pattern-create-max-delay" min="0" value="10000">
<label for="pattern-create-max-colors">Max colours</label>
<input type="number" id="pattern-create-max-colors" min="0" value="10">
</div>
<div class="profiles-row" style="flex-direction: column; align-items: stretch; gap: 0.35rem; margin-bottom: 0.5rem;">
<label for="pattern-create-file">Pattern file</label>
<input type="file" id="pattern-create-file" accept=".py,text/x-python,.PY">
<label for="pattern-create-code" class="muted-text" style="font-size: 0.85em;">Or paste Python source (if no file chosen)</label>
<textarea id="pattern-create-code" rows="5" style="width: 100%; font-family: monospace; font-size: 0.85rem;" placeholder="# class MyPattern: ..."></textarea>
</div>
<div class="modal-actions">
<label style="display: inline-flex; align-items: center; gap: 0.35rem; margin-right: auto;">
<input type="checkbox" id="pattern-create-overwrite" checked>
<span>Overwrite existing file</span>
</label>
<button type="button" class="btn btn-primary" id="pattern-create-btn">Save</button>
<button type="button" class="btn btn-secondary" id="pattern-editor-close-btn">Close</button>
</div>
</div>
</div>
<!-- Colour Palette Modal -->
<div id="color-palette-modal" class="modal">
<div class="modal-content">
<h2>Colour Palette</h2>
<p class="muted-text">Profile: <span id="palette-current-profile-name">None</span></p>
<div id="palette-container" class="profiles-list"></div>
<div class="profiles-actions">
<input type="color" id="palette-new-color" value="#ffffff">
</div>
<div class="modal-actions">
<button class="btn btn-secondary" id="color-palette-close-btn">Close</button>
</div>
</div>
</div>
<!-- Help Modal -->
<div id="help-modal" class="modal">
<div class="modal-content">
<h2>Help</h2>
<p class="muted-text">How to use the LED controller UI.</p>
<h3>Run mode</h3>
<ul>
<li><strong>Select zone</strong>: left-click a zone button in the top bar.</li>
<li><strong>Select preset</strong>: left-click a preset tile to send a <code>select</code> message to all devices in the zone.</li>
<li><strong>Profiles</strong>: open <strong>Profiles</strong> to apply a profile. Profile editing actions are hidden in Run mode.</li>
<li><strong>Devices</strong>: open <strong>Devices</strong> to see drivers (Wi-Fi clients appear when they connect); edit or remove rows as needed.</li>
<li><strong>Send all presets</strong>: this action is available in <strong>Edit mode</strong> and pushes every preset used in the current zone to all zone devices.</li>
<li><strong>Switch modes</strong>: use the mode button in the menu. The button label shows the mode you will switch to.</li>
</ul>
<h3>Edit mode</h3>
<ul>
<li><strong>Tabs</strong>: create, edit, and manage tabs and device assignments.</li>
<li><strong>Presets</strong>: create/manage reusable presets and edit preset details.</li>
<li><strong>Preset tiles</strong>: each tile shows <strong>Edit</strong> and <strong>Remove</strong> controls in Edit mode.</li>
<li><strong>Reorder presets</strong>: drag and drop preset tiles to save zone order.</li>
<li><strong>Profiles</strong>: create/clone/delete profiles. New profiles get a populated <strong>default</strong> zone and can optionally seed a <strong>DJ zone</strong>.</li>
<li><strong>Devices</strong>: view, edit, or remove registry entries (tabs use <strong>names</strong>; each row is keyed by <strong>MAC</strong>).</li>
<li><strong>Colour Palette</strong>: build profile colours and use <strong>From Palette</strong> in preset editor to add linked colours (badge <strong>P</strong>) that update when palette colours change.</li>
</ul>
<h3>What led-tool does</h3>
<ul>
<li><strong>USB device setup</strong>: updates <code>settings.json</code> on ESP32 drivers over serial (for example name, pin, LED count, Wi-Fi credentials).</li>
<li><strong>Deploy and maintenance</strong>: uploads driver files, flashes firmware, resets device, and follows serial logs.</li>
<li><strong>Scope</strong>: led-tool configures devices directly; this web UI controls profiles/zones/presets and sends runtime messages.</li>
</ul>
<div class="modal-actions">
<button class="btn btn-secondary" id="help-close-btn">Close</button>
</div>
</div>
</div>
<!-- Settings Modal -->
<div id="settings-modal" class="modal">
<div class="modal-content">
<h2>Device Settings</h2>
<p class="muted-text">Configure WiFi Access Point and device settings.</p>
<div id="settings-message" class="message"></div>
<!-- Device Name -->
<div class="settings-section">
<h3>Device</h3>
<form id="device-form">
<div class="form-group">
<label for="device-name-input">Device Name</label>
<input type="text" id="device-name-input" name="device_name" placeholder="e.g. led-controller" required>
<small>This name may be used for mDNS (e.g. <code>name.local</code>) and UI display.</small>
</div>
<div class="form-group">
<label for="wifi-channel-input">WiFi channel (ESP-NOW)</label>
<input type="number" id="wifi-channel-input" name="wifi_channel" min="1" max="11" required>
<small>STA channel (1–11) for LED drivers and the serial bridge. Use the same value everywhere.</small>
</div>
<div class="btn-group">
<button type="submit" class="btn btn-primary btn-full">Save device settings</button>
</div>
</form>
</div>
<!-- Network -->
<div class="settings-section">
<h3>Network</h3>
<form id="network-form">
<div class="form-group">
<label for="hostname-input">Hostname (mDNS)</label>
<input type="text" id="hostname-input" placeholder="led-controller" pattern="[A-Za-z0-9\-]+" maxlength="63">
<small>The controller answers at <code>hostname.local</code>.</small>
</div>
<div class="form-group">
<label>Static IPs</label>
<small>Tried in order each time the Ethernet link comes up; the first whose gateway answers is used. If none does, or the list is empty, DHCP is used.</small>
<div id="static-ips-list"></div>
<button type="button" class="btn btn-secondary" id="static-ip-add-btn">Add network</button>
</div>
<div class="btn-group">
<button type="submit" class="btn btn-primary btn-full">Save network settings</button>
</div>
<small>Network changes apply after the controller restarts.</small>
</form>
</div>
<!-- WiFi Access Point Settings -->
<div class="settings-section ap-settings-section">
<h3>WiFi Access Point</h3>
<div id="ap-status" class="status-info">
<h4>AP Status</h4>
<p>Loading...</p>
</div>
<form id="ap-form">
<div class="form-group">
<label for="ap-ssid">AP SSID (Network Name)</label>
<input type="text" id="ap-ssid" name="ssid" placeholder="Enter AP name" required>
<small>The name of the WiFi access point this device creates</small>
</div>
<div class="form-group">
<label for="ap-password">AP Password</label>
<input type="password" id="ap-password" name="password" placeholder="Enter AP password (min 8 chars)" data-bwignore>
<small>Leave empty for open network (min 8 characters if set)</small>
</div>
<div class="form-group">
<label for="ap-channel">Channel (1-11)</label>
<input type="number" id="ap-channel" name="channel" min="1" max="11" placeholder="Auto">
<small>WiFi channel (1-11 for 2.4GHz). Leave empty for auto.</small>
</div>
<div class="btn-group">
<button type="submit" class="btn btn-primary btn-full">Configure AP</button>
</div>
</form>
</div>
<div class="modal-actions">
<button class="btn btn-secondary" id="settings-close-btn">Close</button>
</div>
</div>
</div>
<!-- LED Tool Modal -->
<div id="led-tool-modal" class="modal">
<div class="modal-content">
<h2>LED Tool (USB)</h2>
<p class="muted-text" style="margin-top: 0;">Configure a driver connected over USB using <code>led-tool</code>.</p>
<div id="led-tool-message" class="message" style="margin-bottom: 0.75rem;"></div>
<form id="led-tool-form">
<div class="form-group">
<label for="led-tool-port">Serial port</label>
<div class="profiles-actions" style="gap: 0.5rem;">
<select id="led-tool-port" required style="flex:1;">
<option value="">Select a serial port</option>
</select>
<button type="button" class="btn btn-secondary" id="led-tool-refresh-ports-btn">Refresh</button>
</div>
</div>
<div class="form-group">
<label for="led-tool-name">Name</label>
<input type="text" id="led-tool-name" placeholder="led-abcdef123456">
</div>
<div class="profiles-actions">
<div class="preset-editor-field">
<label for="led-tool-num-leds">Num LEDs</label>
<input type="number" id="led-tool-num-leds" min="1" max="5000" placeholder="60">
</div>
<div class="preset-editor-field">
<label for="led-tool-led-pin">LED pin</label>
<input type="number" id="led-tool-led-pin" min="0" max="48" placeholder="4">
</div>
</div>
<div class="profiles-actions">
<div class="preset-editor-field">
<label for="led-tool-brightness">Brightness</label>
<input type="number" id="led-tool-brightness" min="0" max="255" placeholder="255">
</div>
<div class="preset-editor-field">
<label for="led-tool-wifi-channel">WiFi channel</label>
<input type="number" id="led-tool-wifi-channel" min="1" max="11" placeholder="6">
</div>
</div>
<div class="profiles-actions">
<div class="preset-editor-field">
<label for="led-tool-transport">Transport</label>
<select id="led-tool-transport">
<option value="">(no change)</option>
<option value="espnow">espnow</option>
<option value="wifi">wifi</option>
</select>
</div>
<div class="preset-editor-field">
<label for="led-tool-default">Default preset</label>
<input type="text" id="led-tool-default" placeholder="on">
</div>
</div>
<div class="form-group">
<label for="led-tool-ssid">SSID</label>
<input type="text" id="led-tool-ssid" placeholder="Your WiFi SSID">
</div>
<div class="form-group">
<label for="led-tool-password">WiFi password</label>
<input type="password" id="led-tool-password" placeholder="WiFi password">
</div>
<div class="modal-actions">
<button type="button" class="btn btn-secondary" id="led-tool-read-btn">Read</button>
<button type="button" class="btn btn-secondary" id="led-tool-reset-btn">Reset</button>
<button type="submit" class="btn btn-primary">Apply via USB</button>
<button type="button" class="btn btn-secondary" id="led-tool-close-btn">Close</button>
</div>
</form>
<label for="led-tool-output" style="margin-top:0.5rem; display:block;">Command output</label>
<textarea id="led-tool-output" rows="12" readonly style="width:100%; font-family:monospace; resize:vertical;"></textarea>
</div>
</div>
<!-- Audio Modal -->
<div id="audio-modal" class="modal">
<div class="modal-content audio-modal-content">
<h2>Audio Beat Detection</h2>
<div class="form-group">
<label>Beat indicators</label>
<button type="button" id="audio-modal-beat-sync" class="audio-beat-sync-btn audio-modal-beat-sync" title="Tap on beat 1 of a bar to correct the bar position (or press T)">
<span class="audio-top-indicator-label">BPM</span>
<span id="audio-bpm-value" class="audio-top-indicator-value">--</span>
<span id="audio-modal-beat-readout" class="audio-top-beat-readout" aria-live="polite"></span>
<span id="audio-bar-phase-value" class="audio-top-bar-phase" aria-live="polite" title="Bar phase (beat in bar)"></span>
</button>
</div>
<div class="form-group audio-volume-block">
<div class="audio-volume-header">
<label>Microphone level</label>
<span id="audio-level-readout" class="audio-volume-readout" aria-live="polite">--</span>
</div>
<div class="audio-input-level-meter" role="meter" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" aria-label="Live input level">
<div id="audio-input-level-bar" class="audio-input-level-bar"></div>
</div>
</div>
<div class="form-group">
<label for="audio-simulated-bpm">Simulated BPM</label>
<input type="number" id="audio-simulated-bpm" min="60" max="200" step="1" value="120" style="width:6rem;" title="Beat rate sent to the drivers while the simulation runs; the microphone is ignored meanwhile">
<small id="audio-sim-status" class="muted-text"></small>
</div>
<div class="modal-actions">
<button type="button" class="btn btn-primary" id="audio-sim-start-btn">Start simulation</button>
<button type="button" class="btn btn-secondary" id="audio-sim-stop-btn">Stop simulation</button>
<button type="button" class="btn btn-secondary" id="audio-tap-btn" title="Press on beat 1 of a bar (or press T)">Tap beat 1</button>
<a class="btn btn-secondary" href="/audio" title="Live listening and the tap-along comparison">Full page</a>
<button type="button" class="btn btn-secondary" id="audio-close-btn">Close</button>
</div>
</div>
</div>
<!-- Styles moved to /static/style.css -->
<script src="/static/zones.js"></script>
<script src="/static/help.js"></script>
<script src="/static/audio.js"></script>
<script src="/static/led_tool.js"></script>
<script src="/static/color_palette.js"></script>
<script src="/static/profiles.js"></script>
<script src="/static/zone_palette.js"></script>
<script src="/static/patterns.js"></script>
<script src="/static/presets.js"></script>
<script src="/static/devices.js"></script>
<script src="/static/outputs.js"></script>
<script src="/static/sequences.js"></script>
<script src="/static/list_search.js"></script>
</body>
</html>
+365
View File
@@ -0,0 +1,365 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LED Controller - Settings</title>
<link rel="stylesheet" href="/static/style.css">
<style>
.settings-container {
padding: 2rem;
max-width: 1200px;
margin: 0 auto;
overflow-y: auto;
height: 100%;
}
.settings-header {
margin-bottom: 2rem;
}
.settings-header h1 {
font-size: 2rem;
margin-bottom: 0.5rem;
}
.settings-header p {
color: #aaa;
}
.settings-section {
background-color: #1a1a1a;
border-radius: 8px;
padding: 1.5rem;
margin-bottom: 1.5rem;
border: 1px solid #4a4a4a;
}
.settings-section h2 {
font-size: 1.3rem;
margin-bottom: 1rem;
color: #fff;
border-bottom: 2px solid #4a4a4a;
padding-bottom: 0.5rem;
}
.form-group {
margin-bottom: 1.5rem;
}
.form-group label {
display: block;
margin-bottom: 0.5rem;
color: #ccc;
font-weight: 500;
}
.form-group input[type="text"],
.form-group input[type="password"],
.form-group input[type="number"],
.form-group select {
width: 100%;
padding: 0.75rem;
background-color: #2e2e2e;
border: 1px solid #4a4a4a;
border-radius: 4px;
color: white;
font-size: 1rem;
}
.form-group input:focus,
.form-group select:focus {
outline: none;
border-color: #5a5a5a;
}
.form-group small {
display: block;
margin-top: 0.25rem;
color: #888;
font-size: 0.875rem;
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
.status-info {
background-color: #2e2e2e;
border: 1px solid #4a4a4a;
border-radius: 4px;
padding: 1rem;
margin-bottom: 1rem;
}
.status-info h3 {
font-size: 1rem;
margin-bottom: 0.5rem;
color: #fff;
}
.status-info p {
color: #aaa;
margin: 0.25rem 0;
font-size: 0.9rem;
}
.status-connected {
color: #4caf50;
}
.status-disconnected {
color: #f44336;
}
.btn-group {
display: flex;
gap: 0.5rem;
margin-top: 1rem;
}
.btn-full {
flex: 1;
}
.back-link {
display: inline-block;
margin-bottom: 1rem;
color: #aaa;
text-decoration: none;
padding: 0.5rem 1rem;
border-radius: 4px;
transition: background-color 0.2s;
}
.back-link:hover {
background-color: #2e2e2e;
color: white;
}
.message {
padding: 0.75rem;
border-radius: 4px;
margin-bottom: 1rem;
display: none;
}
.message.success {
background-color: #1b5e20;
color: #4caf50;
border: 1px solid #4caf50;
}
.message.error {
background-color: #5e1b1b;
color: #f44336;
border: 1px solid #f44336;
}
.message.show {
display: block;
}
</style>
</head>
<body>
<div class="app-container">
<div class="settings-container">
<a href="/" class="back-link">← Back to Dashboard</a>
<div class="settings-header">
<h1>Device Settings</h1>
<p>Configure WiFi Access Point and ESP-NOW options</p>
</div>
<div id="message" class="message"></div>
<!-- ESP-NOW (LED driver / bridge channel) -->
<div class="settings-section">
<h2>ESP-NOW</h2>
<form id="espnow-form">
<div class="form-group">
<label for="wifi-channel-page-input">WiFi channel (ESP-NOW)</label>
<input type="number" id="wifi-channel-page-input" name="wifi_channel" min="1" max="11" required>
<small>STA channel (1–11) for LED drivers and the serial bridge. Use the same value on every device.</small>
</div>
<div class="btn-group">
<button type="submit" class="btn btn-primary btn-full">Save channel</button>
</div>
</form>
</div>
<!-- WiFi Access Point Settings -->
<div class="settings-section">
<h2>WiFi Access Point Settings</h2>
<div id="ap-status" class="status-info">
<h3>AP Status</h3>
<p>Loading...</p>
</div>
<form id="ap-form">
<div class="form-group">
<label for="ap-ssid">AP SSID (Network Name)</label>
<input type="text" id="ap-ssid" name="ssid" placeholder="Enter AP name" required>
<small>The name of the WiFi access point this device creates</small>
</div>
<div class="form-group">
<label for="ap-password">AP Password</label>
<input type="password" id="ap-password" name="password" placeholder="Enter AP password (min 8 chars)" data-bwignore>
<small>Leave empty for open network (min 8 characters if set)</small>
</div>
<div class="form-group">
<label for="ap-channel">Channel (1-11)</label>
<input type="number" id="ap-channel" name="channel" min="1" max="11" placeholder="Auto">
<small>WiFi channel (1-11 for 2.4GHz). Leave empty for auto.</small>
</div>
<div class="btn-group">
<button type="submit" class="btn btn-primary btn-full">Configure AP</button>
</div>
</form>
</div>
</div>
</div>
<script>
// Show message helper
function showMessage(text, type = 'success') {
const messageEl = document.getElementById('message');
messageEl.textContent = text;
messageEl.className = `message ${type} show`;
setTimeout(() => {
messageEl.classList.remove('show');
}, 5000);
}
async function loadEspnowChannel() {
try {
const response = await fetch('/settings');
const data = await response.json();
const chInput = document.getElementById('wifi-channel-page-input');
if (chInput && data && typeof data === 'object') {
const ch = data.wifi_channel;
chInput.value =
ch !== undefined && ch !== null && ch !== '' ? String(ch) : '6';
}
} catch (error) {
console.error('Error loading ESP-NOW channel:', error);
}
}
document.getElementById('espnow-form').addEventListener('submit', async (e) => {
e.preventDefault();
const chRaw = document.getElementById('wifi-channel-page-input').value;
const wifiChannel = parseInt(chRaw, 10);
if (Number.isNaN(wifiChannel) || wifiChannel < 1 || wifiChannel > 11) {
showMessage('WiFi channel must be between 1 and 11', 'error');
return;
}
try {
const response = await fetch('/settings/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ wifi_channel: wifiChannel }),
});
const result = await response.json();
if (response.ok) {
showMessage('ESP-NOW channel saved.', 'success');
} else {
showMessage(`Error: ${result.error || 'Failed to save'}`, 'error');
}
} catch (error) {
showMessage(`Error: ${error.message}`, 'error');
}
});
// Load AP status and config
async function loadAPStatus() {
try {
const response = await fetch('/settings/wifi/ap');
const config = await response.json();
const statusEl = document.getElementById('ap-status');
if (config.active) {
statusEl.innerHTML = `
<h3>AP Status: <span class="status-connected">Active</span></h3>
<p><strong>SSID:</strong> ${config.ssid || 'N/A'}</p>
<p><strong>Channel:</strong> ${config.channel || 'Auto'}</p>
<p><strong>IP Address:</strong> ${config.ip || 'N/A'}</p>
`;
} else {
statusEl.innerHTML = `
<h3>AP Status: <span class="status-disconnected">Inactive</span></h3>
<p>Access Point is not currently active</p>
`;
}
// Load saved values
if (config.saved_ssid) document.getElementById('ap-ssid').value = config.saved_ssid;
if (config.saved_channel) document.getElementById('ap-channel').value = config.saved_channel;
} catch (error) {
console.error('Error loading AP status:', error);
}
}
// AP form submission
document.getElementById('ap-form').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = {
ssid: document.getElementById('ap-ssid').value,
password: document.getElementById('ap-password').value,
channel: document.getElementById('ap-channel').value || null
};
// Validate password length if provided
if (formData.password && formData.password.length > 0 && formData.password.length < 8) {
showMessage('AP password must be at least 8 characters', 'error');
return;
}
// Convert channel to number if provided
if (formData.channel) {
formData.channel = parseInt(formData.channel);
if (formData.channel < 1 || formData.channel > 11) {
showMessage('Channel must be between 1 and 11', 'error');
return;
}
}
try {
const response = await fetch('/settings/wifi/ap', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
});
const result = await response.json();
if (response.ok) {
showMessage('Access Point configured successfully!', 'success');
setTimeout(loadAPStatus, 1000);
} else {
showMessage(`Error: ${result.error || 'Failed to configure AP'}`, 'error');
}
} catch (error) {
showMessage(`Error: ${error.message}`, 'error');
}
});
// Load all data on page load
loadEspnowChannel();
loadAPStatus();
// Refresh status every 10 seconds
setInterval(loadAPStatus, 10000);
</script>
</body>
</html>