diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index 81b967f..2fd63c8 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -1,5 +1,5 @@ idf_component_register(SRCS "main.c" "mic.c" "beat.c" "beat_dsp.c" "espnow_tx.c" "store.c" "api.c" "web.c" "envelope.c" "engine.c" "rel.c" "bench.c" "audio.c" "ota.c" "drv_ota.c" - "res_profile.c" "res_misc.c" "res_device.c" "res_group.c" "seqplay.c" "patterns.c" "outputs.c" "ws.c" + "res_profile.c" "res_misc.c" "res_device.c" "res_group.c" "seqplay.c" "res_bundle.c" "audio_api.c" "patterns.c" "outputs.c" "ws.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 diff --git a/main/api.c b/main/api.c index b0afa9a..e6ac129 100644 --- a/main/api.c +++ b/main/api.c @@ -205,6 +205,9 @@ void api_add(const char *coll, cJSON *rec, char *id, size_t len) static bool route(const char *res, httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) { + if (bundles_route(req, n, seg, ret)) { // //import and //export + return true; + } static const struct { const char *res; bool (*fn)(httpd_req_t *, int, api_seg_t, esp_err_t *); @@ -508,6 +511,8 @@ esp_err_t api_register(httpd_handle_t server) store_lock(); api_settings_defaults(); api_migrate_sequences(); + api_migrate_zones(); + api_migrate_groups(); store_unlock(); static const char *const ROUTES[] = { "/devices*", "/zones*", "/presets*", "/profiles*", "/palettes*", diff --git a/main/api_util.h b/main/api_util.h index 26678ac..a5192bc 100644 --- a/main/api_util.h +++ b/main/api_util.h @@ -44,15 +44,22 @@ int api_effective_brightness(const char *mac, int zone_b); // Blink every member of a group, then "off" esp_err_t api_identify_group(const char *group_id); +// New records with every field set (callers merge in the request) +cJSON *api_preset_defaults(const char *profile_id); +cJSON *api_sequence_defaults(void); + // Current profile id (settings.current_profile_id, else the first profile), or NULL const char *api_current_profile(void); bool api_preset_in_profile(const cJSON *rec); // Bring records written by older versions into the current shape (at boot) void api_migrate_sequences(void); +void api_migrate_zones(void); +void api_migrate_groups(void); // Resource handlers, called with the store locked. Each returns true when it answered the request // (its result in *ret); false hands the request to the generic collection CRUD. +bool bundles_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); bool profiles_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); bool zones_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); bool presets_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret); diff --git a/main/audio_api.c b/main/audio_api.c new file mode 100644 index 0000000..9b69f52 --- /dev/null +++ b/main/audio_api.c @@ -0,0 +1,303 @@ +// main's /api/audio routes on this board's microphone: status and an event stream in main's shape, +// start/stop (whether mic beats time sequences), tracking reset and bar anchoring. There is one input, +// the I2S microphone, so device selection is stored but changes nothing. + +#include "audio_api.h" + +#include +#include +#include +#include +#include +#include "api_util.h" +#include "beat.h" +#include "cJSON.h" +#include "esp_log.h" +#include "esp_timer.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "lwip/sockets.h" +#include "mic.h" +#include "seqplay.h" +#include "store.h" + +static const char *TAG = "audio_api"; + +#define EVENTS_HEARTBEAT_US 500000 + +static int setting_int(const char *key, int dflt, int lo, int hi) +{ + const cJSON *v = cJSON_GetObjectItem(store_settings(), key); + int x = cJSON_IsNumber(v) ? (int)v->valuedouble : dflt; + return x < lo ? lo : (x > hi ? hi : x); +} + +static cJSON *audio_run(void) +{ + cJSON *o = cJSON_CreateObject(); + cJSON_AddBoolToObject(o, "enabled", seqplay_audio()); + const cJSON *sel = cJSON_GetObjectItem(store_settings(), "audio_device_select"); + cJSON_AddNullToObject(o, "device"); + cJSON_AddStringToObject(o, "device_override", ""); + cJSON_AddStringToObject(o, "device_select", cJSON_IsString(sel) ? sel->valuestring : ""); + return o; +} + +// main's audio_status_payload +static cJSON *status_payload(void) +{ + beat_info_t bi; + beat_get_info(&bi); + mic_level_t lv; + mic_get_level(&lv); + bool running = seqplay_audio(); + int meter = bi.meter > 0 ? bi.meter : 4; + + cJSON *o = cJSON_CreateObject(); + store_lock(); + int sim_bpm = setting_int("audio_simulated_bpm", 120, 60, 200); + cJSON_AddBoolToObject(o, "running", running); + cJSON_AddStringToObject(o, "device", "i2s"); + cJSON_AddNullToObject(o, "error"); + if (!running) { + cJSON_AddNumberToObject(o, "bpm", sim_bpm); + } else if (bi.locked && bi.bpm > 0) { + cJSON_AddNumberToObject(o, "bpm", bi.bpm < 60 ? 60 : (bi.bpm > 200 ? 200 : bi.bpm)); + } else { + cJSON_AddNullToObject(o, "bpm"); + } + cJSON_AddNumberToObject(o, "beat_seq", bi.beat_count); + cJSON_AddNumberToObject(o, "beats_per_bar", meter); + cJSON_AddStringToObject(o, "beat_type", "unknown"); + cJSON_AddNumberToObject(o, "beat_type_confidence", 0); + cJSON_AddNumberToObject(o, "input_level", running ? powf(10.0f, lv.rms_dbfs / 20.0f) : 0); + cJSON_AddItemToObject(o, "last_beat_ts", bi.last_beat_us ? cJSON_CreateNumber(bi.last_beat_us / 1e6) : cJSON_CreateNull()); + int bar_beat; + double phase_conf; + if (running) { + bar_beat = bi.bar_beat > 0 ? bi.bar_beat : 1; + phase_conf = bi.bar_sure ? 1.0 : 0.0; + } else { + uint32_t tick; + seqplay_clock(&bar_beat, &tick); + phase_conf = 0; + } + char readout[24]; + snprintf(readout, sizeof(readout), "%d/%d", bar_beat, running ? meter : 4); + cJSON_AddNumberToObject(o, "bar_beat", bar_beat); + cJSON_AddBoolToObject(o, "is_downbeat", bar_beat == 1); + cJSON_AddStringToObject(o, "bar_phase_readout", readout); + cJSON_AddNumberToObject(o, "phase_confidence", phase_conf); + + cJSON *seq = seqplay_status(); + const cJSON *ro = cJSON_GetObjectItem(seq, "beat_readout"); + if (cJSON_IsString(ro) && ro->valuestring[0]) { + snprintf(readout, sizeof(readout), "%s", ro->valuestring); + } else if (seqplay_done_readout()[0]) { + snprintf(readout, sizeof(readout), "%s", seqplay_done_readout()); + } else if (running && bi.beat_count > 0) { + snprintf(readout, sizeof(readout), "%lu", (unsigned long)bi.beat_count); + } else { + readout[0] = 0; + } + cJSON_AddItemToObject(o, "sequence", seq); + cJSON *stride = cJSON_AddObjectToObject(o, "manual_beat_stride"); + cJSON_AddFalseToObject(stride, "active"); // drivers step manual presets on the beats themselves + cJSON_AddStringToObject(o, "beat_readout", readout); + cJSON_AddNumberToObject(o, "beat_phase_ms", setting_int("audio_beat_phase_ms", 0, 0, 500)); + cJSON_AddNumberToObject(o, "input_volume", setting_int("audio_input_volume", 100, 0, 200)); + const cJSON *sw = cJSON_GetObjectItem(store_settings(), "sequence_switch_wait"); + cJSON_AddStringToObject(o, "sequence_switch_wait_saved", + cJSON_IsString(sw) && !strcasecmp(sw->valuestring, "downbeat") ? "downbeat" : "beat"); + cJSON_AddStringToObject(o, "sequence_switch_wait", seqplay_switch_wait()); + cJSON_AddItemToObject(o, "audio_run", audio_run()); + cJSON_AddNumberToObject(o, "audio_simulated_bpm", sim_bpm); + cJSON_AddItemToObject(o, "sequence_pending", seqplay_pending()); + cJSON_AddBoolToObject(o, "bpm_simulated", !(running && bi.locked)); + int sim_bar; + uint32_t tick; + seqplay_clock(&sim_bar, &tick); + cJSON_AddNumberToObject(o, "simulated_beat_tick", tick); + store_unlock(); + return o; +} + +static esp_err_t send_json(httpd_req_t *req, const char *status, cJSON *o) +{ + char *s = cJSON_PrintUnformatted(o); + cJSON_Delete(o); + if (!s) { + return httpd_resp_send_500(req); + } + httpd_resp_set_status(req, status); + httpd_resp_set_type(req, "application/json"); + esp_err_t r = httpd_resp_sendstr(req, s); + free(s); + return r; +} + +static esp_err_t ok_with_status(httpd_req_t *req) +{ + cJSON *o = cJSON_CreateObject(); + cJSON_AddTrueToObject(o, "ok"); + cJSON_AddItemToObject(o, "status", status_payload()); + return send_json(req, "200 OK", o); +} + +/* ------------------------------------------------------------ event stream */ + +static bool send_all(int fd, const char *p, size_t len) +{ + while (len > 0) { + int sent = send(fd, p, len, 0); + if (sent <= 0) { + return false; + } + p += sent; + len -= sent; + } + return true; +} + +static bool send_event(int fd, const char *type) +{ + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "type", type); + cJSON_AddItemToObject(o, "status", status_payload()); + char *s = cJSON_PrintUnformatted(o); + cJSON_Delete(o); + bool ok = s && send_all(fd, "data: ", 6) && send_all(fd, s, strlen(s)) && send_all(fd, "\n\n", 2); + free(s); + return ok; +} + +static void events_task(void *arg) +{ + httpd_req_t *req = arg; + httpd_handle_t server = req->handle; + int fd = httpd_req_to_sockfd(req); + QueueHandle_t q = xQueueCreate(8, sizeof(beat_event_t)); + static const char hdr[] = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\n" + "Connection: close\r\n\r\n"; + bool ok = q && beat_subscribe(q) == ESP_OK; + if (!ok) { + static const char busy[] = "HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\nToo many listeners\n"; + send_all(fd, busy, sizeof(busy) - 1); + } else { + ok = send_all(fd, hdr, sizeof(hdr) - 1) && send_event(fd, "status"); + } + int64_t next = esp_timer_get_time() + EVENTS_HEARTBEAT_US; + while (ok) { + int64_t now = esp_timer_get_time(); + beat_event_t ev; + if (now >= next) { + ok = send_event(fd, "status"); + next = now + EVENTS_HEARTBEAT_US; + } else if (xQueueReceive(q, &ev, pdMS_TO_TICKS((next - now) / 1000) + 1) == pdTRUE && ev == BEAT_EVENT_BEAT) { + vTaskDelay(pdMS_TO_TICKS(20)); // let the sequencer count this beat first + ok = send_event(fd, "beat"); + } + } + if (q) { + beat_unsubscribe(q); + vQueueDelete(q); + } + httpd_req_async_handler_complete(req); + httpd_sess_trigger_close(server, fd); + vTaskDelete(NULL); +} + +static esp_err_t events(httpd_req_t *req) +{ + httpd_req_t *async_req = NULL; + if (httpd_req_async_handler_begin(req, &async_req) != ESP_OK) { + return ESP_FAIL; + } + if (xTaskCreate(events_task, "audio_events", 6144, async_req, 5, NULL) != pdPASS) { + httpd_req_async_handler_complete(async_req); + return ESP_FAIL; + } + return ESP_OK; +} + +/* --------------------------------------------------------------- handlers */ + +static esp_err_t audio_handler(httpd_req_t *req) +{ + const char *action = req->uri + strlen("/api/audio/"); + size_t alen = strcspn(action, "?"); + char act[16] = ""; + if (alen < sizeof(act)) { + memcpy(act, action, alen); + } + if (req->method == HTTP_GET && !strcmp(act, "status")) { + cJSON *o = cJSON_CreateObject(); + cJSON_AddItemToObject(o, "status", status_payload()); + return send_json(req, "200 OK", o); + } + if (req->method == HTTP_GET && !strcmp(act, "events")) { + return events(req); + } + if (req->method == HTTP_GET && !strcmp(act, "devices")) { + cJSON *o = cJSON_CreateObject(), *devs = cJSON_AddArrayToObject(o, "devices"), *d = cJSON_CreateObject(); + cJSON_AddStringToObject(d, "id", "i2s"); + cJSON_AddStringToObject(d, "name", "I2S microphone"); + cJSON_AddStringToObject(d, "display_name", "I2S microphone"); + cJSON_AddTrueToObject(d, "is_default"); + cJSON_AddItemToArray(devs, d); + cJSON_AddObjectToObject(o, "diagnostics"); + return send_json(req, "200 OK", o); + } + if (req->method == HTTP_PUT && !strcmp(act, "device")) { + cJSON *body = api_body_opt(req); + if (!body) { + return ESP_OK; + } + const cJSON *sel = cJSON_GetObjectItem(body, "device_select"); + store_lock(); + api_set(store_settings(), "audio_device_select", cJSON_CreateString(cJSON_IsString(sel) ? sel->valuestring : "")); + store_save("settings"); + cJSON *o = cJSON_CreateObject(); + cJSON_AddTrueToObject(o, "ok"); + cJSON_AddItemToObject(o, "audio_run", audio_run()); + store_unlock(); + cJSON_Delete(body); + return send_json(req, "200 OK", o); + } + if (req->method != HTTP_POST) { + return httpd_resp_send_404(req); + } + if (!strcmp(act, "start") || !strcmp(act, "stop")) { + seqplay_set_audio(act[2] == 'a'); // st[a]rt + ESP_LOGI(TAG, "mic beats %s sequences", act[2] == 'a' ? "time" : "no longer time"); + return ok_with_status(req); + } + if (!strcmp(act, "reset") || !strcmp(act, "anchor-bar")) { + if (!seqplay_audio()) { + cJSON *o = cJSON_CreateObject(); + cJSON_AddFalseToObject(o, "ok"); + cJSON_AddStringToObject(o, "error", "Audio detector is not running"); + return send_json(req, "409 Conflict", o); + } + if (act[0] == 'r') { + beat_reset(); + } else { + beat_tap(); + } + return ok_with_status(req); + } + return httpd_resp_send_404(req); +} + +esp_err_t audio_api_register(httpd_handle_t server) +{ + static const httpd_method_t METHODS[] = { HTTP_GET, HTTP_POST, HTTP_PUT }; + for (size_t m = 0; m < 3; m++) { + httpd_uri_t u = { .uri = "/api/audio/*", .method = METHODS[m], .handler = audio_handler }; + esp_err_t err = httpd_register_uri_handler(server, &u); + if (err != ESP_OK) { + return err; + } + } + return ESP_OK; +} diff --git a/main/audio_api.h b/main/audio_api.h new file mode 100644 index 0000000..b05ba8f --- /dev/null +++ b/main/audio_api.h @@ -0,0 +1,7 @@ +#pragma once + +#include "esp_err.h" +#include "esp_http_server.h" + +// /api/audio/{status,events,devices,device,start,stop,reset,anchor-bar}: main's audio API (see audio_api.c) +esp_err_t audio_api_register(httpd_handle_t server); diff --git a/main/beat.c b/main/beat.c index 1755781..9fc5b6e 100644 --- a/main/beat.c +++ b/main/beat.c @@ -105,9 +105,13 @@ static void dsp_event(void *ctx, int events, const beat_dsp_t *d) } } +static float s_rate; +static bool s_reset; + esp_err_t beat_start(float sample_rate) { float gate_rms = powf(10.0f, CONFIG_BEAT_GATE_DBFS / 20.0f); + s_rate = sample_rate; beat_dsp_init(&s_dsp, sample_rate, gate_rms, CONFIG_BEAT_LEAD_MS / 1000.0f); s_info.meter = s_dsp.meter; s_subs_mutex = xSemaphoreCreateMutex(); @@ -128,6 +132,13 @@ esp_err_t beat_start(float sample_rate) return ESP_OK; } +void beat_reset(void) +{ + portENTER_CRITICAL(&s_lock); + s_reset = true; + portEXIT_CRITICAL(&s_lock); +} + void beat_tap(void) { portENTER_CRITICAL(&s_lock); @@ -137,6 +148,19 @@ void beat_tap(void) void beat_feed(const float *x, size_t n) { + portENTER_CRITICAL(&s_lock); + bool reset = s_reset; + s_reset = false; + portEXIT_CRITICAL(&s_lock); + if (reset) { // start tempo and bar tracking over, in the detector's task + beat_dsp_init(&s_dsp, s_rate, powf(10.0f, CONFIG_BEAT_GATE_DBFS / 20.0f), CONFIG_BEAT_LEAD_MS / 1000.0f); + portENTER_CRITICAL(&s_lock); + s_info.bar_beat = 0; + s_info.bar_sure = false; + s_info.meter = s_dsp.meter; + portEXIT_CRITICAL(&s_lock); + ESP_LOGI(TAG, "Tracking reset"); + } beat_dsp_feed(&s_dsp, x, n, dsp_event, NULL); // Taps arrive from the HTTP task; apply them here, in the detector's task diff --git a/main/beat.h b/main/beat.h index 101118d..3e8b815 100644 --- a/main/beat.h +++ b/main/beat.h @@ -37,6 +37,8 @@ void beat_get_info(beat_info_t *out); // The user tapped beat 1 just now: correct the bar position to match void beat_tap(void); +// Forget the tempo and bar position and start tracking again +void beat_reset(void); // Have beat_event_t values posted (without blocking) to a queue of // beat_event_t. Returns ESP_ERR_NO_MEM when all subscriber slots are taken. diff --git a/main/espnow_tx.c b/main/espnow_tx.c index 21ee00e..c91911a 100644 --- a/main/espnow_tx.c +++ b/main/espnow_tx.c @@ -113,9 +113,19 @@ void espnow_tx_beat(float bpm, bool downbeat, int bar) send_beat_copy(NULL); } +static volatile bool s_mic_beats = true; + +void espnow_tx_set_mic_beats(bool on) +{ + s_mic_beats = on; +} + // Runs in the audio task straight from the detector: no queue, no allocation. static void on_beat(const beat_info_t *info, float bpm, bool downbeat) { + if (!s_mic_beats) { + return; + } if (bench_running()) { return; // the bench generator owns the beat stream while it runs } diff --git a/main/espnow_tx.h b/main/espnow_tx.h index bad27ef..4084712 100644 --- a/main/espnow_tx.h +++ b/main/espnow_tx.h @@ -41,6 +41,8 @@ void espnow_tx_stats(espnow_stats_t *out); // Send one beat now (also used by the bench generator). bar 0 = unknown. void espnow_tx_beat(float bpm, bool downbeat, int bar); +// Whether the mic's detected beats go to the drivers (off while audio timing is switched off) +void espnow_tx_set_mic_beats(bool on); // Lossy-link test mode: discard this percentage of outgoing frames and of // received acks/echoes. include_beats = false leaves beat copies alone. diff --git a/main/main.c b/main/main.c index c682277..aa4978c 100644 --- a/main/main.c +++ b/main/main.c @@ -33,6 +33,7 @@ #include "api.h" #include "engine.h" #include "seqplay.h" +#include "audio_api.h" #include "rel.h" #include "web.h" #include "audio.h" @@ -209,7 +210,7 @@ static void start_webserver(void) } httpd_config_t config = HTTPD_DEFAULT_CONFIG(); config.uri_match_fn = httpd_uri_match_wildcard; - config.max_uri_handlers = 72; + config.max_uri_handlers = 80; config.stack_size = 8192; config.lru_purge_enable = true; if (httpd_start(&s_server, &config) != ESP_OK) { @@ -220,6 +221,7 @@ static void start_webserver(void) httpd_register_uri_handler(s_server, &status_uri); web_register(s_server); audio_register(s_server); + audio_api_register(s_server); ota_register(s_server); drv_ota_register(s_server); api_register(s_server); diff --git a/main/res_bundle.c b/main/res_bundle.c new file mode 100644 index 0000000..bbb4366 --- /dev/null +++ b/main/res_bundle.c @@ -0,0 +1,492 @@ +// Import/export bundles: main's util/profile_bundle.py. A profile bundle carries the profile, its +// palette colours, zones, the presets they use and their sequences; preset and sequence bundles carry +// one record (a sequence with its presets). Imports get new ids and belong to the importing profile. + +#include +#include +#include +#include "api_util.h" +#include "engine.h" +#include "store.h" + +#define BUNDLE_VERSION 1 + +static void add_ref(cJSON *set, const cJSON *v) +{ + if (cJSON_IsArray(v)) { + const cJSON *it; + cJSON_ArrayForEach(it, v) + { + add_ref(set, it); + } + return; + } + char id[24]; + if (api_id(v, id, sizeof(id)) && !cJSON_GetObjectItem(set, id)) { + cJSON_AddTrueToObject(set, id); + } +} + +static void zone_preset_ids(const cJSON *zone, cJSON *set) +{ + add_ref(set, cJSON_GetObjectItem(zone, "presets")); + add_ref(set, cJSON_GetObjectItem(zone, "presets_flat")); + add_ref(set, cJSON_GetObjectItem(zone, "default_preset")); +} + +static void sequence_preset_ids(const cJSON *seq, cJSON *set) +{ + const cJSON *lane, *step; + cJSON_ArrayForEach(lane, cJSON_GetObjectItem(seq, "lanes")) + { + cJSON_ArrayForEach(step, lane) + { + add_ref(set, cJSON_GetObjectItem(step, "preset_id")); + } + } + cJSON_ArrayForEach(step, cJSON_GetObjectItem(seq, "steps")) + { + add_ref(set, cJSON_GetObjectItem(step, "preset_id")); + } +} + +static bool owned_by(const cJSON *rec, const char *profile) +{ + char pid[24]; + return api_id(cJSON_GetObjectItem(rec, "profile_id"), pid, sizeof(pid)) && !strcmp(pid, profile); +} + +static cJSON *bundle(const char *kind) +{ + cJSON *b = cJSON_CreateObject(); + cJSON_AddNumberToObject(b, "version", BUNDLE_VERSION); + cJSON_AddStringToObject(b, "kind", kind); + return b; +} + +static cJSON *palette_colors(const cJSON *profile) +{ + char id[24]; + const cJSON *pal = api_id(cJSON_GetObjectItem(profile, "palette_id"), id, sizeof(id)) + ? cJSON_GetObjectItem(store_coll("palette"), id) + : NULL; + if (cJSON_IsObject(pal)) { + pal = cJSON_GetObjectItem(pal, "colors"); + } + return cJSON_IsArray(pal) ? cJSON_Duplicate(pal, true) : cJSON_CreateArray(); +} + +static cJSON *export_profile(const char *id) +{ + const cJSON *src = cJSON_GetObjectItem(store_coll("profile"), id); + if (!src) { + return NULL; + } + cJSON *b = bundle("profile"); + cJSON *prof = cJSON_Duplicate(src, true); + cJSON_DeleteItemFromObject(prof, "palette"); + cJSON_AddItemToObject(b, "profile", prof); + cJSON *pal = cJSON_AddObjectToObject(b, "palette"); + cJSON_AddItemToObject(pal, "colors", palette_colors(src)); + cJSON *zones = cJSON_AddObjectToObject(b, "zones"); + cJSON *presets = cJSON_AddObjectToObject(b, "presets"); + cJSON *seqs = cJSON_AddObjectToObject(b, "sequences"); + cJSON *pset = cJSON_CreateObject(), *sset = cJSON_CreateObject(); + const cJSON *zl = cJSON_GetObjectItem(src, "zones"); + if (!cJSON_GetArraySize(zl)) { + zl = cJSON_GetObjectItem(src, "zone_order"); + } + const cJSON *zid; + cJSON_ArrayForEach(zid, zl) + { + char key[24]; + const cJSON *z = api_id(zid, key, sizeof(key)) ? cJSON_GetObjectItem(store_coll("zone"), key) : NULL; + if (!z || cJSON_GetObjectItem(zones, key)) { + continue; + } + cJSON_AddItemToObject(zones, key, cJSON_Duplicate(z, true)); + zone_preset_ids(z, pset); + add_ref(sset, cJSON_GetObjectItem(z, "sequence_ids")); + } + const cJSON *it; + cJSON_ArrayForEach(it, sset) + { + const cJSON *s = cJSON_GetObjectItem(store_coll("sequence"), it->string); + if (s && owned_by(s, id)) { + cJSON_AddItemToObject(seqs, it->string, cJSON_Duplicate(s, true)); + sequence_preset_ids(s, pset); + } + } + cJSON_ArrayForEach(it, pset) + { + const cJSON *p = cJSON_GetObjectItem(store_coll("preset"), it->string); + if (p && owned_by(p, id)) { + cJSON_AddItemToObject(presets, it->string, cJSON_Duplicate(p, true)); + } + } + cJSON_Delete(pset); + cJSON_Delete(sset); + return b; +} + +// Copy of v with every preset id mapped (nested lists allowed); unknown ids are copied from the store +// into the new profile, or become null when there is no such preset +static cJSON *map_presets(const cJSON *v, cJSON *map, const char *profile) +{ + if (cJSON_IsArray(v)) { + cJSON *out = cJSON_CreateArray(); + const cJSON *it; + cJSON_ArrayForEach(it, v) + { + cJSON_AddItemToArray(out, map_presets(it, map, profile)); + } + return out; + } + char id[24]; + if (!api_id(v, id, sizeof(id))) { + return cJSON_CreateNull(); + } + const cJSON *to = cJSON_GetObjectItem(map, id); + if (to) { + return cJSON_Duplicate(to, false); + } + const cJSON *p = cJSON_GetObjectItem(store_coll("preset"), id); + if (!p) { + return cJSON_CreateNull(); + } + cJSON *copy = cJSON_Duplicate(p, true); + api_set(copy, "profile_id", cJSON_CreateString(profile)); + char nid[16]; + api_add("preset", copy, nid, sizeof(nid)); + cJSON_AddStringToObject(map, id, nid); + return cJSON_CreateString(nid); +} + +static void map_steps(cJSON *steps, const cJSON *map) +{ + cJSON *step; + cJSON_ArrayForEach(step, steps) + { + char id[24]; + const cJSON *to = api_id(cJSON_GetObjectItem(step, "preset_id"), id, sizeof(id)) ? cJSON_GetObjectItem(map, id) : NULL; + if (to) { + api_set(step, "preset_id", cJSON_Duplicate(to, false)); + } + } +} + +// Sequence copy with step preset ids mapped where the map knows them +static cJSON *map_sequence(const cJSON *seq, const cJSON *map) +{ + cJSON *out = cJSON_Duplicate(seq, true), *lane; + cJSON_ArrayForEach(lane, cJSON_GetObjectItem(out, "lanes")) + { + map_steps(lane, map); + } + map_steps(cJSON_GetObjectItem(out, "steps"), map); + return out; +} + +// Presets from a bundle into profile; returns old id -> new id +static cJSON *import_presets(const cJSON *presets, const char *profile) +{ + cJSON *map = cJSON_CreateObject(); + const cJSON *p; + cJSON_ArrayForEach(p, presets) + { + if (!cJSON_IsObject(p)) { + continue; + } + cJSON *copy = cJSON_Duplicate(p, true); + api_set(copy, "profile_id", cJSON_CreateString(profile)); + char nid[16]; + api_add("preset", copy, nid, sizeof(nid)); + cJSON_AddStringToObject(map, p->string, nid); + } + return map; +} + +static const char *import_profile(const cJSON *b, const char *name, char *pid, size_t len, cJSON **out) +{ + const cJSON *ver = cJSON_GetObjectItem(b, "version"), *kind = cJSON_GetObjectItem(b, "kind"); + if (!((cJSON_IsNumber(ver) && ver->valuedouble == BUNDLE_VERSION) || + (cJSON_IsString(ver) && !strcmp(ver->valuestring, "1")))) { + return "Unsupported bundle version"; + } + if (kind && !cJSON_IsNull(kind) && !(cJSON_IsString(kind) && !strcmp(kind->valuestring, "profile"))) { + return "Not a profile bundle"; + } + const cJSON *src = cJSON_GetObjectItem(b, "profile"); + if (!cJSON_IsObject(src)) { + return "Bundle missing profile"; + } + const cJSON *sname = cJSON_GetObjectItem(src, "name"); + const char *new_name = name && name[0] ? name + : cJSON_IsString(sname) && sname->valuestring[0] ? sname->valuestring + : "Imported profile"; + const cJSON *type = cJSON_GetObjectItem(src, "type"); + + cJSON *prof = cJSON_CreateObject(); + cJSON_AddStringToObject(prof, "name", new_name); + cJSON_AddStringToObject(prof, "type", cJSON_IsString(type) ? type->valuestring : "zones"); + api_add("profile", prof, pid, len); + + char palid[16]; + const cJSON *pal = cJSON_GetObjectItem(cJSON_GetObjectItem(b, "palette"), "colors"); + api_add("palette", cJSON_IsArray(pal) ? cJSON_Duplicate(pal, true) : cJSON_CreateArray(), palid, sizeof(palid)); + + cJSON *pmap = import_presets(cJSON_GetObjectItem(b, "presets"), pid); + cJSON *smap = cJSON_CreateObject(); + const cJSON *s; + cJSON_ArrayForEach(s, cJSON_GetObjectItem(b, "sequences")) + { + if (!cJSON_IsObject(s)) { + continue; + } + cJSON *copy = map_sequence(s, pmap); + api_set(copy, "profile_id", cJSON_CreateString(pid)); + char nid[16]; + api_add("sequence", copy, nid, sizeof(nid)); + cJSON_AddStringToObject(smap, s->string, nid); + } + + const cJSON *zones_in = cJSON_GetObjectItem(b, "zones"); + const cJSON *order = cJSON_GetObjectItem(src, "zones"); + cJSON *keys = NULL; + if (!cJSON_IsArray(order)) { + keys = cJSON_CreateArray(); + const cJSON *z; + cJSON_ArrayForEach(z, zones_in) + { + cJSON_AddItemToArray(keys, cJSON_CreateString(z->string)); + } + order = keys; + } + cJSON *zone_ids = cJSON_CreateArray(); + const cJSON *oz; + cJSON_ArrayForEach(oz, order) + { + char key[24]; + const cJSON *z = api_id(oz, key, sizeof(key)) ? cJSON_GetObjectItem(zones_in, key) : NULL; + if (!cJSON_IsObject(z)) { + continue; + } + cJSON *copy = cJSON_Duplicate(z, true); + const cJSON *zn = cJSON_GetObjectItem(z, "name"); + if (!cJSON_IsString(zn) || !zn->valuestring[0]) { + char nm[40]; + snprintf(nm, sizeof(nm), "Zone %s", key); + api_set(copy, "name", cJSON_CreateString(nm)); + } + if (!cJSON_IsArray(cJSON_GetObjectItem(copy, "names"))) { + api_set(copy, "names", cJSON_CreateArray()); + } + static const char *const REFS[] = { "presets", "presets_flat" }; + for (int i = 0; i < 2; i++) { + const cJSON *v = cJSON_GetObjectItem(z, REFS[i]); + if (v && !cJSON_IsNull(v)) { + api_set(copy, REFS[i], map_presets(v, pmap, pid)); + } + } + char dp[24]; + const cJSON *to = api_id(cJSON_GetObjectItem(z, "default_preset"), dp, sizeof(dp)) ? cJSON_GetObjectItem(pmap, dp) : NULL; + if (to) { + api_set(copy, "default_preset", cJSON_Duplicate(to, false)); + } + const cJSON *sids = cJSON_GetObjectItem(z, "sequence_ids"); + if (cJSON_IsArray(sids)) { + cJSON *mapped = cJSON_CreateArray(), *sid; + cJSON_ArrayForEach(sid, sids) + { + char k[24]; + if (api_id(sid, k, sizeof(k))) { + const cJSON *ns = cJSON_GetObjectItem(smap, k); + cJSON_AddItemToArray(mapped, cJSON_CreateString(ns ? ns->valuestring : k)); + } + } + api_set(copy, "sequence_ids", mapped); + } + char nid[16]; + api_add("zone", copy, nid, sizeof(nid)); + cJSON_AddItemToArray(zone_ids, cJSON_CreateString(nid)); + } + cJSON_Delete(keys); + cJSON_Delete(pmap); + cJSON_Delete(smap); + cJSON_AddItemToObject(prof, "zones", zone_ids); + const cJSON *scenes = cJSON_GetObjectItem(src, "scenes"); + cJSON_AddItemToObject(prof, "scenes", cJSON_IsArray(scenes) ? cJSON_Duplicate(scenes, true) : cJSON_CreateArray()); + cJSON_AddStringToObject(prof, "palette_id", palid); + store_save("palette"); + store_save("preset"); + store_save("zone"); + store_save("sequence"); + store_save("profile"); + engine_groups_changed(); + *out = prof; + return NULL; +} + +// The bundle from a body: {"bundle": {...}} or the bundle itself +static const cJSON *bundle_of(const cJSON *body) +{ + const cJSON *b = cJSON_GetObjectItem(body, "bundle"); + return cJSON_IsObject(b) ? b : body; +} + +static bool truthy(const cJSON *v, bool dflt) +{ + if (!v || cJSON_IsNull(v)) { + return dflt; + } + if (cJSON_IsString(v)) { + const char *s = v->valuestring; + return !strcasecmp(s, "1") || !strcasecmp(s, "true") || !strcasecmp(s, "yes") || !strcasecmp(s, "on"); + } + return cJSON_IsTrue(v) || (cJSON_IsNumber(v) && v->valuedouble != 0); +} + +static esp_err_t profiles_import(httpd_req_t *req) +{ + cJSON *body = api_body(req); + if (!body) { + return ESP_OK; + } + const cJSON *nm = cJSON_GetObjectItem(body, "name"); + char name[64] = ""; + if (cJSON_IsString(nm)) { + snprintf(name, sizeof(name), "%s", nm->valuestring); + } + bool apply = truthy(cJSON_GetObjectItem(body, "apply"), true); + char pid[16]; + cJSON *prof = NULL; + const char *err = import_profile(bundle_of(body), name, pid, sizeof(pid), &prof); + cJSON_Delete(body); + if (err) { + return api_error(req, "400 Bad Request", err); + } + if (apply) { + api_set(store_settings(), "current_profile_id", cJSON_CreateString(pid)); + store_save("settings"); + } + cJSON *o = cJSON_CreateObject(); + cJSON_AddItemReferenceToObject(o, pid, prof); + cJSON_AddStringToObject(o, "id", pid); + return api_json(req, "201 Created", o, true); +} + +static esp_err_t presets_import(httpd_req_t *req, const char *profile) +{ + cJSON *body = api_body(req); + if (!body) { + return ESP_OK; + } + const cJSON *b = bundle_of(body), *kind = cJSON_GetObjectItem(b, "kind"), *preset = cJSON_GetObjectItem(b, "preset"); + const char *err = !(cJSON_IsString(kind) && !strcmp(kind->valuestring, "preset")) ? "Not a preset bundle" + : !cJSON_IsObject(preset) ? "Bundle missing preset" + : NULL; + if (err) { + cJSON_Delete(body); + return api_error(req, "400 Bad Request", err); + } + cJSON *rec = api_preset_defaults(profile); + api_merge(rec, preset); + cJSON_Delete(body); + api_set(rec, "profile_id", cJSON_CreateString(profile)); + char id[16]; + api_add("preset", rec, id, sizeof(id)); + store_save("preset"); + cJSON *o = cJSON_CreateObject(); + cJSON_AddItemReferenceToObject(o, id, rec); + return api_json(req, "201 Created", o, true); +} + +static esp_err_t sequences_import(httpd_req_t *req, const char *profile) +{ + cJSON *body = api_body(req); + if (!body) { + return ESP_OK; + } + const cJSON *b = bundle_of(body), *kind = cJSON_GetObjectItem(b, "kind"), *seq = cJSON_GetObjectItem(b, "sequence"); + const char *err = !(cJSON_IsString(kind) && !strcmp(kind->valuestring, "sequence")) ? "Not a sequence bundle" + : !cJSON_IsObject(seq) ? "Bundle missing sequence" + : NULL; + if (err) { + cJSON_Delete(body); + return api_error(req, "400 Bad Request", err); + } + cJSON *map = import_presets(cJSON_GetObjectItem(b, "presets"), profile); + // Steps naming presets that were not in the bundle: copy those from this controller + cJSON *used = cJSON_CreateObject(), *it; + sequence_preset_ids(seq, used); + cJSON_ArrayForEach(it, used) + { + if (!cJSON_GetObjectItem(map, it->string)) { + cJSON *ref = cJSON_CreateString(it->string); + cJSON_Delete(map_presets(ref, map, profile)); // copies the preset and records the mapping + cJSON_Delete(ref); + } + } + cJSON_Delete(used); + cJSON *rec = api_sequence_defaults(); + cJSON *mapped = map_sequence(seq, map); + api_merge(rec, mapped); + cJSON_Delete(mapped); + cJSON_Delete(map); + cJSON_Delete(body); + api_set(rec, "profile_id", cJSON_CreateString(profile)); + char id[16]; + api_add("sequence", rec, id, sizeof(id)); + store_save("preset"); + store_save("sequence"); + cJSON *o = cJSON_CreateObject(); + cJSON_AddItemReferenceToObject(o, id, rec); + return api_json(req, "201 Created", o, true); +} + +bool bundles_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) +{ + const bool profiles = !strcmp(seg[0], "profiles"), presets = !strcmp(seg[0], "presets"), + sequences = !strcmp(seg[0], "sequences"); + if (!profiles && !presets && !sequences) { + return false; + } + const bool is_import = n == 2 && req->method == HTTP_POST && !strcmp(seg[1], "import"); + const bool is_export = n == 3 && req->method == HTTP_GET && !strcmp(seg[2], "export"); + if (!is_import && !is_export) { + return false; + } + const char *profile = api_current_profile(); + if (is_import) { + *ret = profiles ? profiles_import(req) + : !profile ? api_error(req, "404 Not Found", "No profile available") + : presets ? presets_import(req, profile) + : sequences_import(req, profile); + return true; + } + cJSON *b = NULL; + if (profiles) { + b = export_profile(seg[1]); + } else { + const cJSON *rec = cJSON_GetObjectItem(store_coll(presets ? "preset" : "sequence"), seg[1]); + if (rec && profile && owned_by(rec, profile)) { + b = bundle(presets ? "preset" : "sequence"); + cJSON_AddItemToObject(b, presets ? "preset" : "sequence", cJSON_Duplicate(rec, true)); + if (sequences) { + cJSON *ps = cJSON_AddObjectToObject(b, "presets"), *used = cJSON_CreateObject(), *it; + sequence_preset_ids(rec, used); + cJSON_ArrayForEach(it, used) + { + const cJSON *p = cJSON_GetObjectItem(store_coll("preset"), it->string); + if (p && owned_by(p, profile)) { + cJSON_AddItemToObject(ps, it->string, cJSON_Duplicate(p, true)); + } + } + cJSON_Delete(used); + } + } + } + *ret = b ? api_json(req, "200 OK", b, true) + : api_error(req, "404 Not Found", profiles ? "Profile not found" : presets ? "Preset not found" : "Sequence not found"); + return true; +} diff --git a/main/res_group.c b/main/res_group.c index 424c0c4..fdf67b5 100644 --- a/main/res_group.c +++ b/main/res_group.c @@ -296,6 +296,32 @@ static esp_err_t identify(httpd_req_t *req, const char *id, const cJSON *g) return api_json(req, "200 OK", o, true); } +// main's Group.load: every group gets the newer fields +void api_migrate_groups(void) +{ + bool changed = false; + cJSON *defs = cJSON_Parse(DEFAULTS), *g; + static const char *const KEYS[] = { "devices", "wifi_driver_display_name", "wifi_driver_num_leds", "wifi_color_order", + "wifi_startup_mode", "output_brightness", "bridge_id" }; + cJSON_ArrayForEach(g, store_coll("group")) + { + if (!cJSON_IsObject(g)) { + continue; + } + for (size_t i = 0; i < sizeof(KEYS) / sizeof(KEYS[0]); i++) { + if (!cJSON_GetObjectItem(g, KEYS[i])) { + cJSON_AddItemToObject(g, KEYS[i], cJSON_Duplicate(cJSON_GetObjectItem(defs, KEYS[i]), true)); + changed = true; + } + } + normalize_devices(g); + } + cJSON_Delete(defs); + if (changed) { + store_save("group"); + } +} + bool groups_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) { cJSON *all = store_coll("group"); diff --git a/main/res_misc.c b/main/res_misc.c index 08476a4..e6d261b 100644 --- a/main/res_misc.c +++ b/main/res_misc.c @@ -93,6 +93,11 @@ static const char SEQ_DEFAULTS[] = "{\"name\":\"\",\"group_ids\":[],\"lanes\":[[ "\"advance_mode\":\"beats\",\"steps\":[],\"step_duration_ms\":3000," "\"sequence_transition\":500,\"loop\":true}"; +cJSON *api_sequence_defaults(void) +{ + return cJSON_Parse(SEQ_DEFAULTS); +} + static bool has_steps(const cJSON *lanes) { const cJSON *l; diff --git a/main/res_profile.c b/main/res_profile.c index 1329980..bde2669 100644 --- a/main/res_profile.c +++ b/main/res_profile.c @@ -12,7 +12,7 @@ /* ---------------------------------------------------------------- presets */ // A new preset before the request's fields are applied -static cJSON *preset_defaults(const char *profile_id) +cJSON *api_preset_defaults(const char *profile_id) { cJSON *p = cJSON_CreateObject(); cJSON_AddStringToObject(p, "name", ""); @@ -120,7 +120,7 @@ bool presets_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) *ret = ESP_OK; return true; } - cJSON *rec = preset_defaults(profile); + cJSON *rec = api_preset_defaults(profile); api_merge(rec, body); cJSON_Delete(body); api_set(rec, "profile_id", cJSON_CreateString(profile)); @@ -164,7 +164,7 @@ typedef struct { static const seed_t SEED[] = { { "on", "on", "[\"#FFFFFF\"]", 255, 100, { 0 } }, { "off", "off", "[]", 0, 100, { 0 } }, - { "rainbow", "rainbow", "[]", 255, 100, { 2 } }, + { "rainbow", "colour_cycle", "[]", 255, 100, { 2 } }, { "Colour Cycle", "colour_cycle", "[\"#FF0000\",\"#00FF00\",\"#0000FF\"]", 255, 100, { 1 } }, { "transition", "transition", "[\"#FF0000\",\"#00FF00\",\"#0000FF\"]", 255, 500, { 0 } }, { "flicker", "flicker", "[\"#FFB84D\"]", 255, 80, { 30 } }, @@ -172,7 +172,7 @@ static const seed_t SEED[] = { { "twinkle", "twinkle", "[\"#78C8FF\",\"#508CFF\",\"#B478FF\",\"#64DCE8\",\"#A0C8FF\"]", 255, 55, { 72, 140, 2, 6 } }, }; static const seed_t SEED_DJ[] = { - { "DJ Rainbow", "rainbow", "[]", 220, 60, { 12 } }, + { "DJ Rainbow", "colour_cycle", "[]", 220, 60, { 12 } }, { "DJ Single Color", "on", "[\"#ff00ff\"]", 220, 100, { 0 } }, { "DJ Transition", "transition", "[\"#ff0000\",\"#00ff00\",\"#0000ff\"]", 220, 250, { 0 } }, }; @@ -183,7 +183,7 @@ static void seed_zone(const char *profile, const char *zone_name, const char *dr { cJSON *flat = cJSON_CreateArray(); for (int i = 0; i < count; i++) { - cJSON *p = preset_defaults(profile); + cJSON *p = api_preset_defaults(profile); api_set(p, "name", cJSON_CreateString(seed[i].name)); api_set(p, "pattern", cJSON_CreateString(seed[i].pattern)); api_set(p, "colors", cJSON_Parse(seed[i].colors)); @@ -395,8 +395,8 @@ static bool used_elsewhere(const char *skip, const char *key, const char *id) return false; } -// DELETE /profiles/: the profile with its presets, and its zones and palette unless another profile -// uses them. Ids are reused (next id = highest + 1), so leftovers would turn up in the next new profile. +// DELETE /profiles/: the profile with its presets and sequences, and its zones and palette unless +// another profile uses them. Ids are reused (next id = highest + 1), so leftovers would turn up in the next new profile. static esp_err_t delete_profile(httpd_req_t *req, const char *id) { char pid[24]; @@ -405,14 +405,20 @@ static esp_err_t delete_profile(httpd_req_t *req, const char *id) if (!prof) { return api_error(req, "404 Not Found", "Profile not found"); } - cJSON *presets = store_coll("preset"), *it = presets->child; - while (it) { - cJSON *next = it->next; - char owner[24]; - if (api_id(cJSON_GetObjectItem(it, "profile_id"), owner, sizeof(owner)) && !strcmp(owner, pid)) { - cJSON_Delete(cJSON_DetachItemViaPointer(presets, it)); + static const char *const OWNED[] = { "preset", "sequence" }; + for (size_t i = 0; i < sizeof(OWNED) / sizeof(OWNED[0]); i++) { + cJSON *coll = store_coll(OWNED[i]), *it = coll->child; + while (it) { + cJSON *next = it->next; + char owner[24]; + if (api_id(cJSON_GetObjectItem(it, "profile_id"), owner, sizeof(owner)) && !strcmp(owner, pid)) { + if (i == 1) { + seqplay_stop_if(it->string); + } + cJSON_Delete(cJSON_DetachItemViaPointer(coll, it)); + } + it = next; } - it = next; } const cJSON *z; cJSON_ArrayForEach(z, profile_zones(prof)) @@ -433,6 +439,7 @@ static esp_err_t delete_profile(httpd_req_t *req, const char *id) store_save("settings"); } store_save("preset"); + store_save("sequence"); store_save("zone"); store_save("palette"); store_save("profile"); @@ -553,7 +560,7 @@ static esp_err_t create_zone(httpd_req_t *req) const cJSON *name = cJSON_GetObjectItem(body, "name"); if (!cJSON_IsString(name) || !name->valuestring[0]) { cJSON_Delete(body); - return api_error(req, "400 Bad Request", "name is required"); + return api_error(req, "400 Bad Request", "Zone name cannot be empty"); } cJSON *names = cJSON_GetObjectItem(body, "names"); if (!names) { @@ -565,9 +572,26 @@ static esp_err_t create_zone(httpd_req_t *req) const cJSON *presets = cJSON_GetObjectItem(body, "presets"); cJSON_AddItemToObject(z, "presets", cJSON_IsArray(presets) ? cJSON_Duplicate(presets, true) : cJSON_CreateArray()); cJSON_AddNullToObject(z, "default_preset"); + cJSON_AddArrayToObject(z, "group_ids"); + cJSON_AddObjectToObject(z, "preset_group_ids"); + cJSON_AddArrayToObject(z, "sequence_ids"); + cJSON_AddNumberToObject(z, "brightness", 255); cJSON_DeleteItemFromObject(body, "ids"); + const cJSON *kind = cJSON_GetObjectItem(body, "content_kind"); + if (kind && !(cJSON_IsString(kind) && (!strcmp(kind->valuestring, "presets") || !strcmp(kind->valuestring, "sequences")))) { + cJSON_DeleteItemFromObject(body, "content_kind"); + } api_merge(z, body); cJSON_Delete(body); + cJSON *gids = cJSON_CreateArray(), *g; + cJSON_ArrayForEach(g, cJSON_GetObjectItem(z, "group_ids")) + { + char id[24]; + if (api_id(g, id, sizeof(id))) { + cJSON_AddItemToArray(gids, cJSON_CreateString(id)); + } + } + api_set(z, "group_ids", gids); char id[16]; api_add("zone", z, id, sizeof(id)); cJSON *list = profile_zone_list(); @@ -786,3 +810,56 @@ bool zones_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) } return false; } + +/* -------------------------------------------------------------- migration */ + +// Preset ids a zone lists (presets_flat, else presets as a flat list or rows) +static bool zone_has_presets(const cJSON *z) +{ + const cJSON *flat = cJSON_GetObjectItem(z, "presets_flat"); + if (cJSON_IsArray(flat)) { + return cJSON_GetArraySize(flat) > 0; + } + const cJSON *row; + cJSON_ArrayForEach(row, cJSON_GetObjectItem(z, "presets")) + { + if (cJSON_IsString(row) || cJSON_GetArraySize(row) > 0) { + return true; + } + } + return false; +} + +// main's Zone.load: group_ids, preset_group_ids, sequence_ids and content_kind on every zone +void api_migrate_zones(void) +{ + bool changed = false; + cJSON *z; + cJSON_ArrayForEach(z, store_coll("zone")) + { + if (!cJSON_IsObject(z)) { + continue; + } + if (!cJSON_IsArray(cJSON_GetObjectItem(z, "group_ids"))) { + api_set(z, "group_ids", cJSON_CreateArray()); + changed = true; + } + if (!cJSON_IsObject(cJSON_GetObjectItem(z, "preset_group_ids"))) { + api_set(z, "preset_group_ids", cJSON_CreateObject()); + changed = true; + } + if (!cJSON_IsArray(cJSON_GetObjectItem(z, "sequence_ids"))) { + api_set(z, "sequence_ids", cJSON_CreateArray()); + changed = true; + } + const cJSON *kind = cJSON_GetObjectItem(z, "content_kind"); + if (!(cJSON_IsString(kind) && (!strcmp(kind->valuestring, "presets") || !strcmp(kind->valuestring, "sequences")))) { + bool seqs = cJSON_GetArraySize(cJSON_GetObjectItem(z, "sequence_ids")) > 0; + api_set(z, "content_kind", cJSON_CreateString(seqs && !zone_has_presets(z) ? "sequences" : "presets")); + changed = true; + } + } + if (changed) { + store_save("zone"); + } +} diff --git a/main/seqplay.c b/main/seqplay.c index ba8662f..bc067fc 100644 --- a/main/seqplay.c +++ b/main/seqplay.c @@ -6,6 +6,8 @@ #include "api_util.h" #include "beat.h" #include "engine.h" +#include "espnow_tx.h" +#include "bench.h" #include "esp_heap_caps.h" #include "esp_log.h" #include "esp_timer.h" @@ -466,6 +468,10 @@ static void beat_task(void *arg) if (!audio_drives()) { bool down = s_sim_beats % BEATS_PER_BAR == 0; s_sim_beats++; + // Drivers get the clock's beats too, so manual (beat-stepped) presets keep moving + if (!bench_running()) { + espnow_tx_beat(60e6f / interval, down, (int)((s_sim_beats - 1) % BEATS_PER_BAR) + 1); + } on_beat(down); } continue; @@ -492,6 +498,7 @@ esp_err_t seqplay_init(void) const cJSON *a = cJSON_GetObjectItem(store_settings(), "audio_timing"); s_audio = !cJSON_IsFalse(a); store_unlock(); + espnow_tx_set_mic_beats(s_audio); return xTaskCreate(beat_task, "seqplay", 6144, NULL, 4, NULL) == pdPASS ? ESP_OK : ESP_ERR_NO_MEM; } @@ -673,6 +680,7 @@ void seqplay_set_audio(bool on) { store_lock(); s_audio = on; + espnow_tx_set_mic_beats(on); api_set(store_settings(), "audio_timing", cJSON_CreateBool(on)); store_save("settings"); store_unlock(); @@ -682,3 +690,17 @@ bool seqplay_audio(void) { return s_audio; } + +const char *seqplay_switch_wait(void) +{ + store_lock(); + bool down = wait_for_downbeat(); + store_unlock(); + return down ? "downbeat" : "beat"; +} + +void seqplay_clock(int *bar_beat, uint32_t *tick) +{ + *tick = s_sim_beats; + *bar_beat = s_sim_beats ? (int)((s_sim_beats - 1) % BEATS_PER_BAR) + 1 : 1; +} diff --git a/main/seqplay.h b/main/seqplay.h index 6c6b55d..2dc13a0 100644 --- a/main/seqplay.h +++ b/main/seqplay.h @@ -37,3 +37,8 @@ const char *seqplay_done_readout(void); // Use the mic's beats for timing (main's audio start/stop); off falls back to the clock void seqplay_set_audio(bool on); bool seqplay_audio(void); + +// The start-switch wait in effect: "downbeat" (saved, and the mic is timing) or "beat" +const char *seqplay_switch_wait(void); +// The clock's bar position (1..4) and how many beats it has ticked +void seqplay_clock(int *bar_beat, uint32_t *tick); diff --git a/main/ws.c b/main/ws.c index 84b4c92..9b4e7d5 100644 --- a/main/ws.c +++ b/main/ws.c @@ -45,17 +45,20 @@ static void forward(httpd_req_t *req, const char *text) } } +// Right after the upgrade: the v1 greeting. The controller keeps no Wi-Fi driver connections, so the +// snapshot is always empty. +static esp_err_t on_open(httpd_req_t *req) +{ + send_text(req, "{\"type\":\"device_tcp_snapshot\",\"connected_ips\":[]}"); + return ESP_OK; +} + static esp_err_t ws_handler(httpd_req_t *req) { - if (req->method == HTTP_GET) { - if (httpd_ws_get_fd_info(req->handle, httpd_req_to_sockfd(req)) != HTTPD_WS_CLIENT_WEBSOCKET) { - httpd_resp_set_status(req, "426 Upgrade Required"); - httpd_resp_set_hdr(req, "Upgrade", "websocket"); - return httpd_resp_sendstr(req, "websocket only"); - } - // The controller keeps no Wi-Fi driver connections, so the v1 snapshot is always empty - send_text(req, "{\"type\":\"device_tcp_snapshot\",\"connected_ips\":[]}"); - return ESP_OK; + if (req->method == HTTP_GET) { // only a plain GET reaches the handler; the upgrade is answered by httpd + httpd_resp_set_status(req, "426 Upgrade Required"); + httpd_resp_set_hdr(req, "Upgrade", "websocket"); + return httpd_resp_sendstr(req, "websocket only"); } httpd_ws_frame_t f = { 0 }; esp_err_t err = httpd_ws_recv_frame(req, &f, 0); @@ -85,6 +88,8 @@ static esp_err_t ws_handler(httpd_req_t *req) esp_err_t ws_register(httpd_handle_t server) { - const httpd_uri_t u = { .uri = "/ws", .method = HTTP_GET, .handler = ws_handler, .is_websocket = true }; + const httpd_uri_t u = { + .uri = "/ws", .method = HTTP_GET, .handler = ws_handler, .is_websocket = true, .ws_post_handshake_cb = on_open + }; return httpd_register_uri_handler(server, &u); } diff --git a/sdkconfig.defaults b/sdkconfig.defaults index 3929b70..a3a90ba 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -20,3 +20,4 @@ CONFIG_BEAT_TEST_GPIO=4 CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y # /ws (browser websocket) CONFIG_HTTPD_WS_SUPPORT=y +CONFIG_HTTPD_WS_POST_HANDSHAKE_CB_SUPPORT=y diff --git a/test/api/README.md b/test/api/README.md index adc879b..66cf58a 100644 --- a/test/api/README.md +++ b/test/api/README.md @@ -1,6 +1,6 @@ # API tests -HTTP tests against a running controller, ported from the v1 Python app's `tests/test_endpoints_pytest.py` and `tests/test_endpoints.py`. They need `pytest` and `requests`. +HTTP tests against a running controller, ported from the Python app's endpoint tests (`tests/test_endpoints_pytest.py` and `tests/test_endpoints.py`) on both the `animation-engine` and `main` lines, plus `main`'s bundle, audio, group and sequence tests where they work over HTTP. They need `pytest`, `requests` and `websocket-client`. ```bash make test-api HOST=10.1.1.180 @@ -8,7 +8,7 @@ make test-api HOST=10.1.1.180 or `python3 -m pytest test/api --host ` (or set `LED_HOST`). Without a host every test is skipped. -The tests create and delete profiles, presets, zones and so on. Before the run they save every collection (`GET /db/`), and afterwards they write each one back (`PUT /db/`). Zone play and preset send do go out over ESP-NOW. They use made-up driver names (`pytest-a`, `pytest-nobody`) so real drivers ignore them. +The tests create and delete profiles, presets, zones and so on. The sequence tests switch mic timing off and run the beat clock at 200 BPM for a few seconds; mic timing is switched back on afterwards. Before the run they save every collection (`GET /db/`), and afterwards they write each one back (`PUT /db/`). Zone play and preset send do go out over ESP-NOW. They use made-up driver names (`pytest-a`, `pytest-nobody`) so real drivers ignore them. ## v1 features v2 does not have yet diff --git a/test/api/test_audio.py b/test/api/test_audio.py new file mode 100644 index 0000000..52f4ac3 --- /dev/null +++ b/test/api/test_audio.py @@ -0,0 +1,59 @@ +"""main's /api/audio routes on the controller's microphone.""" + +import json + +import requests + +STATUS_KEYS = {"running", "bpm", "beat_readout", "bar_beat", "is_downbeat", "sequence", "sequence_pending", + "audio_run", "audio_simulated_bpm", "bpm_simulated", "sequence_switch_wait"} + + +def test_status(c): + resp = c.get("/api/audio/status") + assert resp.status_code == 200 + st = resp.json()["status"] + assert STATUS_KEYS <= set(st) + assert st["sequence"]["active"] in (True, False) + + +def test_start_stop(c): + was = c.get("/api/audio/status").json()["status"]["running"] + resp = c.post("/api/audio/stop") + assert resp.json()["ok"] is True + st = resp.json()["status"] + assert st["running"] is False and st["bpm_simulated"] is True + assert st["bpm"] == st["audio_simulated_bpm"] + assert c.post("/api/audio/reset").status_code == 409 # nothing to reset while stopped + assert c.post("/api/audio/start").json()["status"]["running"] is True + assert c.post("/api/audio/reset").json()["ok"] is True + assert c.post("/api/audio/anchor-bar").json()["ok"] is True + if not was: + c.post("/api/audio/stop") + + +def test_devices(c): + data = c.get("/api/audio/devices").json() + assert data["devices"][0]["is_default"] is True + resp = c.put("/api/audio/device", json={"device_select": "i2s"}) + assert resp.json()["audio_run"]["device_select"] == "i2s" + + +def test_events_stream(base_url): + # From main's test_audio_events_sse_first_chunk: the first event is a status snapshot + with requests.get(base_url + "/api/audio/events", stream=True, timeout=10) as resp: + assert resp.status_code == 200 + assert resp.headers["Content-Type"].startswith("text/event-stream") + for line in resp.iter_lines(decode_unicode=True): + if line.startswith("data: "): + event = json.loads(line[6:]) + assert event["type"] == "status" + assert STATUS_KEYS <= set(event["status"]) + break + + +def test_settings_switch_wait(c): + assert c.put("/settings", json={"sequence_switch_wait": "downbeat"}).status_code == 200 + assert c.get("/settings").json()["sequence_switch_wait"] == "downbeat" + assert c.put("/settings", json={"sequence_switch_wait": "bar"}).status_code == 400 + assert c.put("/settings", json={"audio_simulated_bpm": 999}).status_code == 200 + assert c.get("/settings").json()["audio_simulated_bpm"] == 200 # clamped to the BPM range diff --git a/test/api/test_bundles.py b/test/api/test_bundles.py new file mode 100644 index 0000000..fc49016 --- /dev/null +++ b/test/api/test_bundles.py @@ -0,0 +1,82 @@ +"""Import/export bundles (main's tests/test_profile_bundle.py over HTTP).""" + +import pytest + +from helpers import new_id, unique + + +@pytest.fixture +def profile(c): + pid = new_id(c.post("/profiles", json={"name": unique("pytest-profile")})) + assert c.post(f"/profiles/{pid}/apply").status_code == 200 + yield pid + c.delete(f"/profiles/{pid}") + + +def test_profile_round_trip(c, profile): + presets = c.get("/presets").json() + a = next(iter(presets)) + sid = new_id(c.post("/sequences", json={"name": "pytest-seq", "lanes": [[{"preset_id": a, "beats": 2}]]})) + zid = c.get(f"/profiles/{profile}").json()["zones"][0] + c.put(f"/zones/{zid}", json={"sequence_ids": [sid]}) + c.put(f"/palettes/{c.get(f'/profiles/{profile}').json()['palette_id']}", json={"colors": ["#123456"]}) + + bundle = c.get(f"/profiles/{profile}/export").json() + assert bundle["version"] == 1 and bundle["kind"] == "profile" + assert bundle["palette"]["colors"] == ["#123456"] + assert zid in bundle["zones"] and sid in bundle["sequences"] + assert set(presets) == set(bundle["presets"]) + + resp = c.post("/profiles/import", json={"bundle": bundle, "name": "pytest-imported"}) + assert resp.status_code == 201 + new = resp.json()["id"] + assert resp.json()[new]["name"] == "pytest-imported" + assert c.get("/profiles/current").json()["id"] == new # applied by default + imported = c.get("/presets").json() + assert len(imported) == len(presets) and not set(imported) & set(presets) + nz = c.get(f"/profiles/{new}").json()["zones"] + assert len(nz) == 1 and nz[0] != zid + zone = c.get(f"/zones/{nz[0]}").json() + new_sid = zone["sequence_ids"][0] + assert new_sid != sid + seq = c.get(f"/sequences/{new_sid}").json() + assert seq["lanes"][0][0]["preset_id"] in imported + pal = c.get(f"/palettes/{c.get(f'/profiles/{new}').json()['palette_id']}").json() + assert pal["colors"] == ["#123456"] + c.delete(f"/profiles/{new}") + + +def test_profile_import_rejects_other_bundles(c, profile): + assert c.post("/profiles/import", json={"version": 2, "kind": "profile", "profile": {}}).status_code == 400 + assert c.post("/profiles/import", json={"version": 1, "kind": "preset", "profile": {}}).status_code == 400 + assert c.post("/profiles/import", json={"version": 1, "kind": "profile"}).status_code == 400 + + +def test_export_unknown_profile(c): + assert c.get("/profiles/999999/export").status_code == 404 + + +def test_preset_round_trip(c, profile): + a = next(iter(c.get("/presets").json())) + bundle = c.get(f"/presets/{a}/export").json() + assert bundle["kind"] == "preset" + resp = c.post("/presets/import", json={"bundle": bundle}) + assert resp.status_code == 201 + new = new_id(resp) + assert new != a + assert resp.json()[new]["name"] == bundle["preset"]["name"] + assert resp.json()[new]["profile_id"] == profile + assert c.post("/presets/import", json={"kind": "sequence"}).status_code == 400 + + +def test_sequence_round_trip(c, profile): + a = next(iter(c.get("/presets").json())) + sid = new_id(c.post("/sequences", json={"name": "pytest-seq", "lanes": [[{"preset_id": a, "beats": 3}]]})) + bundle = c.get(f"/sequences/{sid}/export").json() + assert bundle["kind"] == "sequence" and a in bundle["presets"] + resp = c.post("/sequences/import", json={"bundle": bundle}) + assert resp.status_code == 201 + new = new_id(resp) + step = resp.json()[new]["lanes"][0][0] + assert step["beats"] == 3 and step["preset_id"] != a + assert step["preset_id"] in c.get("/presets").json() diff --git a/test/api/test_collections.py b/test/api/test_collections.py index 02a16f1..1bb4585 100644 --- a/test/api/test_collections.py +++ b/test/api/test_collections.py @@ -1,69 +1,6 @@ -"""Groups, sequences, scenes and palettes.""" +"""Scenes and palettes.""" -from helpers import find_id_by_field, new_id, unique - - -def test_groups(c): - name = unique("pytest-group") - assert c.post("/groups", json={"name": name}).status_code == 201 - gid = find_id_by_field(c.get("/groups").json(), "name", name) - resp = c.get(f"/groups/{gid}") - assert resp.status_code == 200 - assert resp.json()["name"] == name - resp = c.put(f"/groups/{gid}", json={"brightness": 10}) - assert resp.status_code == 200 - assert resp.json()["brightness"] == 10 - assert c.delete(f"/groups/{gid}").status_code == 200 - - -def test_sequences_crud(c): - name = unique("pytest-seq") - resp = c.post("/sequences", json={"name": name, "steps": [{"preset_id": "1", "duration_s": 2}]}) - assert resp.status_code == 201 - sid = find_id_by_field(c.get("/sequences").json(), "name", name) - resp = c.get(f"/sequences/{sid}") - assert resp.status_code == 200 - assert resp.json()["steps"] == [{"preset_id": "1", "duration_s": 2.0}] - resp = c.put(f"/sequences/{sid}", json={"loop": False, "repeat_count": 2}) - assert resp.status_code == 200 - assert resp.json()["loop"] is False and resp.json()["repeat_count"] == 2 - assert c.get("/sequences/status").status_code == 200 - assert c.delete(f"/sequences/{sid}").status_code == 200 - - -def test_sequence_step_needs_preset(c): - sid = new_id(c.post("/sequences", json={"name": unique("pytest-seq"), "steps": []})) - assert c.put(f"/sequences/{sid}", json={"steps": [{"duration_s": 1}]}).status_code == 400 - c.delete(f"/sequences/{sid}") - - -def test_sequence_without_zone_cannot_play(c): - sid = new_id(c.post("/sequences", json={"name": unique("pytest-seq"), - "steps": [{"preset_id": "1", "duration_s": 1}]})) - assert c.post(f"/sequences/{sid}/play").status_code == 400 - c.delete(f"/sequences/{sid}") - - -def test_sequence_play_and_stop(c): - profile = new_id(c.post("/profiles", json={"name": unique("pytest-engine")})) - c.post(f"/profiles/{profile}/apply") - preset = new_id(c.post("/presets", json={"name": "pytest-on", "pattern": "on", "colors": ["#ff0000"]})) - zone = new_id(c.post("/zones", json={"name": "pytest-engine-zone", "names": ["pytest-nobody"]})) - c.post("/sequences", json={"name": "pytest-engine-seq", "zone_id": zone, "loop": False, - "steps": [{"preset_id": preset, "duration_s": 0.5}]}) - sid = find_id_by_field(c.get("/sequences").json(), "name", "pytest-engine-seq") - - resp = c.post(f"/sequences/{sid}/play") - assert resp.status_code == 200 - assert resp.json()["zone_id"] == zone - assert c.get(f"/sequences/{sid}").json()["active"] is True - resp = c.post(f"/sequences/{sid}/stop") - assert resp.json()["stopped"] is True - assert c.get(f"/sequences/{sid}").json()["active"] is False - - c.delete(f"/sequences/{sid}") - c.delete(f"/zones/{zone}") - c.delete(f"/profiles/{profile}") +from helpers import find_id_by_field, unique def test_scenes(c): diff --git a/test/api/test_groups.py b/test/api/test_groups.py new file mode 100644 index 0000000..e211f78 --- /dev/null +++ b/test/api/test_groups.py @@ -0,0 +1,123 @@ +"""Device groups (main's controllers/group.py) and combined brightness.""" + +import pytest + +from helpers import find_id_by_field, new_id, unique + +MAC = "aabbccddee01" # made up: no driver answers it + + +@pytest.fixture +def profile(c): + pid = new_id(c.post("/profiles", json={"name": unique("pytest-profile")})) + assert c.post(f"/profiles/{pid}/apply").status_code == 200 + yield pid + c.delete(f"/profiles/{pid}") + + +@pytest.fixture +def device(c): + c.delete(f"/devices/{MAC}") + assert c.post("/devices", json={"name": "pytest-g", "mac": MAC, "output_brightness": 128}).status_code == 201 + yield MAC + c.delete(f"/devices/{MAC}") + + +@pytest.fixture +def group(c, device): + resp = c.post("/groups", json={"name": unique("pytest-group"), "devices": ["AA:BB:CC:DD:EE:01"], + "output_brightness": 128}) + assert resp.status_code == 201 + gid = str(resp.json()["id"]) + yield gid + c.delete(f"/groups/{gid}") + + +def test_crud(c): + name = unique("pytest-group") + resp = c.post("/groups", json={"name": name}) + assert resp.status_code == 201 + assert resp.json()["devices"] == [] + assert resp.json()["output_brightness"] == 255 + gid = find_id_by_field(c.get("/groups").json(), "name", name) + resp = c.get(f"/groups/{gid}") + assert resp.status_code == 200 + assert resp.json()["name"] == name + resp = c.put(f"/groups/{gid}", json={"brightness": 10}) + assert resp.status_code == 200 + assert resp.json()["brightness"] == 10 + assert c.delete(f"/groups/{gid}").status_code == 200 + assert c.get(f"/groups/{gid}").status_code == 404 + + +def test_device_macs_normalized(c, group): + assert c.get(f"/groups/{group}").json()["devices"] == [MAC] + + +def test_profile_scoped_group(c, profile): + resp = c.post("/groups", json={"name": unique("pytest-scoped"), "profile_scoped": True}) + gid = str(resp.json()["id"]) + assert resp.json()["profile_id"] == profile + other = new_id(c.post("/profiles", json={"name": unique("pytest-other")})) + c.post(f"/profiles/{other}/apply") + assert gid not in c.get("/groups").json() + assert c.get(f"/groups/{gid}").status_code == 404 + c.post(f"/profiles/{profile}/apply") + assert gid in c.get("/groups").json() + c.delete(f"/groups/{gid}") + c.delete(f"/profiles/{other}") + + +def test_resolve_brightness(c, group): + # global 255 x group 128 x device 128 (x zone 255) -> round(255 * 128/255 * 128/255) = 64 + resp = c.post("/devices/resolve-brightness", json={"macs": [MAC], "zone_brightness": 255}) + assert resp.status_code == 200 + assert resp.json()["values"] == {MAC: 64} + + +def test_resolve_brightness_needs_list(c): + assert c.post("/devices/resolve-brightness", json={"macs": "x"}).status_code == 400 + + +def test_group_brightness(c, group): + resp = c.post(f"/groups/{group}/brightness") + assert resp.status_code == 200 + assert resp.json()["sent"] == 1 + + +def test_group_identify(c, group): + resp = c.post(f"/groups/{group}/identify") + assert resp.status_code == 200 + assert resp.json()["sent"] == 1 + + +def test_group_identify_needs_devices(c): + gid = str(c.post("/groups", json={"name": unique("pytest-empty")}).json()["id"]) + assert c.post(f"/groups/{gid}/identify").status_code == 400 + c.delete(f"/groups/{gid}") + + +def test_group_driver_config(c, group): + assert c.post(f"/groups/{group}/driver-config", json={}).status_code == 400 + resp = c.post(f"/groups/{group}/driver-config", json={"wifi_driver_num_leds": 60}) + assert resp.status_code == 200 + assert resp.json()["sent"] == 1 + + +def test_device_brightness_and_config(c, device): + resp = c.post(f"/devices/{device}/brightness", json={"zone_brightness": 255}) + assert resp.status_code == 200 + assert resp.json()["brightness"] == 128 + assert c.post(f"/devices/{device}/driver-config", json={}).status_code == 400 + assert c.post(f"/devices/{device}/driver-config", json={"num_leds": 30}).status_code == 200 + + +def test_update_groups_push(c): + resp = c.post("/devices/groups") + espnow = [d for d in c.get("/devices").json().values() if d.get("transport") == "espnow"] + if not espnow: + assert resp.status_code == 400 + return + data = resp.json() + assert data["total"] == len(espnow) + assert data["sent"] + data["failed"] == data["total"] diff --git a/test/api/test_profiles.py b/test/api/test_profiles.py index 6c0ce9c..5d6e614 100644 --- a/test/api/test_profiles.py +++ b/test/api/test_profiles.py @@ -2,7 +2,7 @@ import pytest from helpers import new_id, unique -# Presets every new profile is seeded with (v1 controllers/profile.py) +# Presets every new profile is seeded with (main's controllers/profile.py) SEEDED = {"on", "off", "rainbow", "Colour Cycle", "transition", "flicker", "flame", "twinkle"} @@ -81,7 +81,21 @@ def test_clone(c, profile): assert c.delete(f"/profiles/{clone}").status_code == 200 +def test_seeded_rainbow_uses_colour_cycle(c, profile): + presets = c.get("/presets").json().values() + assert next(p for p in presets if p["name"] == "rainbow")["pattern"] == "colour_cycle" + + def test_delete(c): pid = new_id(c.post("/profiles", json={"name": unique("pytest-profile")})) + c.post(f"/profiles/{pid}/apply") + prof = c.get(f"/profiles/{pid}").json() + preset_ids = set(c.get("/presets").json()) + seq = new_id(c.post("/sequences", json={"name": "pytest-seq"})) assert c.delete(f"/profiles/{pid}").status_code == 200 assert c.get(f"/profiles/{pid}").status_code == 404 + # its presets, sequences, zones and palette go with it, so a profile that reuses the id starts clean + assert not preset_ids & set(c.get("/db/preset").json()) + assert not set(prof["zones"]) & set(c.get("/zones").json()["zones"]) + assert prof["palette_id"] not in c.get("/palettes").json() + assert seq not in c.get("/db/sequence").json() diff --git a/test/api/test_routes.py b/test/api/test_routes.py index 238ea66..1e0b4ff 100644 --- a/test/api/test_routes.py +++ b/test/api/test_routes.py @@ -26,3 +26,21 @@ def test_ws_rejects_plain_get(c): # A websocket endpoint refuses a request that is not an upgrade resp = c.get("/ws") assert resp.status_code in {400, 401, 403, 405, 426} + + +def test_ws_forwards_messages(base_url): + # From main's test_main_routes: the socket greets with the (empty) Wi-Fi snapshot and takes v1 messages + import websocket + + ws = websocket.create_connection(base_url.replace("http", "ws", 1) + "/ws", timeout=5) + try: + import json + + snapshot = json.loads(ws.recv()) + assert snapshot["type"] == "device_tcp_snapshot" + assert isinstance(snapshot["connected_ips"], list) + ws.send('{"v":"1","select":["off"],"groups":["pytest-none"]}') + ws.send("not json") + assert "error" in json.loads(ws.recv()) + finally: + ws.close() diff --git a/test/api/test_sequences.py b/test/api/test_sequences.py new file mode 100644 index 0000000..2e2756d --- /dev/null +++ b/test/api/test_sequences.py @@ -0,0 +1,145 @@ +"""Sequences (main's model and server playback). Playback runs on the controller's beat clock: the tests +switch mic timing off and set the clock to 200 BPM (0.3 s a beat).""" + +import time + +import pytest + +from helpers import find_id_by_field, new_id, unique + +BEAT_S = 0.3 + + +@pytest.fixture +def profile(c): + pid = new_id(c.post("/profiles", json={"name": unique("pytest-profile")})) + assert c.post(f"/profiles/{pid}/apply").status_code == 200 + yield pid + c.delete(f"/profiles/{pid}") + + +@pytest.fixture +def clock(c): + """Beats from the clock at 200 BPM; mic timing is restored afterwards.""" + was = c.get("/api/audio/status").json()["status"]["running"] + c.post("/api/audio/stop") + c.put("/settings", json={"audio_simulated_bpm": 200}) + yield + c.post("/sequences/stop") + if was: + c.post("/api/audio/start") + + +@pytest.fixture +def zone(c, profile): + zid = new_id(c.post("/zones", json={"name": unique("pytest-zone"), "names": ["pytest-nobody"]})) + yield zid + c.delete(f"/zones/{zid}") + + +def presets(c, n): + ids = list(c.get("/presets").json()) + assert len(ids) >= n + return ids[:n] + + +def test_crud(c, profile): + name = unique("pytest-seq") + resp = c.post("/sequences", json={"name": name, "steps": [{"preset_id": "1", "group_ids": []}]}) + assert resp.status_code == 201 + sid = new_id(resp) + rec = resp.json()[sid] + assert rec["profile_id"] == profile + assert rec["lanes"] == [[{"preset_id": "1", "group_ids": []}]] # steps become lane 0 + assert rec["advance_mode"] == "beats" + assert find_id_by_field(c.get("/sequences").json(), "name", name) == sid + resp = c.put(f"/sequences/{sid}", json={"step_duration_ms": 1234}) + assert resp.status_code == 200 + assert resp.json()["step_duration_ms"] == 1234 + assert c.delete(f"/sequences/{sid}").status_code == 200 + assert c.get(f"/sequences/{sid}").status_code == 404 + + +def test_scoped_to_profile(c, profile): + sid = new_id(c.post("/sequences", json={"name": unique("pytest-seq")})) + other = new_id(c.post("/profiles", json={"name": unique("pytest-other")})) + c.post(f"/profiles/{other}/apply") + assert sid not in c.get("/sequences").json() + assert c.get(f"/sequences/{sid}").status_code == 404 + c.post(f"/profiles/{profile}/apply") + c.delete(f"/sequences/{sid}") + c.delete(f"/profiles/{other}") + + +def test_play_needs_zone(c, profile): + sid = new_id(c.post("/sequences", json={"name": unique("pytest-seq")})) + assert c.post(f"/sequences/{sid}/play", json={}).status_code == 400 + assert c.post(f"/sequences/{sid}/play", json={"zone_id": "999999"}).status_code == 400 + + +def test_play_needs_steps(c, zone): + sid = new_id(c.post("/sequences", json={"name": unique("pytest-seq")})) + resp = c.post(f"/sequences/{sid}/play", json={"zone_id": zone}) + assert resp.status_code == 400 + assert "steps" in resp.json()["error"] + + +def test_sync_phase_needs_playback(c): + c.post("/sequences/stop") + assert c.post("/sequences/sync-phase", json={"mode": "step"}).status_code == 409 + + +def test_plays_on_beats_and_finishes(c, zone, clock): + a, b = presets(c, 2) + sid = new_id(c.post("/sequences", json={"name": unique("pytest-seq"), "loop": False, + "lanes": [[{"preset_id": a, "beats": 2}, {"preset_id": b, "beats": 1}]]})) + resp = c.post(f"/sequences/{sid}/play", json={"zone_id": zone}) + assert resp.status_code == 200 + assert resp.json()["ok"] is True and resp.json()["pending"] is False + st = c.get("/sequences/status").json() + assert st["active"] is True + assert st["sequence_id"] == sid and st["zone_id"] == zone + assert st["lane0_current_step"] == 1 and st["lane0_beats_per_step"] == 2 + assert st["sequence_beats_per_pass"] == 3 + seen = set() + deadline = time.monotonic() + 10 * BEAT_S + while time.monotonic() < deadline: + st = c.get("/sequences/status").json() + if not st["active"]: + break + seen.add(st["lane0_current_step"]) + time.sleep(BEAT_S / 3) + assert st["active"] is False, "sequence should end after its 3 beats" + assert {1, 2} <= seen + assert c.get("/api/audio/status").json()["status"]["beat_readout"] == "3/3" + + +def test_loops_and_stops(c, zone, clock): + a, = presets(c, 1) + sid = new_id(c.post("/sequences", json={"name": unique("pytest-seq"), "lanes": [[{"preset_id": a, "beats": 1}]]})) + c.post(f"/sequences/{sid}/play", json={"zone_id": zone}) + time.sleep(5 * BEAT_S) + assert c.get("/sequences/status").json()["active"] is True # loop defaults on + assert c.post("/sequences/sync-phase", json={"mode": "pass"}).json() == {"ok": True, "mode": "pass"} + assert c.post("/sequences/stop").json() == {"ok": True} + assert c.get("/sequences/status").json()["active"] is False + + +def test_switch_waits_for_next_beat(c, zone, clock): + a, b = presets(c, 2) + s1 = new_id(c.post("/sequences", json={"name": unique("pytest-seq"), "lanes": [[{"preset_id": a, "beats": 1}]]})) + s2 = new_id(c.post("/sequences", json={"name": unique("pytest-seq"), "lanes": [[{"preset_id": b, "beats": 1}]]})) + c.post(f"/sequences/{s1}/play", json={"zone_id": zone}) + resp = c.post(f"/sequences/{s2}/play", json={"zone_id": zone}) + assert resp.json()["pending"] is True + assert resp.json()["sequence_id"] == s2 + time.sleep(3 * BEAT_S) + assert c.get("/sequences/status").json()["sequence_id"] == s2 + + +def test_editing_stops_playback(c, zone, clock): + a, = presets(c, 1) + sid = new_id(c.post("/sequences", json={"name": unique("pytest-seq"), "lanes": [[{"preset_id": a, "beats": 1}]]})) + c.post(f"/sequences/{sid}/play", json={"zone_id": zone}) + c.put(f"/sequences/{sid}", json={"name": "edited"}) + assert c.get("/sequences/status").json()["active"] is False diff --git a/test/api/test_settings.py b/test/api/test_settings.py index 6d500a8..9aa90cf 100644 --- a/test/api/test_settings.py +++ b/test/api/test_settings.py @@ -21,3 +21,10 @@ def test_global_brightness(c): def test_global_brightness_out_of_range(c): assert c.put("/settings/settings", json={"global_brightness": 300}).status_code == 400 + + +def test_put_settings_root(c): + # main's UI writes PUT /settings + assert c.put("/settings", json={"audio_beat_phase_ms": 40}).status_code == 200 + assert c.get("/settings").json()["audio_beat_phase_ms"] == 40 + assert c.put("/settings", json={"audio_beat_phase_ms": 900}).status_code == 400 diff --git a/test/api/test_zones.py b/test/api/test_zones.py index 33013f3..0048608 100644 --- a/test/api/test_zones.py +++ b/test/api/test_zones.py @@ -118,3 +118,21 @@ def test_play_and_stop(c, zone): resp = c.post(f"/zones/{zone}/stop") assert resp.status_code == 200 assert resp.json()["stopped"] is True + + +def test_new_zone_has_main_fields(c, zone): + rec = c.get(f"/zones/{zone}").json() + assert rec["group_ids"] == [] and rec["preset_group_ids"] == {} and rec["sequence_ids"] == [] + assert rec["brightness"] == 255 + + +def test_zone_with_groups(c, profile): + # main's test_zone_content_kind: presets and sequences coexist; group ids are kept as strings + resp = c.post("/zones", json={"name": unique("pytest-zone"), "group_ids": [7], "content_kind": "sequences"}) + zid = new_id(resp) + rec = resp.json()[zid] + assert rec["group_ids"] == ["7"] and rec["content_kind"] == "sequences" + c.put(f"/zones/{zid}", json={"presets": [["1"]], "sequence_ids": ["1"]}) + rec = c.get(f"/zones/{zid}").json() + assert rec["presets"] == [["1"]] and rec["sequence_ids"] == ["1"] + c.delete(f"/zones/{zid}") diff --git a/web/static/audio.js b/web/static/audio.js index 8922880..0a2b5ee 100644 --- a/web/static/audio.js +++ b/web/static/audio.js @@ -1,188 +1,936 @@ -// 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; +(() => { + let beatEventSource = null; + let beatEventsReconnectTimer = null; + let audioDetectorRunning = false; + let lastBeatSeq = 0; + let lastSimulatedBeatTick = 0; + /** Prior poll had server zone sequence playback active (`status.sequence.active === true`). */ + let prevZoneSequencePlaybackActive = false; + /** + * After sequence playback ends/stops while audio keeps running, keep header # idle until the + * next beat bumps `beat_seq` (avoids the stuck final cumulative value vs sequence readout). + */ + let headerBeatStickyIdleAfterSeq = false; + /** @type {Set>} */ + const pendingBeatPhaseTimers = new Set(); + let cachedBeatPhaseMs = 0; + /** @type {{ device: string|number|null, device_override: string, device_select: string }} */ + let cachedAudioRun = { device: null, device_override: "", device_select: "" }; + /** True after client starts sequence playback until server reports stop. */ + let clientSequenceUiActive = false; + /** Last pass readout (e.g. ``6/6``) kept visible briefly after playback ends. */ + let stickySequenceBeatReadout = ""; - 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 el(id) { + return document.getElementById(id); } - function showBar(bar, meter, sure) { - if (!bar) { - barPhase.textContent = ''; + /** @param {Record} status */ + function resolveBeatReadoutText(status) { + let text = String((status && status.beat_readout) || "").trim(); + if (text) return text; + const seq = /** @type {Record|undefined} */ ( + status && status.sequence + ); + if (seq && seq.active) { + text = String(seq.beat_readout || "").trim(); + if (text) return text; + } + if (stickySequenceBeatReadout) { + return stickySequenceBeatReadout; + } + return ""; + } + + /** @param {Record} status */ + function updateBeatReadoutDisplays(status) { + const text = resolveBeatReadoutText(status); + for (const id of ["audio-top-beat-readout", "audio-modal-beat-readout"]) { + const n = el(id); + if (n) n.textContent = text; + } + } + + function updateBpmDisplay(bpm, simulated = false) { + const text = Number.isFinite(bpm) ? bpm.toFixed(1) : "--"; + for (const id of ["audio-bpm-value", "audio-top-bpm-value"]) { + const node = el(id); + if (node) node.textContent = text; + } + for (const id of ["audio-top-indicator", "audio-modal-beat-sync"]) { + const node = el(id); + if (node) node.classList.toggle("audio-simulated", !!simulated); + } + } + + /** Zone sequence playback (server); only when `active === true` is beat X/Y meaningful. */ + function sequencePlaybackActiveFromStatus(status) { + const seq = /** @type {Record|undefined} */ ( + status && status.sequence + ); + return !!(seq && seq.active); + } + + /** Sequence playing or waiting on beat/downbeat before start (simulated beats still run). */ + function sequenceBeatUiActiveFromStatus(status) { + if (sequencePlaybackActiveFromStatus(status)) return true; + const pending = /** @type {Record|undefined} */ ( + status && status.sequence_pending + ); + return !!(pending && pending.pending); + } + + function resolveSeqUiActive(status) { + return sequenceBeatUiActiveFromStatus(status) || clientSequenceUiActive; + } + + /** @param {Record} status */ + function updateTopIndicatorFromStatus(status) { + const running = !!(status && status.running); + const bpmSimulated = !!(status && status.bpm_simulated); + const seqUiActive = resolveSeqUiActive(status); + const show = running || seqUiActive || bpmSimulated; + setTopBpmVisible(show); + if (!show || running) return; + const simBpm = + status && status.audio_simulated_bpm != null + ? Number(status.audio_simulated_bpm) + : getSimulatedBpmPercent(); + updateBpmDisplay(Number.isFinite(simBpm) ? simBpm : null, true); + } + + /** @param {Record} status */ + function shouldKeepStatusPolling(status) { + return ( + !!(status && status.running) || + resolveSeqUiActive(status) || + !!(status && status.bpm_simulated) + ); + } + + function updateHitTypeDisplay(hitType, confidence) { + const node = el("audio-hit-type-value"); + if (!node) return; + const label = String(hitType || "unknown").toLowerCase(); + const conf = Number.isFinite(confidence) ? ` (${confidence.toFixed(2)})` : ""; + node.textContent = `${label}${conf}`; + } + + /** @param {Record} status */ + function updateBarPhaseDisplay(status) { + const readout = String((status && status.bar_phase_readout) || "").trim(); + const phaseConf = Number((status && status.phase_confidence) || 0); + const downbeat = !!(status && status.is_downbeat); + const simulated = !!(status && status.bpm_simulated); + const showPhase = !!(status && status.running) || simulated; + let text = readout || "--"; + if (readout && Number.isFinite(phaseConf) && phaseConf > 0) { + text = `${text} (${Math.round(phaseConf * 100)}%)`; + } + for (const id of ["audio-bar-phase-value", "audio-top-bar-phase"]) { + const node = el(id); + if (!node) continue; + node.textContent = showPhase ? text : ""; + node.classList.toggle("is-downbeat", downbeat && !!readout && showPhase); + } + } + + function setTopBpmVisible(on) { + const top = el("audio-top-indicator"); + if (!top) return; + top.classList.toggle("audio-running", !!on); + } + + function closeBeatEvents() { + if (beatEventsReconnectTimer != null) { + clearTimeout(beatEventsReconnectTimer); + beatEventsReconnectTimer = null; + } + if (beatEventSource) { + beatEventSource.close(); + beatEventSource = null; + } + } + + function scheduleBeatEventsReconnect() { + if (beatEventsReconnectTimer != null) return; + beatEventsReconnectTimer = setTimeout(() => { + beatEventsReconnectTimer = null; + void fetchAudioStatusOnce() + .then((status) => { + applyAudioStatus(status); + if (shouldKeepStatusPolling(status)) ensureBeatEvents(); + }) + .catch((e) => { + console.warn("audio status reconnect fetch failed", e); + }); + }, 2000); + } + + function ensureBeatEvents() { + if (beatEventSource) return; + const es = new EventSource("/api/audio/events"); + beatEventSource = es; + es.onmessage = (ev) => { + try { + const data = JSON.parse(String(ev.data || "")); + if (data && data.status) applyAudioStatus(data.status); + } catch (e) { + console.warn("audio beat event parse failed", e); + } + }; + es.onerror = () => { + closeBeatEvents(); + scheduleBeatEventsReconnect(); + }; + } + + function setResetDetectorEnabled(on) { + const btn = el("audio-reset-btn"); + if (btn) btn.disabled = !on; + } + + async function resetAudioTracking() { + try { + const res = await fetch("/api/audio/reset", { + method: "POST", + headers: { Accept: "application/json" }, + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + console.warn("audio reset failed", data.error || res.status); + return; + } + await pollStatus(); + } catch (e) { + console.warn("audio reset failed", e); + } + } + + function beatSyncButtonTitle(zoneSeqActive) { + if (!audioDetectorRunning) return "Start beat detection"; + if (zoneSeqActive) return "Sync step to music (S)"; + return "Beat detection running"; + } + + function updateSequenceSyncControls(zoneSeqActive) { + const disabled = audioDetectorRunning && !zoneSeqActive; + const title = beatSyncButtonTitle(zoneSeqActive); + for (const id of ["audio-top-beat-sync", "audio-modal-beat-sync"]) { + const btn = el(id); + if (!btn) continue; + btn.disabled = disabled; + btn.title = title; + } + } + + async function handleTopBpmButtonClick() { + if (!audioDetectorRunning) { + try { + await startAudio(); + } catch (e) { + console.error("audio start failed", e); + alert("Failed to start audio input. Check mic permissions."); + } 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); + await syncSequenceBeatPhase("step"); } 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); + console.warn("sequence beat sync failed", e); } } - 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 }), + async function syncSequenceBeatPhase(mode) { + const res = await fetch("/sequences/sync-phase", { + method: "POST", + headers: { "Content-Type": "application/json", Accept: "application/json" }, + body: JSON.stringify({ mode: mode || "step" }), }); if (!res.ok) { - simStatus.textContent = 'The controller refused that BPM.'; + const data = await res.json().catch(() => ({})); + throw new Error(data.error || `Sync failed (${res.status})`); + } + await pollStatus(); + } + + function isTypingTarget(target) { + if (!target || typeof target !== "object") return false; + const tag = String(target.tagName || "").toLowerCase(); + return tag === "input" || tag === "textarea" || tag === "select" || target.isContentEditable; + } + + function flashBeatSyncButton(btn, simulated = false) { + if (!btn) return; + btn.classList.add(simulated ? "flash-simulated" : "flash"); + setTimeout(() => btn.classList.remove(simulated ? "flash-simulated" : "flash"), 90); + } + + function flashBeat(simulated = false) { + const top = el("audio-top-indicator"); + const topSync = el("audio-top-beat-sync"); + if ( + topSync && + top && + (top.classList.contains("audio-running") || simulated) + ) { + flashBeatSyncButton(topSync, simulated); + } + const modalSync = el("audio-modal-beat-sync"); + if (modalSync && (audioDetectorRunning || simulated)) { + flashBeatSyncButton(modalSync, simulated); + } + } + + function gainPercentToDb(pct) { + const gain = Math.max(0.001, pct / 100); + return 20 * Math.log10(gain); + } + + function formatGainReadout(pct) { + const db = gainPercentToDb(pct); + const dbText = db >= 0 ? `+${db.toFixed(2)}` : db.toFixed(2); + return `${pct}% (${dbText} dB)`; + } + + function updateInputLevelDisplay(level) { + const pct = Number.isFinite(level) ? Math.round(Math.min(1, Math.max(0, level)) * 100) : 0; + const bar = el("audio-input-level-bar"); + const meter = el("audio-modal")?.querySelector(".audio-input-level-meter"); + if (bar) bar.style.width = `${pct}%`; + if (meter) meter.setAttribute("aria-valuenow", String(pct)); + } + + function clearBeatPhaseTimers() { + pendingBeatPhaseTimers.forEach((t) => clearTimeout(t)); + pendingBeatPhaseTimers.clear(); + } + + function getBeatPhaseDelayMs() { + return Math.min(500, Math.max(0, cachedBeatPhaseMs)); + } + + function getInputVolumePercent() { + const inp = el("audio-input-volume"); + if (!inp) return 100; + const n = parseInt(String(inp.value).trim(), 10); + if (!Number.isFinite(n)) return 100; + return Math.min(200, Math.max(0, n)); + } + + function updateInputVolumeReadout() { + const readout = el("audio-input-volume-readout"); + const slider = el("audio-input-volume"); + const pct = getInputVolumePercent(); + if (readout) readout.textContent = formatGainReadout(pct); + if (slider) { + slider.style.setProperty("--audio-volume-pct", `${(pct / 200) * 100}%`); + } + } + + const SIMULATED_BPM_MIN = 60; + const SIMULATED_BPM_MAX = 200; + + function clampSimulatedBpm(n) { + if (!Number.isFinite(n)) return 120; + return Math.min(SIMULATED_BPM_MAX, Math.max(SIMULATED_BPM_MIN, Math.round(n))); + } + + function clampLiveBpm(n) { + if (!Number.isFinite(n)) return null; + return Math.min(SIMULATED_BPM_MAX, Math.max(SIMULATED_BPM_MIN, n)); + } + + function getSimulatedBpmPercent() { + const inp = el("audio-simulated-bpm"); + if (!inp) return 120; + return clampSimulatedBpm(parseInt(String(inp.value).trim(), 10)); + } + + async function persistSimulatedBpm() { + const bpm = getSimulatedBpmPercent(); + try { + await fetch("/settings", { + method: "PUT", + headers: { "Content-Type": "application/json", Accept: "application/json" }, + body: JSON.stringify({ audio_simulated_bpm: bpm }), + }); + } catch (e) { + console.warn("simulated bpm save failed", e); + } + } + + async function persistInputVolume() { + const vol = getInputVolumePercent(); + updateInputVolumeReadout(); + try { + await fetch("/settings", { + method: "PUT", + headers: { "Content-Type": "application/json", Accept: "application/json" }, + body: JSON.stringify({ audio_input_volume: vol }), + }); + } catch (e) { + console.warn("input volume save failed", e); + } + } + + function scheduleBeatPhaseFire(seq, delayMs, simulated = false) { + let tid = null; + const run = () => { + if (tid != null) pendingBeatPhaseTimers.delete(tid); + flashBeat(simulated); + try { + window.dispatchEvent( + new CustomEvent("ledControllerAudioBeat", { detail: { beatSeq: seq } }), + ); + } catch (e) { + /* ignore */ + } + }; + if (delayMs <= 0) { + run(); return; } - setSimRunning(false); - setSimRunning(true); - fetch('/settings/settings', { - method: 'PUT', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ audio_simulated_bpm: simBpm }), - }).catch(() => {}); + tid = setTimeout(run, delayMs); + pendingBeatPhaseTimers.add(tid); } - async function stopSim() { - await fetch('/test/beats/stop', { method: 'POST' }); - setSimRunning(false); - } - - function tap() { - fetch('/tap', { method: 'POST' }).catch(() => {}); - } - - async function loadSimBpm() { + /** Stop detector and polling; does not clear “resume on load” prefs (used before restart). */ + async function stopAudioOnly() { + audioDetectorRunning = false; + setResetDetectorEnabled(false); + clearBeatPhaseTimers(); + lastBeatSeq = 0; + lastSimulatedBeatTick = 0; + prevZoneSequencePlaybackActive = false; + headerBeatStickyIdleAfterSeq = false; + updateBeatReadoutDisplays({}); + updateInputLevelDisplay(0); + setTopBpmVisible(true); + updateBpmDisplay(getSimulatedBpmPercent(), true); try { - const s = await (await fetch('/settings', { cache: 'no-store' })).json(); - if (s.audio_simulated_bpm != null) simInput.value = clampSim(s.audio_simulated_bpm); + await fetch("/api/audio/stop", { method: "POST" }); } catch (e) { - /* keep the default */ + console.warn("audio stop failed", e); + } + ensureBeatEvents(); + await pollStatus(); + } + + /** User-initiated stop (run intent cleared on server). */ + async function stopAudio() { + await stopAudioOnly(); + } + + async function fetchAudioStatusOnce() { + const res = await fetch("/api/audio/status", { cache: "no-store" }); + const data = await res.json(); + return data?.status || {}; + } + + async function pollStatus() { + try { + const status = await fetchAudioStatusOnce(); + applyAudioStatus(status); + } catch (e) { + console.warn("audio status fetch failed", e); } } - // --- open and close -------------------------------------------------------------------- - function open() { - modal.classList.add('active'); - simStop.disabled = true; - loadSimBpm(); - openEvents(); - clearTimeout(pollTimer); - poll(); + /** @param {Record} status */ + function applyAudioStatus(status) { + try { + if (status.error && String(status.error).trim()) { + const node = el("audio-hit-type-value"); + if (node) { + node.textContent = String(status.error).trim().slice(0, 120); + } + updateBeatReadoutDisplays({}); + audioDetectorRunning = !!status.running; + updateInputLevelDisplay(0); + updateTopIndicatorFromStatus(status); + setResetDetectorEnabled(!!status.running); + if (!shouldKeepStatusPolling(status)) closeBeatEvents(); + return; + } + audioDetectorRunning = !!status.running; + const zoneSeqActive = sequencePlaybackActiveFromStatus(status); + const seqUiActive = resolveSeqUiActive(status); + const bpmSimulated = !!status.bpm_simulated; + if (sequenceBeatUiActiveFromStatus(status)) { + clientSequenceUiActive = false; + } + updateTopIndicatorFromStatus(status); + setResetDetectorEnabled(!!status.running); + updateSequenceSyncControls(zoneSeqActive || clientSequenceUiActive); + const displayBpm = + bpmSimulated && status.audio_simulated_bpm != null + ? clampSimulatedBpm(Number(status.audio_simulated_bpm)) + : status.bpm != null + ? clampLiveBpm(Number(status.bpm)) + : null; + updateBpmDisplay( + Number.isFinite(displayBpm) ? displayBpm : null, + bpmSimulated, + ); + updateHitTypeDisplay(status.beat_type, Number(status.beat_type_confidence)); + updateBarPhaseDisplay(status); + updateInputLevelDisplay( + status.running ? Number(status.input_level) : 0, + ); + applyServerAudioUiFields(status); + if (typeof window.setSequenceSwitchSimulatedMode === "function") { + window.setSequenceSwitchSimulatedMode(bpmSimulated); + } + if (typeof window.applySequenceSwitchWaitFromServer === "function") { + window.applySequenceSwitchWaitFromServer(status.sequence_switch_wait); + } + /* + * `status.beat_seq` is cumulative since Audio Start — used only for flash / sticky idle + * after sequence ends. Preset and sequence loop counts come from `manual_beat_stride` / + * `sequence` on each poll. + */ + const beatSeq = Number(status.beat_seq || 0); + const simTick = Number(status.simulated_beat_tick || 0); + const endedSeq = prevZoneSequencePlaybackActive && !zoneSeqActive; + const startedSeq = !prevZoneSequencePlaybackActive && zoneSeqActive; + prevZoneSequencePlaybackActive = zoneSeqActive; + if (startedSeq) { + headerBeatStickyIdleAfterSeq = false; + stickySequenceBeatReadout = ""; + if (bpmSimulated) { + lastSimulatedBeatTick = Math.max(0, simTick - 1); + } + } + if (zoneSeqActive) { + const liveReadout = String((status.beat_readout || "") || "").trim() + || String((status.sequence && status.sequence.beat_readout) || "").trim(); + if (liveReadout) { + stickySequenceBeatReadout = liveReadout; + } + } + if (endedSeq) { + clientSequenceUiActive = false; + headerBeatStickyIdleAfterSeq = true; + clearBeatPhaseTimers(); + lastBeatSeq = beatSeq; + lastSimulatedBeatTick = simTick; + if (!stickySequenceBeatReadout) { + const tail = String((status.beat_readout || "") || "").trim(); + if (tail) stickySequenceBeatReadout = tail; + } + } + if (bpmSimulated && simTick > lastSimulatedBeatTick) { + lastSimulatedBeatTick = simTick; + scheduleBeatPhaseFire(simTick, getBeatPhaseDelayMs(), true); + } else if (!zoneSeqActive && headerBeatStickyIdleAfterSeq) { + if (beatSeq > lastBeatSeq) { + lastBeatSeq = beatSeq; + scheduleBeatPhaseFire(beatSeq, getBeatPhaseDelayMs(), false); + headerBeatStickyIdleAfterSeq = false; + } + } else if (!bpmSimulated && beatSeq > lastBeatSeq) { + lastBeatSeq = beatSeq; + scheduleBeatPhaseFire(beatSeq, getBeatPhaseDelayMs(), false); + } + updateBeatReadoutDisplays(status); + if (shouldKeepStatusPolling(status)) { + ensureBeatEvents(); + } else { + closeBeatEvents(); + } + } catch (e) { + console.warn("audio status apply failed", e); + } } - 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; + /** Ignore server device sync briefly after the user picks from the dropdown. */ + let deviceSelectLockUntil = 0; + /** Suppress change handler while rebuilding or programmatically setting the select. */ + let suppressDeviceSelectEvents = false; + /** Last explicit UI choice (dropdown); not overwritten by server poll. */ + let uiDeviceSelectId = ""; + + function lockDeviceSelect(ms = 10000) { + deviceSelectLockUntil = Date.now() + ms; } - 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(); + function preferredSavedDeviceId() { + return cachedAudioRun.device_select ? String(cachedAudioRun.device_select) : ""; + } + + function optionIdForSavedDevice(select, savedId) { + const saved = savedId == null ? "" : String(savedId); + if (!saved || !select) return ""; + if (selectHasDeviceOptionId(select, saved)) return saved; + if (!/^-?\d+$/.test(saved)) return ""; + for (const opt of select.options) { + if (String(opt.dataset.sdIndex ?? "") === saved) return opt.value; + } + return ""; + } + + function restoreDeviceSelectAfterRefresh(select, defaultId, restoreId = "") { + const picked = restoreId || getSelectedDeviceId(); + if (picked && selectHasDeviceOptionId(select, picked)) { + setSelectedDeviceId(picked); + return; + } + const saved = preferredSavedDeviceId(); + const savedId = optionIdForSavedDevice(select, saved) || saved; + if (savedId && selectHasDeviceOptionId(select, savedId)) { + setSelectedDeviceId(savedId); + return; + } + if (defaultId && selectHasDeviceOptionId(select, defaultId)) { + setSelectedDeviceId(defaultId); + return; + } + setSelectedDeviceId(""); + } + + function getSelectedDeviceId() { + return String(el("audio-device-select")?.value ?? ""); + } + + function selectHasDeviceOptionId(select, deviceId) { + const id = deviceId == null ? "" : String(deviceId); + return [...select.options].some((opt) => opt.value === id); + } + + function audioRunPreferredDeviceId(run) { + return run.device_select ? String(run.device_select) : ""; + } + + function setSelectedDeviceId(deviceId, { force = false } = {}) { + const id = deviceId == null ? "" : String(deviceId); + const select = el("audio-device-select"); + if (!select) return false; + if (id !== "" && !selectHasDeviceOptionId(select, id)) { + if (!force) return false; + } + suppressDeviceSelectEvents = true; + try { + select.value = id; + uiDeviceSelectId = id; + } finally { + suppressDeviceSelectEvents = false; + } + return true; + } + + function readDeviceForm() { + return { override: "", selected: getSelectedDeviceId() }; + } + + async function persistDeviceSelection(deviceId) { + const selected = deviceId != null ? String(deviceId) : getSelectedDeviceId(); + uiDeviceSelectId = selected; + cachedAudioRun.device_select = selected; + try { + const res = await fetch("/api/audio/device", { + method: "PUT", + headers: { "Content-Type": "application/json", Accept: "application/json" }, + body: JSON.stringify({ device_select: selected, device_override: "" }), + }); + const data = await res.json().catch(() => ({})); + if (data?.audio_run && typeof data.audio_run === "object") { + const saved = data.audio_run.device_select + ? String(data.audio_run.device_select) + : ""; + if (saved === selected) { + cachedAudioRun.device_select = saved; + } + } + } catch (e) { + console.warn("device selection save failed", e); + } + } + + async function startAudio(deviceId) { + const selected = + deviceId != null && deviceId !== undefined + ? String(deviceId) + : uiDeviceSelectId || getSelectedDeviceId(); + lockDeviceSelect(); + uiDeviceSelectId = selected; + cachedAudioRun.device_select = selected; + await stopAudioOnly(); + await persistDeviceSelection(selected); + const rawDevice = selected; + const numeric = rawDevice !== "" && /^-?\d+$/.test(rawDevice) ? Number(rawDevice) : rawDevice; + const body = { + device: rawDevice === "" ? null : numeric, + device_override: "", + device_select: selected, + }; + const res = await fetch("/api/audio/start", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + throw new Error(data.error || "Failed to start audio detector"); + } + cachedAudioRun.device_select = selected; + setSelectedDeviceId(selected); + updateBpmDisplay(null); + updateHitTypeDisplay("unknown", NaN); + ensureBeatEvents(); + await pollStatus(); + } + + async function refreshDevices() { + const select = el("audio-device-select"); + if (!select) return; + const res = await fetch("/api/audio/devices"); + const data = await res.json(); + // Re-read after fetch so a pick during the request is not overwritten by a stale value. + const restoreId = getSelectedDeviceId(); + const inputs = Array.isArray(data?.devices) ? data.devices.slice() : []; + select.innerHTML = ""; + const defaultOpt = document.createElement("option"); + defaultOpt.value = ""; + defaultOpt.textContent = "System default input"; + select.appendChild(defaultOpt); + let defaultId = ""; + inputs.forEach((d, idx) => { + const opt = document.createElement("option"); + opt.value = String(d.id); + const text = d.display_name || d.name || `Input ${idx + 1}`; + opt.textContent = text; + const title = d.label || d.name || ""; + if (title && title !== text) opt.title = title; + if (d.sounddevice_index != null && d.sounddevice_index !== "") { + opt.dataset.sdIndex = String(d.sounddevice_index); + } + select.appendChild(opt); + if (d.is_default) defaultId = String(d.id); + }); + suppressDeviceSelectEvents = true; + try { + restoreDeviceSelectAfterRefresh(select, defaultId, restoreId); + } finally { + suppressDeviceSelectEvents = false; + } + } + + function bind() { + const modal = el("audio-modal"); + const openBtn = el("audio-btn"); + const closeBtn = el("audio-close-btn"); + const startBtn = el("audio-start-btn"); + const stopBtn = el("audio-stop-btn"); + const resetBtn = el("audio-reset-btn"); + const refreshBtn = el("audio-refresh-btn"); + if (!modal || !openBtn) return; + + openBtn.addEventListener("click", async () => { + modal.classList.add("active"); + try { + await refreshDevices(); + } catch (e) { + console.warn("audio device refresh failed", e); + } + await loadServerAudioUiFields(); + setResetDetectorEnabled(audioDetectorRunning); + }); + if (closeBtn) { + closeBtn.addEventListener("click", () => { + modal.classList.remove("active"); + }); + } + if (startBtn) { + startBtn.addEventListener("click", async () => { + const picked = getSelectedDeviceId(); + try { + await startAudio(picked); + } catch (e) { + console.error("audio start failed", e); + alert("Failed to start audio input. Check mic permissions."); + } + }); + } + if (stopBtn) { + stopBtn.addEventListener("click", async () => { + await stopAudio(); + }); + } + if (resetBtn) { + resetBtn.addEventListener("click", () => resetAudioTracking()); + } + if (refreshBtn) { + refreshBtn.addEventListener("click", async () => { + try { + await refreshDevices(); + } catch (e) { + console.error("refresh devices failed", e); + } + }); + } + const deviceSelect = el("audio-device-select"); + if (deviceSelect) { + deviceSelect.addEventListener("change", async () => { + if (suppressDeviceSelectEvents) return; + const picked = getSelectedDeviceId(); + uiDeviceSelectId = picked; + lockDeviceSelect(); + cachedAudioRun.device_select = picked; + await persistDeviceSelection(picked); + }); + } + const volInp = el("audio-input-volume"); + if (volInp) { + volInp.addEventListener("input", () => { + updateInputVolumeReadout(); + void persistInputVolume(); + }); + volInp.addEventListener("change", () => { + updateInputVolumeReadout(); + void persistInputVolume(); + }); + updateInputVolumeReadout(); + } + const simBpmInp = el("audio-simulated-bpm"); + if (simBpmInp) { + const onSimBpmChange = () => { + void persistSimulatedBpm(); + if (!audioDetectorRunning) { + updateBpmDisplay(getSimulatedBpmPercent(), true); + } + }; + simBpmInp.addEventListener("input", onSimBpmChange); + simBpmInp.addEventListener("change", onSimBpmChange); + } + + for (const id of ["audio-top-beat-sync", "audio-modal-beat-sync"]) { + const btn = el(id); + if (btn) { + btn.addEventListener("click", () => { + void handleTopBpmButtonClick(); + }); + } + } + + document.addEventListener("keydown", (ev) => { + if (ev.defaultPrevented || ev.repeat || isTypingTarget(ev.target)) return; + const k = String(ev.key || "").toLowerCase(); + if (k !== "s") return; + ev.preventDefault(); + const mode = ev.shiftKey ? "pass" : "step"; + void syncSequenceBeatPhase(mode).catch((e) => console.warn("sequence beat sync failed", e)); + }); + } + + async function resumeBeatEventsIfNeeded() { + try { + const status = await fetchAudioStatusOnce(); + audioDetectorRunning = !!status.running; + updateTopIndicatorFromStatus(status); + if (shouldKeepStatusPolling(status)) { + lastBeatSeq = Number(status.beat_seq || 0); + lastSimulatedBeatTick = Number(status.simulated_beat_tick || 0); + prevZoneSequencePlaybackActive = sequencePlaybackActiveFromStatus(status); + applyAudioStatus(status); + ensureBeatEvents(); + } else { + updateSequenceSyncControls( + sequencePlaybackActiveFromStatus(status) || clientSequenceUiActive, + ); + } + } catch (e) { + console.warn("audio resume status check failed", e); + } + } + + /** Apply server-owned audio UI fields from status (volume; device dropdown is user-owned). */ + function applyServerAudioUiFields(status) { + if (!status || typeof status !== "object") return; + const run = status.audio_run; + if (run && typeof run === "object") { + cachedAudioRun = { + device: run.device ?? null, + device_override: run.device_override != null ? String(run.device_override) : "", + device_select: run.device_select ? String(run.device_select) : "", + }; + } + if (status.beat_phase_ms != null) { + const ms = parseInt(String(status.beat_phase_ms), 10); + if (Number.isFinite(ms)) { + cachedBeatPhaseMs = Math.min(500, Math.max(0, ms)); + } + } + const volInp = el("audio-input-volume"); + if ( + volInp && + status.input_volume != null && + document.activeElement !== volInp + ) { + const vol = parseInt(String(status.input_volume), 10); + if (Number.isFinite(vol)) { + volInp.value = String(Math.min(200, Math.max(0, vol))); + updateInputVolumeReadout(); + } + } + const simBpmInp = el("audio-simulated-bpm"); + if ( + simBpmInp && + status.audio_simulated_bpm != null && + document.activeElement !== simBpmInp + ) { + const bpm = parseInt(String(status.audio_simulated_bpm), 10); + if (Number.isFinite(bpm)) { + simBpmInp.value = String(clampSimulatedBpm(bpm)); + } + } + } + + async function loadServerAudioUiFields() { + try { + const res = await fetch("/api/audio/status", { cache: "no-store" }); + const data = await res.json(); + const status = data?.status || {}; + applyServerAudioUiFields(status); + const select = el("audio-device-select"); + const saved = audioRunPreferredDeviceId(status.audio_run || {}); + if (select && saved && selectHasDeviceOptionId(select, saved)) { + uiDeviceSelectId = saved; + setSelectedDeviceId(saved); + } + updateInputLevelDisplay(status.running ? Number(status.input_level) : 0); + updateTopIndicatorFromStatus(status); + if (typeof window.setSequenceSwitchSimulatedMode === "function") { + window.setSequenceSwitchSimulatedMode(!!status.bpm_simulated); + } + if (!status.running) { + lastSimulatedBeatTick = Number(status.simulated_beat_tick || 0); + applyAudioStatus(status); + } + } catch (e) { + console.warn("audio status load failed", e); + } + } + + /** Called from sequences.js when server playback starts/stops. */ + window.ledControllerSequencePlaybackChanged = (active) => { + clientSequenceUiActive = !!active; + updateSequenceSyncControls(!!active); + if (active) { + setTopBpmVisible(true); + if (!audioDetectorRunning) { + updateBpmDisplay(getSimulatedBpmPercent(), true); + } + ensureBeatEvents(); + void pollStatus(); + return; + } + void pollStatus(); + }; + + document.addEventListener("DOMContentLoaded", async () => { + bind(); + await loadServerAudioUiFields(); + await resumeBeatEventsIfNeeded(); }); -}); +})(); diff --git a/web/static/bundle_io.js b/web/static/bundle_io.js new file mode 100644 index 0000000..1aca90b --- /dev/null +++ b/web/static/bundle_io.js @@ -0,0 +1,48 @@ +/** Download/upload JSON bundles for profile, preset, and sequence import/export. */ + +window.downloadJsonFile = function downloadJsonFile(filename, data) { + const text = typeof data === 'string' ? data : JSON.stringify(data, null, 2); + const blob = new Blob([text], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = filename || 'bundle.json'; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); +}; + +window.pickJsonFile = function pickJsonFile() { + return new Promise((resolve) => { + const input = document.createElement('input'); + input.type = 'file'; + input.accept = 'application/json,.json'; + input.style.display = 'none'; + document.body.appendChild(input); + input.addEventListener('change', () => { + const file = input.files && input.files[0]; + input.remove(); + if (!file) { + resolve(null); + return; + } + const reader = new FileReader(); + reader.onload = () => resolve(reader.result); + reader.onerror = () => resolve(null); + reader.readAsText(file); + }); + input.click(); + }); +}; + +window.parseJsonFileText = function parseJsonFileText(text) { + if (text == null || text === '') { + return null; + } + try { + return JSON.parse(text); + } catch (e) { + return null; + } +}; diff --git a/web/static/devices.js b/web/static/devices.js index f403060..3caaeaf 100644 --- a/web/static/devices.js +++ b/web/static/devices.js @@ -1,6 +1,5 @@ // 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; @@ -76,6 +75,13 @@ function normalizeDeviceMacKey(mac) { .replace(/[:-]/g, ''); } +function normalizeMacInput(raw) { + return String(raw || '') + .trim() + .toLowerCase() + .replace(/[:-]/g, ''); +} + function findPingResponse(responses, deviceId) { if (!responses || typeof responses !== 'object') return null; const want = normalizeDeviceMacKey(deviceId); @@ -283,61 +289,41 @@ function mergeTcpSnapshotPresence(ip, connected) { 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 espDrv = document.getElementById('edit-device-espnow-driver-wrap'); const wifiWrap = document.getElementById('edit-device-address-wifi-wrap'); + const drvWrap = document.getElementById('edit-device-wifi-driver-wrap'); if (esp) esp.hidden = isWifi; + if (espDrv) espDrv.hidden = isWifi; if (wifiWrap) wifiWrap.hidden = !isWifi; + if (drvWrap) drvWrap.hidden = !isWifi; +} + +function getDriverConfigPushFields(transport, registryName) { + const push = {}; + if (registryName) push.name = registryName; + if (transport === 'wifi') { + const nl = document.getElementById('edit-device-wifi-num-leds'); + const co = document.getElementById('edit-device-wifi-color-order'); + const ws = document.getElementById('edit-device-wifi-startup-mode'); + if (nl && nl.value !== '') { + const n = parseInt(nl.value, 10); + if (!Number.isNaN(n) && n >= 1) push.num_leds = n; + } + if (co && co.value) push.color_order = co.value; + if (ws && ws.value) push.startup_mode = ws.value; + } else { + const nl = document.getElementById('edit-device-espnow-num-leds'); + const co = document.getElementById('edit-device-espnow-color-order'); + if (nl && nl.value !== '') { + const n = parseInt(nl.value, 10); + if (!Number.isNaN(n) && n >= 1) push.num_leds = n; + } + if (co && co.value) push.color_order = co.value; + } + return push; } function getAddressForPayload(transport) { @@ -346,13 +332,56 @@ function getAddressForPayload(transport) { 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(); + const macEl = document.getElementById('edit-device-address-mac'); + const hex = normalizeMacInput(macEl && macEl.value); return hex || null; } +function collectDeviceEditPayload() { + 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; + const transport = (transportSel && transportSel.value) || 'espnow'; + const address = getAddressForPayload(transport); + const obr = document.getElementById('edit-device-output-brightness'); + let output_brightness = 255; + if (obr && obr.value !== '') { + const n = parseInt(obr.value, 10); + output_brightness = !Number.isNaN(n) ? Math.max(0, Math.min(255, n)) : 255; + } + const payload = { + name: nameInput ? nameInput.value.trim() : '', + type: (typeSel && typeSel.value) || 'led', + transport, + address, + output_brightness, + }; + if (transport === 'wifi') { + const dn = document.getElementById('edit-device-wifi-driver-name'); + const nl = document.getElementById('edit-device-wifi-num-leds'); + const co = document.getElementById('edit-device-wifi-color-order'); + const ws = document.getElementById('edit-device-wifi-startup-mode'); + if (dn && dn.value.trim()) payload.wifi_driver_display_name = dn.value.trim(); + if (nl && nl.value !== '') { + const n = parseInt(nl.value, 10); + if (!Number.isNaN(n) && n >= 1) payload.wifi_driver_num_leds = n; + } + if (co && co.value) payload.wifi_color_order = co.value; + if (ws && ws.value) payload.wifi_startup_mode = ws.value; + } else { + const nl = document.getElementById('edit-device-espnow-num-leds'); + const co = document.getElementById('edit-device-espnow-color-order'); + if (nl && nl.value !== '') { + const n = parseInt(nl.value, 10); + if (!Number.isNaN(n) && n >= 1) payload.num_leds = n; + } + if (co && co.value) payload.color_order = co.value; + } + return { devId, payload }; +} + async function loadDevicesModal() { const container = document.getElementById('devices-list-modal'); if (!container) return; @@ -371,6 +400,69 @@ async function loadDevicesModal() { } } +async function createDeviceFromModal() { + const nameEl = document.getElementById('devices-add-name'); + const trEl = document.getElementById('devices-add-transport'); + const macEl = document.getElementById('devices-add-mac'); + const addrEl = document.getElementById('devices-add-address'); + const statusEl = document.getElementById('devices-add-status'); + const btn = document.getElementById('devices-add-btn'); + const name = (nameEl && nameEl.value.trim()) || ''; + const transport = (trEl && trEl.value) || 'espnow'; + const mac = normalizeMacInput(macEl && macEl.value); + const address = (addrEl && addrEl.value.trim()) || ''; + + if (!name) { + if (statusEl) statusEl.textContent = 'Name is required'; + return; + } + if (mac.length !== 12) { + if (statusEl) statusEl.textContent = 'MAC must be 12 hex characters'; + return; + } + if (transport === 'wifi' && !address) { + if (statusEl) statusEl.textContent = 'Address is required for Wi-Fi devices'; + return; + } + + if (btn) { + btn.disabled = true; + btn.textContent = 'Adding…'; + } + if (statusEl) statusEl.textContent = 'Creating device…'; + try { + const payload = { + name, + transport, + type: 'led', + mac, + address: transport === 'wifi' ? address : mac, + }; + const res = await fetch('/devices', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify(payload), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + if (statusEl) statusEl.textContent = data.error || 'Create failed'; + return; + } + if (statusEl) statusEl.textContent = 'Device added'; + if (nameEl) nameEl.value = ''; + if (macEl) macEl.value = ''; + if (addrEl) addrEl.value = ''; + await loadDevicesModal(); + } catch (e) { + if (statusEl) statusEl.textContent = e.message || 'Create failed'; + } finally { + if (btn) { + btn.disabled = false; + btn.textContent = 'Add device'; + } + } +} + function renderDevicesList(devices) { const container = document.getElementById('devices-list-modal'); if (!container) return; @@ -379,7 +471,7 @@ function renderDevicesList(devices) { 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.'; + p.textContent = 'No devices yet.'; container.appendChild(p); return; } @@ -499,7 +591,7 @@ function openEditDeviceModal(devId, dev) { 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 macInput = document.getElementById('edit-device-address-mac'); const wifiInput = document.getElementById('edit-device-address-wifi'); if (!modal || !idInput) return; idInput.value = devId; @@ -509,46 +601,75 @@ function openEditDeviceModal(devId, dev) { const tr = (dev && dev.transport) || 'espnow'; if (transportSel) transportSel.value = tr; applyTransportVisibility(tr); - setAddressToBoxes(addressBoxes, tr === 'espnow' ? ((dev && dev.address) || '') : ''); + if (macInput) macInput.value = 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]) : ''; - }); + const eLeds = document.getElementById('edit-device-espnow-num-leds'); + const eCo = document.getElementById('edit-device-espnow-color-order'); + if (eLeds) { + eLeds.value = + tr === 'espnow' && dev && dev.num_leds != null && dev.num_leds !== '' + ? String(dev.num_leds) + : ''; + } + if (eCo) { + const co = (dev && dev.color_order) || 'rgb'; + eCo.value = ['rgb', 'rbg', 'grb', 'gbr', 'brg', 'bgr'].includes(String(co).toLowerCase()) + ? String(co).toLowerCase() + : 'rgb'; + } + const wName = document.getElementById('edit-device-wifi-driver-name'); + const wLeds = document.getElementById('edit-device-wifi-num-leds'); + const wCo = document.getElementById('edit-device-wifi-color-order'); + const wStart = document.getElementById('edit-device-wifi-startup-mode'); + if (wName) { + const savedDisp = + dev && Object.prototype.hasOwnProperty.call(dev, 'wifi_driver_display_name') + ? dev.wifi_driver_display_name + : undefined; + if (savedDisp != null && String(savedDisp).trim() !== '') { + wName.value = String(savedDisp).trim(); + } else { + wName.value = dev && dev.name ? String(dev.name) : ''; + } + } + if (wLeds) { + wLeds.value = + dev && dev.wifi_driver_num_leds != null && dev.wifi_driver_num_leds !== '' + ? String(dev.wifi_driver_num_leds) + : ''; + } + if (wCo) { + const co = (dev && dev.wifi_color_order) || 'rgb'; + wCo.value = ['rgb', 'rbg', 'grb', 'gbr', 'brg', 'bgr'].includes(String(co).toLowerCase()) + ? String(co).toLowerCase() + : 'rgb'; + } + if (wStart) { + const sm = (dev && dev.wifi_startup_mode) || 'default'; + wStart.value = ['default', 'last', 'off'].includes(String(sm).toLowerCase()) + ? String(sm).toLowerCase() + : 'default'; + } + const obr = document.getElementById('edit-device-output-brightness'); + const obv = document.getElementById('edit-device-output-brightness-value'); + if (obr) { + let bv = 255; + if (dev && dev.output_brightness != null && dev.output_brightness !== '') { + const n = parseInt(String(dev.output_brightness), 10); + if (!Number.isNaN(n)) bv = Math.max(0, Math.min(255, n)); + } + obr.value = String(bv); + if (obv) obv.textContent = String(bv); + } 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) { +async function updateDevice(devId, payload) { 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 || {}), - }), + body: JSON.stringify(payload), }); const data = await res.json().catch(() => ({})); if (res.ok) { @@ -564,6 +685,41 @@ async function updateDevice(devId, name, type, transport, address, settings) { } } +async function pushWifiDriverConfig(devId, fields) { + const push = {}; + if (fields.name != null && String(fields.name).trim()) push.name = String(fields.name).trim(); + if (fields.num_leds != null && fields.num_leds !== '') { + const n = parseInt(String(fields.num_leds), 10); + if (!Number.isNaN(n) && n >= 1) push.num_leds = n; + } + if (fields.color_order != null && String(fields.color_order).trim()) { + push.color_order = String(fields.color_order).trim().toLowerCase(); + } + if (fields.startup_mode != null && String(fields.startup_mode).trim()) { + const sm = String(fields.startup_mode).trim().toLowerCase(); + if (sm === 'default' || sm === 'last' || sm === 'off') push.startup_mode = sm; + } + if (Object.keys(push).length === 0) return { ok: true, skipped: true }; + try { + const res = await fetch(`/devices/${encodeURIComponent(devId)}/driver-config`, { + method: 'POST', + credentials: 'same-origin', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify(push), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + alert(data.error || 'Could not send settings to the driver (is it connected?)'); + return { ok: false }; + } + return { ok: true }; + } catch (e) { + console.error('pushWifiDriverConfig:', e); + alert('Could not send settings to the driver'); + return { ok: false }; + } +} + document.addEventListener('DOMContentLoaded', () => { window.addEventListener('deviceTcpStatus', (ev) => { const { ip, connected } = ev.detail || {}; @@ -588,7 +744,13 @@ document.addEventListener('DOMContentLoaded', () => { refreshDevicesListQuiet(); }); - makeHexAddressBoxes(document.getElementById('edit-device-address-boxes')); + const devOutBr = document.getElementById('edit-device-output-brightness'); + const devOutBrVal = document.getElementById('edit-device-output-brightness-value'); + if (devOutBr && devOutBrVal) { + devOutBr.addEventListener('input', () => { + devOutBrVal.textContent = devOutBr.value; + }); + } const transportEdit = document.getElementById('edit-device-transport'); if (transportEdit) { @@ -603,6 +765,9 @@ document.addEventListener('DOMContentLoaded', () => { const editForm = document.getElementById('edit-device-form'); const editCloseBtn = document.getElementById('edit-device-close-btn'); const editDeviceModal = document.getElementById('edit-device-modal'); + const addTransport = document.getElementById('devices-add-transport'); + const addAddress = document.getElementById('devices-add-address'); + const addBtn = document.getElementById('devices-add-btn'); if (devicesBtn && devicesModal) { devicesBtn.addEventListener('click', () => { @@ -610,6 +775,7 @@ document.addEventListener('DOMContentLoaded', () => { if (typeof window.getEspnowSocket === 'function') { window.getEspnowSocket(); } + applyEspnowPingAggregateToDots(); loadDevicesModal(); startDevicesModalLiveRefresh(); }); @@ -620,6 +786,17 @@ document.addEventListener('DOMContentLoaded', () => { }); } + if (addTransport && addAddress) { + const syncAddAddress = () => { + addAddress.hidden = addTransport.value !== 'wifi'; + }; + addTransport.addEventListener('change', syncAddAddress); + syncAddAddress(); + } + if (addBtn) { + addBtn.addEventListener('click', () => createDeviceFromModal()); + } + const devicesPingBtn = document.getElementById('devices-ping-btn'); if (devicesPingBtn) { devicesPingBtn.addEventListener('click', () => { @@ -648,26 +825,39 @@ document.addEventListener('DOMContentLoaded', () => { 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; + const { devId, payload } = collectDeviceEditPayload(); if (!devId) return; - const transport = (transportSel && transportSel.value) || 'espnow'; - const address = getAddressForPayload(transport); - const ok = await updateDevice( + const ok = await updateDevice(devId, payload); + if (!ok) return; + try { + const brRes = await fetch(`/devices/${encodeURIComponent(devId)}/brightness`, { + method: 'POST', + credentials: 'same-origin', + headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, + body: JSON.stringify({}), + }); + if (!brRes.ok && brRes.status !== 503) { + const brData = await brRes.json().catch(() => ({})); + console.warn('brightness push:', brData.error || brRes.status); + } + } catch (e) { + console.warn('brightness push failed', e); + } + const pushRes = await pushWifiDriverConfig( devId, - nameInput ? nameInput.value.trim() : '', - (typeSel && typeSel.value) || 'led', - transport, - address, - readDeviceSettings() + getDriverConfigPushFields(payload.transport || 'espnow', payload.name), ); - if (ok) editDeviceModal.classList.remove('active'); + if (!pushRes.ok) return; + await loadDevicesModal(); }); } if (editCloseBtn) { editCloseBtn.addEventListener('click', () => editDeviceModal && editDeviceModal.classList.remove('active')); } }); + +if (typeof window !== 'undefined') { + window.applyEspnowPingToDeviceRows = applyEspnowPingToDeviceRows; + window.runEspnowPing = runEspnowPing; + window.applyEspnowPingAggregateToDots = applyEspnowPingAggregateToDots; +} diff --git a/web/static/groups.js b/web/static/groups.js new file mode 100644 index 0000000..a2ab3a1 --- /dev/null +++ b/web/static/groups.js @@ -0,0 +1,542 @@ +// Device groups: members (MAC ids) + Wi‑Fi driver defaults; persisted via /groups. +// Without ``profile_id``, a group is shared across all profiles; with ``profile_id`` it is listed only for that profile. + +async function getCurrentProfileIdForGroups() { + try { + const res = await fetch('/profiles/current', { + headers: { Accept: 'application/json' }, + credentials: 'same-origin', + }); + if (!res.ok) return null; + const data = await res.json(); + const id = data && (data.id || (data.profile && data.profile.id)); + return id != null ? String(id) : null; + } catch { + return null; + } +} + +async function fetchGroupsMap() { + try { + const response = await fetch('/groups', { + headers: { Accept: 'application/json' }, + credentials: 'same-origin', + }); + if (!response.ok) return {}; + const data = await response.json(); + return data && typeof data === 'object' ? data : {}; + } catch (e) { + console.error('fetchGroupsMap:', e); + return {}; + } +} + +async function fetchDevicesMapForGroups() { + try { + const response = await fetch('/devices', { headers: { Accept: 'application/json' } }); + if (!response.ok) return {}; + const data = await response.json(); + return data && typeof data === 'object' ? data : {}; + } catch (e) { + console.error('fetchDevicesMapForGroups:', e); + return {}; + } +} + +function renderGroupDevicesEditor(containerEl, macRows, devicesMap) { + if (!containerEl) return; + const panel = + typeof window.prepareZoneDevicesPanel === 'function' + ? window.prepareZoneDevicesPanel(containerEl) + : null; + const listEl = panel ? panel.listEl : containerEl; + if (!panel) { + containerEl.innerHTML = ''; + } + const entries = Object.entries(devicesMap || {}).sort(([a], [b]) => a.localeCompare(b)); + + macRows.forEach((row, idx) => { + const div = document.createElement('div'); + div.className = 'zone-device-row profiles-row'; + const label = document.createElement('span'); + label.className = 'zone-device-row-label'; + const strong = document.createElement('strong'); + strong.textContent = row.label || row.mac || '—'; + label.appendChild(strong); + label.appendChild(document.createTextNode(' ')); + const sub = document.createElement('span'); + sub.className = 'muted-text'; + sub.textContent = row.mac || ''; + label.appendChild(sub); + + const rm = document.createElement('button'); + rm.type = 'button'; + rm.className = 'btn btn-danger btn-small'; + rm.textContent = 'Remove'; + rm.addEventListener('click', () => { + macRows.splice(idx, 1); + renderGroupDevicesEditor(containerEl, macRows, devicesMap); + }); + div.appendChild(label); + div.appendChild(rm); + listEl.appendChild(div); + }); + + const macsInRows = new Set(macRows.map((r) => r.mac).filter(Boolean)); + const addWrap = document.createElement('div'); + addWrap.className = 'zone-devices-add profiles-actions'; + const picker = + typeof window.createSearchableAddPicker === 'function' + ? window.createSearchableAddPicker({ + entries, + excludeIds: macsInRows, + labelFor: (mac, d) => { + const labelName = d && d.name ? String(d.name).trim() : ''; + return labelName ? `${labelName} — ${mac}` : mac; + }, + searchTextFor: (mac, d) => { + const labelName = d && d.name ? String(d.name).trim() : ''; + return `${labelName} ${mac}`; + }, + onPick: (mac, d) => { + if (!mac || !devicesMap[mac]) return; + const n = String((d.name || '').trim() || mac); + macRows.push({ mac, label: n }); + renderGroupDevicesEditor(containerEl, macRows, devicesMap); + }, + placeholder: 'Search devices to add…', + emptyMessage: 'No devices match your search.', + noItemsMessage: 'All devices are already in this group.', + }) + : null; + if (picker) { + addWrap.appendChild(picker); + } + if (panel) { + panel.addSlot.appendChild(addWrap); + } else { + containerEl.appendChild(addWrap); + } +} + +function collectGroupEditPayload() { + const idInput = document.getElementById('edit-group-id'); + const nameInput = document.getElementById('edit-group-name'); + const gid = idInput && idInput.value; + const rows = window.__editGroupDeviceRows || []; + const devices = rows.map((r) => r.mac).filter(Boolean); + const payload = { + name: nameInput ? nameInput.value.trim() : '', + devices, + }; + const dn = document.getElementById('edit-group-wifi-driver-name'); + const nl = document.getElementById('edit-group-wifi-num-leds'); + const co = document.getElementById('edit-group-wifi-color-order'); + const ws = document.getElementById('edit-group-wifi-startup-mode'); + if (dn || nl || co || ws) { + if (dn && dn.value.trim()) payload.wifi_driver_display_name = dn.value.trim(); + else if (dn) payload.wifi_driver_display_name = null; + if (nl && nl.value !== '') { + const n = parseInt(nl.value, 10); + if (!Number.isNaN(n) && n >= 1) payload.wifi_driver_num_leds = n; + else payload.wifi_driver_num_leds = null; + } else if (nl) payload.wifi_driver_num_leds = null; + if (co && co.value) payload.wifi_color_order = co.value; + if (ws && ws.value) payload.wifi_startup_mode = ws.value; + } + const gob = document.getElementById('edit-group-output-brightness'); + if (gob && gob.value !== '') { + const nb = parseInt(gob.value, 10); + if (!Number.isNaN(nb)) payload.output_brightness = Math.max(0, Math.min(255, nb)); + } + return { gid, payload }; +} + +function syncGroupShareCheckboxFromDoc(g) { + const cb = document.getElementById('edit-group-share-all-profiles'); + if (!cb) return; + const raw = g && (g.profile_id != null ? g.profile_id : g.profileId); + const scoped = raw != null && String(raw).trim() !== ''; + cb.checked = !scoped; +} + +function loadWifiFieldsFromGroup(g) { + const wName = document.getElementById('edit-group-wifi-driver-name'); + const wLeds = document.getElementById('edit-group-wifi-num-leds'); + const wCo = document.getElementById('edit-group-wifi-color-order'); + const wStart = document.getElementById('edit-group-wifi-startup-mode'); + if (wName) { + const v = g && Object.prototype.hasOwnProperty.call(g, 'wifi_driver_display_name') + ? g.wifi_driver_display_name + : null; + wName.value = v != null && String(v).trim() !== '' ? String(v).trim() : ''; + } + if (wLeds) { + const v = g && g.wifi_driver_num_leds; + wLeds.value = + v != null && v !== '' && String(v).trim() !== '' + ? String(v) + : ''; + } + if (wCo) { + const co = (g && g.wifi_color_order) || 'rgb'; + wCo.value = ['rgb', 'rbg', 'grb', 'gbr', 'brg', 'bgr'].includes(String(co).toLowerCase()) + ? String(co).toLowerCase() + : 'rgb'; + } + if (wStart) { + const sm = (g && g.wifi_startup_mode) || 'default'; + wStart.value = ['default', 'last', 'off'].includes(String(sm).toLowerCase()) + ? String(sm).toLowerCase() + : 'default'; + } + const gob = document.getElementById('edit-group-output-brightness'); + const gobv = document.getElementById('edit-group-output-brightness-value'); + if (gob) { + let bv = 255; + if (g && g.output_brightness != null && g.output_brightness !== '') { + const n = parseInt(String(g.output_brightness), 10); + if (!Number.isNaN(n)) bv = Math.max(0, Math.min(255, n)); + } + gob.value = String(bv); + if (gobv) gobv.textContent = String(bv); + } +} + +async function openEditGroupModal(groupId, groupDoc) { + const modal = document.getElementById('edit-group-modal'); + const idInput = document.getElementById('edit-group-id'); + const nameInput = document.getElementById('edit-group-name'); + const editor = document.getElementById('edit-group-devices-editor'); + + let g = groupDoc; + if (!g || typeof g !== 'object') { + try { + const response = await fetch(`/groups/${encodeURIComponent(groupId)}`, { + credentials: 'same-origin', + headers: { Accept: 'application/json' }, + }); + if (response.ok) g = await response.json(); + } catch (e) { + console.error(e); + } + } + g = g || {}; + + if (idInput) idInput.value = groupId; + if (nameInput) nameInput.value = g.name || ''; + + const dm = await fetchDevicesMapForGroups(); + const macs = Array.isArray(g.devices) ? g.devices : []; + window.__editGroupDeviceRows = macs.map((m) => { + const mac = String(m).trim().toLowerCase().replace(/:/g, '').replace(/-/g, ''); + const d = dm[mac]; + return { + mac, + label: d && d.name ? String(d.name).trim() : mac, + }; + }); + renderGroupDevicesEditor(editor, window.__editGroupDeviceRows, dm); + loadWifiFieldsFromGroup(g); + syncGroupShareCheckboxFromDoc(g); + if (modal) modal.classList.add('active'); +} + +async function loadGroupsModal() { + const container = document.getElementById('groups-list-modal'); + if (!container) return; + container.innerHTML = 'Loading...'; + try { + const data = await fetchGroupsMap(); + renderGroupsList(data || {}); + } catch (e) { + console.error('loadGroupsModal:', e); + container.innerHTML = 'Failed to load groups.'; + } +} + +function renderGroupsList(groups) { + const container = document.getElementById('groups-list-modal'); + if (!container) return; + container.innerHTML = ''; + const ids = Object.keys(groups).filter((k) => groups[k] && typeof groups[k] === 'object'); + if (ids.length === 0) { + const p = document.createElement('p'); + p.className = 'muted-text'; + p.textContent = 'No groups yet.'; + container.appendChild(p); + return; + } + ids.sort((a, b) => parseInt(a, 10) - parseInt(b, 10)); + ids.forEach((gid) => { + const g = groups[gid]; + const row = document.createElement('div'); + row.className = 'group-list-row'; + + const info = document.createElement('div'); + info.className = 'group-list-row-info'; + + const label = document.createElement('div'); + label.className = 'group-list-row-title'; + const devs = Array.isArray(g.devices) ? g.devices : []; + label.textContent = `${g.name || gid} (${devs.length} device${devs.length === 1 ? '' : 's'})`; + + const meta = document.createElement('div'); + meta.className = 'group-list-row-meta muted-text'; + const rawPid = g.profile_id != null ? g.profile_id : g.profileId; + const scoped = rawPid != null && String(rawPid).trim() !== ''; + meta.textContent = scoped ? `This profile only (${rawPid})` : 'Shared across profiles'; + + info.appendChild(label); + info.appendChild(meta); + + const actions = document.createElement('div'); + actions.className = 'group-list-row-actions'; + const editBtn = document.createElement('button'); + editBtn.className = 'btn btn-secondary btn-small'; + editBtn.textContent = 'Edit'; + editBtn.addEventListener('click', () => openEditGroupModal(gid, g)); + + const brightBtn = document.createElement('button'); + brightBtn.className = 'btn btn-secondary btn-small'; + brightBtn.type = 'button'; + brightBtn.textContent = 'Apply brightness'; + brightBtn.title = 'Push group output brightness to Wi‑Fi drivers in this group'; + brightBtn.addEventListener('click', async () => { + try { + const res = await fetch(`/groups/${encodeURIComponent(gid)}/brightness`, { + method: 'POST', + credentials: 'same-origin', + headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, + body: JSON.stringify({}), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + alert(data.error || 'Apply brightness failed'); + return; + } + } catch (err) { + console.error(err); + alert('Apply brightness failed'); + } + }); + + const applyBtn = document.createElement('button'); + applyBtn.className = 'btn btn-primary btn-small'; + applyBtn.type = 'button'; + applyBtn.textContent = 'Apply defaults to drivers'; + applyBtn.title = 'Push Wi‑Fi defaults to each connected driver in this group'; + applyBtn.addEventListener('click', async () => { + try { + const res = await fetch(`/groups/${encodeURIComponent(gid)}/driver-config`, { + method: 'POST', + credentials: 'same-origin', + headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, + body: JSON.stringify({}), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + alert(data.error || 'Apply failed'); + return; + } + } catch (err) { + console.error(err); + alert('Apply failed'); + } + }); + + const identifyBtn = document.createElement('button'); + identifyBtn.className = 'btn btn-secondary btn-small'; + identifyBtn.type = 'button'; + identifyBtn.textContent = 'Identify'; + identifyBtn.title = + 'Identify all devices in this group at once (red blink at 10 Hz)'; + identifyBtn.addEventListener('click', async () => { + await identifyGroupById(gid); + }); + + const delBtn = document.createElement('button'); + delBtn.className = 'btn btn-danger btn-small'; + delBtn.textContent = 'Delete'; + delBtn.addEventListener('click', async () => { + if (!confirm(`Delete group "${g.name || gid}"? Zones referencing it may need updating.`)) return; + try { + const res = await fetch(`/groups/${encodeURIComponent(gid)}`, { + method: 'DELETE', + credentials: 'same-origin', + }); + if (res.ok) await loadGroupsModal(); + else { + const data = await res.json().catch(() => ({})); + alert(data.error || 'Delete failed'); + } + } catch (err) { + console.error(err); + alert('Delete failed'); + } + }); + + actions.appendChild(editBtn); + actions.appendChild(brightBtn); + actions.appendChild(applyBtn); + actions.appendChild(identifyBtn); + actions.appendChild(delBtn); + row.appendChild(info); + row.appendChild(actions); + container.appendChild(row); + }); +} + +async function identifyGroupById(gid) { + if (!gid) return; + try { + const res = await fetch(`/groups/${encodeURIComponent(gid)}/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; + } + const errs = Array.isArray(data.errors) ? data.errors : []; + if (errs.some((e) => e && e.error)) { + console.warn('Group identify errors', errs); + } + } catch (e) { + console.error(e); + alert('Identify failed'); + } +} + +document.addEventListener('DOMContentLoaded', () => { + const groupsBtn = document.getElementById('groups-btn'); + const groupsModal = document.getElementById('groups-modal'); + const groupsCloseBtn = document.getElementById('groups-close-btn'); + const newNameInput = document.getElementById('new-group-name'); + const createBtn = document.getElementById('create-group-btn'); + const editForm = document.getElementById('edit-group-form'); + const editCloseBtn = document.getElementById('edit-group-close-btn'); + const editModal = document.getElementById('edit-group-modal'); + + if (groupsBtn && groupsModal) { + groupsBtn.addEventListener('click', () => { + groupsModal.classList.add('active'); + loadGroupsModal(); + }); + } + if (groupsCloseBtn && groupsModal) { + groupsCloseBtn.addEventListener('click', () => groupsModal.classList.remove('active')); + } + + const grpOutBr = document.getElementById('edit-group-output-brightness'); + const grpOutBrVal = document.getElementById('edit-group-output-brightness-value'); + if (grpOutBr && grpOutBrVal) { + grpOutBr.addEventListener('input', () => { + grpOutBrVal.textContent = grpOutBr.value; + }); + } + + const editIdentifyBtn = document.getElementById('edit-group-identify-btn'); + if (editIdentifyBtn) { + editIdentifyBtn.addEventListener('click', async () => { + const idInput = document.getElementById('edit-group-id'); + const gid = idInput && idInput.value; + if (!gid) return; + await identifyGroupById(gid); + }); + } + + const createHandler = async () => { + const name = newNameInput && newNameInput.value.trim(); + if (!name) return; + const profileOnly = document.getElementById('new-group-profile-only'); + try { + const res = await fetch('/groups', { + method: 'POST', + credentials: 'same-origin', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify({ + name, + profile_scoped: !!(profileOnly && profileOnly.checked), + }), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + alert(data.error || 'Create failed'); + return; + } + if (newNameInput) newNameInput.value = ''; + if (profileOnly) profileOnly.checked = false; + await loadGroupsModal(); + } catch (e) { + console.error(e); + alert('Create failed'); + } + }; + if (createBtn) createBtn.addEventListener('click', createHandler); + if (newNameInput) { + newNameInput.addEventListener('keypress', (ev) => { + if (ev.key === 'Enter') createHandler(); + }); + } + + if (editForm) { + editForm.addEventListener('submit', async (e) => { + e.preventDefault(); + const { gid, payload } = collectGroupEditPayload(); + if (!gid) return; + + const shareCb = document.getElementById('edit-group-share-all-profiles'); + if (shareCb && shareCb.checked) { + payload.profile_id = null; + } else { + const pid = await getCurrentProfileIdForGroups(); + payload.profile_id = pid || null; + } + + try { + const res = await fetch(`/groups/${encodeURIComponent(gid)}`, { + method: 'PUT', + credentials: 'same-origin', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify(payload), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + alert(data.error || 'Save failed'); + return; + } + try { + await fetch(`/groups/${encodeURIComponent(gid)}/brightness`, { + method: 'POST', + credentials: 'same-origin', + headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, + body: JSON.stringify({}), + }); + } catch (_) { + /* ignore push errors after save */ + } + await loadGroupsModal(); + } catch (err) { + console.error(err); + alert('Save failed'); + } + }); + } + if (editCloseBtn && editModal) { + editCloseBtn.addEventListener('click', () => editModal.classList.remove('active')); + } + + window.openDeviceGroupsModal = async () => { + const gm = document.getElementById('groups-modal'); + if (!gm) return; + gm.classList.add('active'); + try { + await loadGroupsModal(); + } catch (e) { + console.error('openDeviceGroupsModal', e); + } + }; +}); diff --git a/web/static/help.js b/web/static/help.js index 552c825..da7cf9d 100644 --- a/web/static/help.js +++ b/web/static/help.js @@ -7,9 +7,11 @@ document.addEventListener('DOMContentLoaded', () => { const mainMenuDropdown = document.getElementById('main-menu-dropdown'); if (helpBtn && helpModal) { - helpBtn.addEventListener('click', () => { + const openHelp = () => { helpModal.classList.add('active'); - }); + switchHelpTab('overview'); + }; + helpBtn.addEventListener('click', openHelp); } if (helpCloseBtn && helpModal) { @@ -18,10 +20,37 @@ document.addEventListener('DOMContentLoaded', () => { }); } + const helpTabButtons = document.querySelectorAll('[data-help-tab]'); + const helpTabPanels = document.querySelectorAll('[data-help-panel]'); + + function switchHelpTab(tabId) { + if (!tabId) tabId = 'overview'; + for (const btn of helpTabButtons) { + const on = btn.getAttribute('data-help-tab') === tabId; + btn.classList.toggle('active', on); + btn.setAttribute('aria-selected', on ? 'true' : 'false'); + } + for (const panel of helpTabPanels) { + const on = panel.getAttribute('data-help-panel') === tabId; + panel.classList.toggle('active', on); + panel.hidden = !on; + } + } + + for (const btn of helpTabButtons) { + btn.addEventListener('click', () => { + switchHelpTab(btn.getAttribute('data-help-tab')); + }); + } + // Mobile main menu: forward clicks to existing header buttons if (mainMenuBtn && mainMenuDropdown) { mainMenuBtn.addEventListener('click', () => { mainMenuDropdown.classList.toggle('open'); + const zonesMenuDropdown = document.getElementById('zones-menu-dropdown'); + const zonesMenuBtn = document.getElementById('zones-menu-btn'); + if (zonesMenuDropdown) zonesMenuDropdown.classList.remove('open'); + if (zonesMenuBtn) zonesMenuBtn.setAttribute('aria-expanded', 'false'); }); mainMenuDropdown.addEventListener('click', (event) => { @@ -136,38 +165,10 @@ document.addEventListener('DOMContentLoaded', () => { 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 = ` -

AP Status: Active

-

SSID: ${config.ssid || 'N/A'}

-

Channel: ${config.channel || 'Auto'}

-

IP Address: ${config.ip || 'N/A'}

- `; - } else { - statusEl.innerHTML = ` -

AP Status: Inactive

-

Access Point is not currently active

- `; - } - 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(); }); } @@ -251,45 +252,4 @@ document.addEventListener('DOMContentLoaded', () => { } }); } - 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'); - } - }); - } }); diff --git a/web/static/led_tool.js b/web/static/led_tool.js deleted file mode 100644 index c3b11b1..0000000 --- a/web/static/led_tool.js +++ /dev/null @@ -1,255 +0,0 @@ -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 = ''; - - 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); - } - }); -}); diff --git a/web/static/numpad.js b/web/static/numpad.js new file mode 100644 index 0000000..78868a7 --- /dev/null +++ b/web/static/numpad.js @@ -0,0 +1,117 @@ +/** + * Bluetooth / USB HID numpad shortcuts (browser focus required). + * + * Numpad1–9,0 → zone 1–10 (visible zone list order) + * NumpadEnter → sequence beat sync (step), same as S + * NumpadDecimal → sequence beat sync (pass), same as Shift+S + * NumpadMultiply → reset audio detector + * NumpadAdd → brightness +16 + * NumpadSubtract → brightness −16 + * NumpadDivide → stop zone sequence playback + */ +(() => { + const BRIGHTNESS_STEP = 16; + + function isTypingTarget(target) { + if (!target || typeof target !== "object") return false; + const tag = String(target.tagName || "").toLowerCase(); + return tag === "input" || tag === "textarea" || tag === "select" || target.isContentEditable; + } + + function zoneIdsInListOrder() { + return [...document.querySelectorAll("#zones-list .zone-button[data-zone-id]")] + .map((el) => el.getAttribute("data-zone-id")) + .filter((id) => id != null && id !== ""); + } + + async function selectZoneByListIndex(oneBased) { + const order = zoneIdsInListOrder(); + if (oneBased < 1 || oneBased > order.length) return; + const zoneId = order[oneBased - 1]; + if (window.tabsManager && typeof window.tabsManager.selectZone === "function") { + await window.tabsManager.selectZone(zoneId); + } else if (typeof selectZone === "function") { + await selectZone(zoneId); + } + } + + async function syncSequenceBeatPhase(mode) { + const res = await fetch("/sequences/sync-phase", { + method: "POST", + headers: { "Content-Type": "application/json", Accept: "application/json" }, + body: JSON.stringify({ mode: mode || "step" }), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + throw new Error(data.error || `Sync failed (${res.status})`); + } + } + + async function resetAudioTracking() { + const res = await fetch("/api/audio/reset", { + method: "POST", + headers: { Accept: "application/json" }, + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + throw new Error(data.error || `Reset failed (${res.status})`); + } + } + + function adjustZoneBrightness(delta) { + const zoneId = + (window.tabsManager && typeof window.tabsManager.getCurrentTabId === "function" + ? window.tabsManager.getCurrentTabId() + : null) || + (window.tabsManager && typeof window.tabsManager.getCurrentZoneId === "function" + ? window.tabsManager.getCurrentZoneId() + : null); + if (!zoneId) return; + const slider = + document.getElementById("header-brightness-slider") || + document.getElementById("menu-brightness-slider"); + if (!slider) return; + const cur = parseInt(slider.value, 10); + const base = Number.isFinite(cur) ? cur : 127; + const next = Math.max(0, Math.min(255, base + delta)); + if (String(slider.value) === String(next)) return; + slider.value = String(next); + slider.dispatchEvent(new Event("input", { bubbles: true })); + } + + async function stopSequencePlayback() { + if (typeof window.stopZoneSequencePlayback === "function") { + await window.stopZoneSequencePlayback(true); + } + } + + /** @type {Record void | Promise>} */ + const actions = { + NumpadEnter: () => syncSequenceBeatPhase("step"), + NumpadDecimal: () => syncSequenceBeatPhase("pass"), + NumpadMultiply: () => resetAudioTracking(), + NumpadAdd: () => adjustZoneBrightness(BRIGHTNESS_STEP), + NumpadSubtract: () => adjustZoneBrightness(-BRIGHTNESS_STEP), + NumpadDivide: () => stopSequencePlayback(), + Numpad1: () => selectZoneByListIndex(1), + Numpad2: () => selectZoneByListIndex(2), + Numpad3: () => selectZoneByListIndex(3), + Numpad4: () => selectZoneByListIndex(4), + Numpad5: () => selectZoneByListIndex(5), + Numpad6: () => selectZoneByListIndex(6), + Numpad7: () => selectZoneByListIndex(7), + Numpad8: () => selectZoneByListIndex(8), + Numpad9: () => selectZoneByListIndex(9), + Numpad0: () => selectZoneByListIndex(10), + }; + + document.addEventListener("keydown", (ev) => { + if (ev.defaultPrevented || ev.repeat || isTypingTarget(ev.target)) return; + const code = ev.code; + if (!code || !code.startsWith("Numpad")) return; + const action = actions[code]; + if (!action) return; + ev.preventDefault(); + Promise.resolve(action()).catch((e) => console.warn("numpad shortcut failed:", e)); + }); +})(); diff --git a/web/static/patterns.js b/web/static/patterns.js index 8fb95f9..9afa1c3 100644 --- a/web/static/patterns.js +++ b/web/static/patterns.js @@ -33,6 +33,33 @@ document.addEventListener('DOMContentLoaded', () => { return Number.isFinite(t) ? t : def; }; + const coercePresetAuto = (preset) => { + if (!preset || typeof preset !== 'object') { + return true; + } + const v = + preset.auto !== undefined && preset.auto !== null ? preset.auto : preset.a; + if (typeof v === 'boolean') { + return v; + } + if (v === 0 || v === '0') { + return false; + } + if (v === 1 || v === '1') { + return true; + } + if (typeof v === 'string') { + const l = v.trim().toLowerCase(); + if (['false', '0', 'no', 'off'].includes(l)) { + return false; + } + if (['true', '1', 'yes', 'on'].includes(l)) { + return true; + } + } + return true; + }; + const getCurrentProfileId = async () => { try { const response = await fetch('/profiles/current', { headers: { Accept: 'application/json' } }); @@ -71,24 +98,8 @@ document.addEventListener('DOMContentLoaded', () => { : []; }; - 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 postDriverSequence = (sequence, targetMacs, delayS, pushOptions) => + window.postDriverSequence(sequence, targetMacs, delayS, pushOptions); const nReadableStringFromMeta = (meta, key) => { if (!meta || typeof meta !== 'object') { @@ -257,10 +268,6 @@ document.addEventListener('DOMContentLoaded', () => { 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); @@ -397,13 +404,7 @@ document.addEventListener('DOMContentLoaded', () => { 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 { + if (!isFirmwareBuiltinPattern(patternName)) { const sendBtn = document.createElement('button'); sendBtn.className = 'btn btn-primary btn-small'; sendBtn.textContent = 'Send'; @@ -531,6 +532,7 @@ document.addEventListener('DOMContentLoaded', () => { const colors = Array.isArray(preset.colors) && preset.colors.length ? preset.colors : ['#FFFFFF']; + const presetAuto = coercePresetAuto(preset); wirePresets[presetId] = { pattern: preset.pattern || 'off', colors, @@ -538,13 +540,19 @@ document.addEventListener('DOMContentLoaded', () => { brightness: typeof preset.brightness === 'number' ? preset.brightness : (typeof preset.br === 'number' ? preset.br : 127), - auto: typeof preset.auto === 'boolean' ? preset.auto : true, + auto: presetAuto, + a: presetAuto, n1: coercePresetInt(preset.n1), n2: coercePresetInt(preset.n2), n3: coercePresetInt(preset.n3), n4: coercePresetInt(preset.n4), n5: coercePresetInt(preset.n5), - n6: coercePresetInt(preset.n6), + n6: (() => { + if (preset.mode !== undefined && preset.mode !== null && preset.mode !== '') { + return coercePresetInt(preset.mode); + } + return coercePresetInt(preset.n6); + })(), }; }); if (!Object.keys(wirePresets).length) { @@ -552,26 +560,28 @@ document.addEventListener('DOMContentLoaded', () => { 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 groupIds = + typeof window.zonesManager !== 'undefined' && + typeof window.zonesManager.effectiveGroupIdsForZonePreset === 'function' + ? window.zonesManager.effectiveGroupIdsForZonePreset(zoneData) + : Array.isArray(zoneData.group_ids) + ? zoneData.group_ids.map((g) => String(g).trim()).filter((g) => g.length > 0) + : []; 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 }); + if (groupIds.length) { + sequence[0].groups = groupIds; + sequence[1].groups = groupIds; } - await postDriverSequence(sequence, targetMacs, 0.05); + if (deviceNames.length > 0 && zonePresetIds.length > 0) { + const sel = { v: '1', select: zonePresetIds.slice() }; + if (groupIds.length) sel.groups = groupIds; + sequence.push(sel); + } + await postDriverSequence(sequence, [], 0.05, { groupIds }); } catch (error) { console.error('Send all patterns failed:', error); alert('Failed to send all patterns.'); diff --git a/web/static/presets.js b/web/static/presets.js index d4d5fb1..6e312eb 100644 --- a/web/static/presets.js +++ b/web/static/presets.js @@ -1,6 +1,28 @@ -// Sending presets and selects to drivers +// Shared WebSocket for ESPNow messages (presets + selects) +let espnowSocket = null; +let espnowSocketReady = false; +let espnowPendingMessages = []; let currentProfileIdCache = null; +function 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; +} + +/** Style variant for wire ``n6``; presets may store ``mode`` or legacy ``n6``. */ +function presetWireN6(preset, def = 0) { + if (!preset || typeof preset !== 'object') { + return def; + } + if (preset.mode !== undefined && preset.mode !== null && preset.mode !== '') { + return coercePresetInt(preset.mode, def); + } + return coercePresetInt(preset.n6, def); +} + const getCurrentProfileId = async () => { try { const res = await fetch('/profiles/current', { headers: { Accept: 'application/json' } }); @@ -26,6 +48,9 @@ const filterPresetsForCurrentProfile = async (presetsObj) => { }), ); }; +try { + window.filterPresetsForCurrentProfile = filterPresetsForCurrentProfile; +} catch (e) {} const getCurrentProfileData = async () => { try { @@ -66,13 +91,80 @@ const resolveColorsWithPaletteRefs = (colors, paletteRefs, paletteColors) => { }); }; -// The v2 controller has no /ws endpoint: ESP-NOW goes out through POST /presets/push, and the Wi-Fi -// device presence dots stay as the devices list shows them. Kept so callers need no change. -const getEspnowSocket = () => null; +const getEspnowSocket = () => { + if (espnowSocket && (espnowSocket.readyState === WebSocket.OPEN || espnowSocket.readyState === WebSocket.CONNECTING)) { + return espnowSocket; + } -const sendEspnowMessage = (obj) => postDriverSequence([obj], [], 0).catch((err) => { - console.error('Failed to send ESPNow message:', err); -}); + const wsScheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; + const wsUrl = `${wsScheme}//${window.location.host}/ws`; + espnowSocket = new WebSocket(wsUrl); + espnowSocketReady = false; + + espnowSocket.onopen = () => { + espnowSocketReady = true; + window.dispatchEvent(new CustomEvent('deviceTcpWsOpen')); + // Flush any queued messages + espnowPendingMessages.forEach((msg) => { + try { + espnowSocket.send(msg); + } catch (err) { + console.error('Failed to send queued ESPNow message:', err); + } + }); + espnowPendingMessages = []; + }; + + espnowSocket.onmessage = (event) => { + try { + const data = JSON.parse(event.data); + if (data && data.type === 'device_tcp' && typeof data.connected === 'boolean' && data.ip) { + window.dispatchEvent( + new CustomEvent('deviceTcpStatus', { detail: { ip: data.ip, connected: data.connected } }), + ); + return; + } + if (data && data.type === 'device_tcp_snapshot' && Array.isArray(data.connected_ips)) { + window.dispatchEvent( + new CustomEvent('deviceTcpSnapshot', { detail: { connectedIps: data.connected_ips } }), + ); + return; + } + if (data && data.error) { + console.error('ESP-NOW:', data.error); + alert('ESP-NOW send failed. ' + (data.error === 'ESP-NOW send failed' ? 'Check device WiFi/interface.' : data.error)); + } + } catch (_) { + // Ignore non-JSON or non-error messages + } + }; + + espnowSocket.onclose = () => { + espnowSocketReady = false; + espnowSocket = null; + }; + + espnowSocket.onerror = (err) => { + console.error('ESPNow WebSocket error:', err); + }; + + return espnowSocket; +}; + +const sendEspnowMessage = (obj) => { + const json = JSON.stringify(obj); + const ws = getEspnowSocket(); + if (espnowSocketReady && ws.readyState === WebSocket.OPEN) { + try { + ws.send(json); + } catch (err) { + console.error('Failed to send ESPNow message:', err); + } + } else { + // Queue until connection is open + espnowPendingMessages.push(json); + } +}; function tabDeviceNamesFromSection(section) { if (typeof window.parseTabDeviceNames === 'function') { @@ -84,11 +176,64 @@ function tabDeviceNamesFromSection(section) { : []; } -async function postDriverSequence(sequence, targetMacs, delayS) { +/** Group ids for preset broadcast targeting on a zone tab. */ +function zoneGroupIdsFromTabData(tabData) { + const zm = window.zonesManager; + if (zm && typeof zm.effectiveGroupIdsForZonePreset === 'function') { + return zm.effectiveGroupIdsForZonePreset(tabData || {}); + } + return Array.isArray(tabData && tabData.group_ids) + ? tabData.group_ids.map((g) => String(g).trim()).filter((g) => g.length > 0) + : []; +} + +/** Device names for ``presetId`` on the current zone tab (zone ``group_ids`` for presets, else tab devices). */ +async function deviceNamesForPresetOnCurrentZone(presetId) { + const section = document.querySelector('.presets-section[data-zone-id]'); + const fallback = tabDeviceNamesFromSection(section); + if (!section || !presetId) return fallback; + const zm = window.zonesManager; + if (!zm || typeof zm.resolveDeviceNamesForZonePreset !== 'function') return fallback; + const zoneId = section.dataset.zoneId; + try { + const res = await fetch(`/zones/${zoneId}`, { headers: { Accept: 'application/json' } }); + if (!res.ok) return fallback; + const zd = await res.json(); + const names = await zm.resolveDeviceNamesForZonePreset(zd, String(presetId)); + return names.length ? names : fallback; + } catch (_) { + return fallback; + } +} + +function formatPresetTargetGroupsLine(zoneDoc, groupsMap) { + const zm = window.zonesManager; + const gids = + zm && typeof zm.effectiveGroupIdsForZonePreset === 'function' + ? zm.effectiveGroupIdsForZonePreset(zoneDoc || {}) + : Array.isArray(zoneDoc && zoneDoc.group_ids) + ? zoneDoc.group_ids.map((x) => String(x).trim()).filter((x) => x.length > 0) + : []; + const parts = (gids || []) + .map((id) => { + const g = groupsMap && groupsMap[id]; + const gn = g && g.name ? String(g.name).trim() : ''; + return gn; + }) + .filter(Boolean); + return parts.length ? parts.join(', ') : ''; +} + +async function postDriverSequence(sequence, targetMacs, delayS, pushOptions) { const body = { sequence, - targets: Array.isArray(targetMacs) && targetMacs.length ? [...new Set(targetMacs)] : undefined, }; + if (pushOptions && pushOptions.unicast === true) { + body.unicast = true; + if (Array.isArray(targetMacs) && targetMacs.length) { + body.targets = [...new Set(targetMacs)]; + } + } if (delayS != null && delayS >= 0) { body.delay_s = delayS; } @@ -120,10 +265,22 @@ document.addEventListener('DOMContentLoaded', () => { const presetNewColorInput = document.getElementById('preset-new-color'); const presetBrightnessInput = document.getElementById('preset-brightness-input'); const presetDelayInput = document.getElementById('preset-delay-input'); + const presetDelayField = presetDelayInput ? presetDelayInput.closest('.preset-editor-field') : null; + const presetBackgroundInput = document.getElementById('preset-background-input'); + const presetBackgroundButton = document.getElementById('preset-background-btn'); + const presetManualModeInput = document.getElementById('preset-manual-mode-input'); + const presetManualModeLabel = document.getElementById('preset-manual-mode-label'); + const presetManualBeatNWrap = document.getElementById('preset-manual-beat-n-wrap'); + const presetManualBeatNInput = document.getElementById('preset-manual-beat-n-input'); const presetDefaultButton = document.getElementById('preset-default-btn'); const presetRemoveFromTabButton = document.getElementById('preset-remove-from-zone-btn'); const presetSaveButton = document.getElementById('preset-save-btn'); const presetAddFromPaletteButton = document.getElementById('preset-add-from-palette-btn'); + const presetBackgroundFromPaletteButton = document.getElementById('preset-background-from-palette-btn'); + const presetModeInput = document.getElementById('preset-mode-input'); + const presetModeGroup = document.getElementById('preset-mode-group'); + const presetReverseInput = document.getElementById('preset-reverse-input'); + const presetReverseGroup = document.getElementById('preset-reverse-group'); if (!presetsButton || !presetsModal || !presetsList || !presetSaveButton) { return; @@ -135,6 +292,8 @@ document.addEventListener('DOMContentLoaded', () => { let cachedPatterns = {}; let currentPresetColors = []; // Track colors for the current preset let currentPresetPaletteRefs = []; // Palette index refs per color (null for direct colors) + let currentBackgroundPaletteRef = null; + let bgPaletteResolveGen = 0; // Function to get max colors for current pattern const getMaxColors = () => { @@ -149,6 +308,151 @@ document.addEventListener('DOMContentLoaded', () => { return Infinity; // No limit if not specified }; + const resolvePatternConfig = (patternName) => { + const rawPatternName = String(patternName || '').trim(); + const normalizedPatternName = rawPatternName.endsWith('.py') + ? rawPatternName.slice(0, -3) + : rawPatternName; + let patternConfig = + (cachedPatterns && cachedPatterns[rawPatternName]) || + (cachedPatterns && cachedPatterns[normalizedPatternName]) || + null; + if (!patternConfig && cachedPatterns && typeof cachedPatterns === 'object') { + const lower = normalizedPatternName.toLowerCase(); + const matchedKey = Object.keys(cachedPatterns).find( + (k) => String(k).toLowerCase() === lower, + ); + if (matchedKey) { + patternConfig = cachedPatterns[matchedKey]; + } + } + if (patternConfig && typeof patternConfig === 'object' && patternConfig.data && typeof patternConfig.data === 'object') { + patternConfig = patternConfig.data; + } + if ( + patternConfig && + typeof patternConfig === 'object' && + patternConfig.parameter_mappings && + typeof patternConfig.parameter_mappings === 'object' + ) { + const { parameter_mappings: pm, data: _data, ...rest } = patternConfig; + patternConfig = { ...rest, ...pm }; + } + return patternConfig && typeof patternConfig === 'object' ? patternConfig : null; + }; + + /** From db/pattern.json; missing key means pattern allows manual / beat (backward compatible). */ + const patternSupportsManual = (patternName) => { + const cfg = resolvePatternConfig(patternName); + if (!cfg) { + return true; + } + return cfg.supports_manual !== false; + }; + + const getPatternModeOptions = (patternName) => { + const cfg = resolvePatternConfig(patternName); + if (!cfg || typeof cfg.mode !== 'object' || cfg.mode === null || Array.isArray(cfg.mode)) { + return null; + } + const entries = Object.entries(cfg.mode).filter( + ([, label]) => typeof label === 'string' && label.trim(), + ); + if (entries.length < 2) { + return null; + } + entries.sort((a, b) => parseInt(a[0], 10) - parseInt(b[0], 10)); + return entries; + }; + + const patternSupportsModes = (patternName) => getPatternModeOptions(patternName) !== null; + + const patternSupportsReverse = (patternName) => { + const cfg = resolvePatternConfig(patternName); + return !!(cfg && cfg.supports_reverse); + }; + + const setPresetReverseFieldVisible = (show) => { + if (!presetReverseGroup) { + return; + } + presetReverseGroup.hidden = !show; + presetReverseGroup.style.display = show ? '' : 'none'; + if (!show && presetReverseInput) { + presetReverseInput.checked = false; + } + }; + + const setPresetModeFieldVisible = (show) => { + if (!presetModeGroup) { + return; + } + presetModeGroup.hidden = !show; + presetModeGroup.style.display = show ? '' : 'none'; + if (!show && presetModeInput) { + presetModeInput.innerHTML = ''; + } + }; + + const presetStoredMode = (preset) => { + if (!preset || typeof preset !== 'object') { + return 0; + } + if (preset.mode !== undefined && preset.mode !== null && preset.mode !== '') { + const m = parseInt(String(preset.mode), 10); + return Number.isFinite(m) ? m : 0; + } + const n6 = parseInt(String(preset.n6), 10); + return Number.isFinite(n6) ? n6 : 0; + }; + + const updateManualBeatNVisibility = () => { + if (!presetManualBeatNWrap) { + return; + } + const manualOn = presetManualModeInput && presetManualModeInput.checked; + const patternName = presetPatternInput ? presetPatternInput.value.trim() : ''; + const ok = !patternName || patternSupportsManual(patternName); + presetManualBeatNWrap.style.display = manualOn && ok ? '' : 'none'; + }; + + const updatePresetBackgroundButton = () => { + if (!presetBackgroundButton || !presetBackgroundInput) return; + const color = coercePresetBackground({ background: presetBackgroundInput.value }); + presetBackgroundInput.value = color; + presetBackgroundButton.textContent = color; + presetBackgroundButton.style.backgroundColor = color; + presetBackgroundButton.style.color = '#fff'; + presetBackgroundButton.style.borderColor = 'rgba(255, 255, 255, 0.6)'; + presetBackgroundButton.title = + currentBackgroundPaletteRef != null + ? `Background from profile palette (index ${currentBackgroundPaletteRef}); click to pick a custom colour` + : 'Choose background colour'; + }; + + const updateDelayVisibilityForManualMode = () => { + if (!presetDelayField) return; + const manualOn = presetManualModeInput && presetManualModeInput.checked; + presetDelayField.style.display = manualOn ? 'none' : ''; + }; + + const updateManualModeAvailability = () => { + if (!presetManualModeInput) { + return; + } + const patternName = presetPatternInput ? presetPatternInput.value.trim() : ''; + const ok = !patternName || patternSupportsManual(patternName); + presetManualModeInput.disabled = !ok; + if (presetManualModeLabel) { + presetManualModeLabel.style.opacity = ok ? '' : '0.55'; + } + if (!ok) { + presetManualModeInput.checked = false; + } + updateManualBeatNVisibility(); + updateDelayVisibilityForManualMode(); + }; + // Function to show/hide color section based on max_colors const updateColorSectionVisibility = () => { const maxColors = getMaxColors(); @@ -206,12 +510,11 @@ document.addEventListener('DOMContentLoaded', () => { // Get max colors for current pattern const maxColors = getMaxColors(); - const maxColorsText = maxColors !== Infinity ? ` (max ${maxColors})` : ''; - + if (currentPresetColors.length === 0) { const empty = document.createElement('p'); empty.className = 'muted-text'; - empty.textContent = `No colors added. Use the color picker to add colors.${maxColorsText}`; + empty.textContent = 'No colours yet.'; presetColorsContainer.appendChild(empty); return; } @@ -221,12 +524,12 @@ document.addEventListener('DOMContentLoaded', () => { const info = document.createElement('p'); info.className = 'muted-text'; info.style.cssText = 'font-size: 0.85em; margin-bottom: 0.5rem; color: #ffa500;'; - info.textContent = `Maximum ${maxColors} color${maxColors !== 1 ? 's' : ''} reached for this pattern.`; + info.textContent = 'Maximum colours reached.'; presetColorsContainer.appendChild(info); } const swatchContainer = document.createElement('div'); - swatchContainer.style.cssText = 'display: flex; flex-wrap: wrap; gap: 0.5rem;'; + swatchContainer.style.cssText = 'display: flex; flex-wrap: nowrap; gap: 0.5rem; align-items: flex-start; overflow-x: auto;'; swatchContainer.classList.add('color-swatches-container'); currentPresetColors.forEach((color, index) => { @@ -398,7 +701,7 @@ document.addEventListener('DOMContentLoaded', () => { presetColorsContainer.appendChild(swatchContainer); }; - + // Function to get drag after element for colors (horizontal layout) const getDragAfterElementForColors = (container, x) => { const draggableElements = [...container.querySelectorAll('.draggable-color-swatch:not(.dragging-color)')]; @@ -422,12 +725,46 @@ document.addEventListener('DOMContentLoaded', () => { presetNameInput.value = preset.name || ''; const patternName = preset.pattern || ''; presetPatternInput.value = patternName; - const colors = Array.isArray(preset.colors) ? preset.colors : []; - const paletteRefs = Array.isArray(preset.palette_refs) ? preset.palette_refs : []; + const colors = Array.isArray(preset.colors) ? preset.colors.slice() : []; + const paletteRefs = Array.isArray(preset.palette_refs) ? preset.palette_refs.slice() : []; renderPresetColors(colors, paletteRefs); presetBrightnessInput.value = preset.brightness || 0; presetDelayInput.value = preset.delay || 0; - + if (presetBackgroundInput) { + const rawBgRef = preset.background_palette_ref ?? preset.backgroundPaletteRef; + let bgRef = null; + if (rawBgRef != null && rawBgRef !== '') { + const n = typeof rawBgRef === 'number' ? rawBgRef : parseInt(String(rawBgRef), 10); + if (Number.isInteger(n) && n >= 0) { + bgRef = n; + } + } + currentBackgroundPaletteRef = bgRef; + presetBackgroundInput.value = coercePresetBackground(preset); + updatePresetBackgroundButton(); + const gen = ++bgPaletteResolveGen; + void getCurrentProfilePaletteColors().then((pal) => { + if (gen !== bgPaletteResolveGen || !presetBackgroundInput) { + return; + } + presetBackgroundInput.value = resolvePresetBackgroundHex(preset, pal); + updatePresetBackgroundButton(); + }); + } else { + updatePresetBackgroundButton(); + } + if (presetManualModeInput) { + const autoVal = typeof preset.auto === 'boolean' ? preset.auto : true; + presetManualModeInput.checked = !autoVal; + } + if (presetManualBeatNInput) { + const raw = preset.manual_beat_n; + let n = typeof raw === 'number' ? raw : parseInt(String(raw != null ? raw : '1'), 10); + if (!Number.isFinite(n)) n = 1; + n = Math.max(1, Math.min(64, n)); + presetManualBeatNInput.value = String(n); + } + // Update color section visibility based on pattern updateColorSectionVisibility(); @@ -458,6 +795,12 @@ document.addEventListener('DOMContentLoaded', () => { }); } + if (presetReverseInput) { + const n5raw = preset.n5; + const n5 = typeof n5raw === 'number' ? n5raw : parseInt(String(n5raw != null ? n5raw : '0'), 10); + presetReverseInput.checked = Number.isFinite(n5) && n5 > 0; + } + // Set n values, checking both n keys and descriptive names for (let i = 1; i <= 8; i++) { const nKey = `n${i}`; @@ -481,11 +824,13 @@ document.addEventListener('DOMContentLoaded', () => { } // After values: show only mapped n params with labels from pattern.json; clear hidden inputs - updatePresetNLabels(patternName); + updatePresetNLabels(patternName, preset); + updateManualModeAvailability(); updatePresetEditorTabActionsVisibility(); }; const clearForm = () => { + bgPaletteResolveGen += 1; currentEditId = null; currentEditTabId = null; currentPresetColors = []; @@ -504,7 +849,22 @@ document.addEventListener('DOMContentLoaded', () => { n6: 0, n7: 0, n8: 0, + background: '#000000', + auto: true, + manual_beat_n: 1, }); + if (presetManualModeInput) { + presetManualModeInput.checked = false; + } + if (presetReverseInput) { + presetReverseInput.checked = false; + } + setPresetReverseFieldVisible(false); + if (presetManualBeatNInput) { + presetManualBeatNInput.value = '1'; + } + updatePresetBackgroundButton(); + updateManualModeAvailability(); // Re-enable name and pattern when clearing (for new preset) if (presetNameInput) { presetNameInput.disabled = false; @@ -527,10 +887,29 @@ document.addEventListener('DOMContentLoaded', () => { return section ? section.dataset.zoneId : null; }; - const updatePresetEditorTabActionsVisibility = () => { + const updatePresetEditorTabActionsVisibility = async () => { if (!presetRemoveFromTabButton) return; - const show = Boolean(currentEditTabId && currentEditId); - presetRemoveFromTabButton.hidden = !show; + if (!currentEditTabId || !currentEditId) { + presetRemoveFromTabButton.hidden = true; + return; + } + try { + const tabRes = await fetch(`/zones/${currentEditTabId}`, { + headers: { Accept: 'application/json' }, + }); + if (!tabRes.ok) { + presetRemoveFromTabButton.hidden = false; + return; + } + const tabData = await tabRes.json(); + const allowed = + typeof window.zoneAllowsPresets === 'function' + ? window.zoneAllowsPresets(tabData, currentEditTabId) + : true; + presetRemoveFromTabButton.hidden = !allowed; + } catch (e) { + presetRemoveFromTabButton.hidden = false; + } }; const updateTabDefaultPreset = async (presetId) => { @@ -561,8 +940,15 @@ document.addEventListener('DOMContentLoaded', () => { if (presetEditorModal) { presetEditorModal.classList.add('active'); } + const patternName = presetPatternInput ? presetPatternInput.value : ''; + const modeBefore = patternSupportsModes(patternName) + ? presetStoredMode({ + mode: presetModeInput ? presetModeInput.value : undefined, + n6: getNumberInput('preset-n6-input'), + }) + : 0; loadPatterns().then(() => { - updatePresetNLabels(presetPatternInput ? presetPatternInput.value : ''); + updatePresetNLabels(patternName, { mode: modeBefore, n6: modeBefore }); updateColorSectionVisibility(); }); }; @@ -582,13 +968,38 @@ document.addEventListener('DOMContentLoaded', () => { // Use canonical field names expected by the device / API brightness: presetBrightnessInput ? parseInt(presetBrightnessInput.value, 10) || 0 : 0, delay: presetDelayInput ? parseInt(presetDelayInput.value, 10) || 0 : 0, + background: presetBackgroundInput ? presetBackgroundInput.value : '#000000', + background_palette_ref: currentBackgroundPaletteRef != null ? currentBackgroundPaletteRef : null, + auto: presetManualModeInput ? !presetManualModeInput.checked : true, + manual_beat_n: (() => { + if (!presetManualBeatNInput) return 1; + let n = parseInt(presetManualBeatNInput.value, 10); + if (!Number.isFinite(n)) n = 1; + return Math.max(1, Math.min(64, n)); + })(), }; - // Always store numeric parameters as n1..n8. + // Always store numeric parameters as n1..n8 (except n6 when pattern uses mode). + const modeEntries = patternSupportsModes(payload.pattern) + ? getPatternModeOptions(payload.pattern) + : null; + const reverseField = patternSupportsReverse(payload.pattern); for (let i = 1; i <= 8; i++) { const nKey = `n${i}`; + if (modeEntries && nKey === 'n6') { + continue; + } + if (reverseField && nKey === 'n5') { + continue; + } payload[nKey] = getNumberInput(`preset-${nKey}-input`); } + if (reverseField) { + payload.n5 = presetReverseInput && presetReverseInput.checked ? 1 : 0; + } + if (modeEntries && presetModeInput) { + payload.mode = parseInt(presetModeInput.value, 10) || 0; + } return payload; }; @@ -675,30 +1086,8 @@ document.addEventListener('DOMContentLoaded', () => { } }; - const updatePresetNLabels = (patternName) => { - const rawPatternName = String(patternName || '').trim(); - const normalizedPatternName = rawPatternName.endsWith('.py') - ? rawPatternName.slice(0, -3) - : rawPatternName; - let patternConfig = - (cachedPatterns && cachedPatterns[rawPatternName]) || - (cachedPatterns && cachedPatterns[normalizedPatternName]) || - null; - if (!patternConfig && cachedPatterns && typeof cachedPatterns === 'object') { - const lower = normalizedPatternName.toLowerCase(); - const matchedKey = Object.keys(cachedPatterns).find( - (k) => String(k).toLowerCase() === lower, - ); - if (matchedKey) { - patternConfig = cachedPatterns[matchedKey]; - } - } - if (patternConfig && typeof patternConfig === 'object' && patternConfig.data && typeof patternConfig.data === 'object') { - patternConfig = patternConfig.data; - } - if (patternConfig && typeof patternConfig === 'object' && patternConfig.parameter_mappings && typeof patternConfig.parameter_mappings === 'object') { - patternConfig = patternConfig.parameter_mappings; - } + const updatePresetNLabels = (patternName, presetForMode = null) => { + const patternConfig = resolvePatternConfig(patternName); const labels = {}; const visibleNKeys = new Set(); @@ -714,9 +1103,45 @@ document.addEventListener('DOMContentLoaded', () => { }); } + const modeEntries = patternSupportsModes(patternName) ? getPatternModeOptions(patternName) : null; + const reverseField = patternSupportsReverse(patternName); + if (modeEntries) { + visibleNKeys.delete('n6'); + } + if (reverseField) { + visibleNKeys.delete('n5'); + } + setPresetReverseFieldVisible(reverseField); + if (reverseField && presetReverseInput) { + const n5raw = presetForMode && presetForMode.n5 !== undefined ? presetForMode.n5 : 0; + const n5 = typeof n5raw === 'number' ? n5raw : parseInt(String(n5raw), 10); + presetReverseInput.checked = Number.isFinite(n5) && n5 > 0; + } + if (presetModeInput) { + if (modeEntries) { + setPresetModeFieldVisible(true); + presetModeInput.innerHTML = ''; + modeEntries.forEach(([val, label]) => { + const opt = document.createElement('option'); + opt.value = val; + opt.textContent = label.trim(); + presetModeInput.appendChild(opt); + }); + const modeVal = presetForMode ? presetStoredMode(presetForMode) : 0; + const modeStr = String(modeVal); + if ([...presetModeInput.options].some((o) => o.value === modeStr)) { + presetModeInput.value = modeStr; + } else if (presetModeInput.options.length) { + presetModeInput.selectedIndex = 0; + } + } else { + setPresetModeFieldVisible(false); + } + } + const hasPatternMeta = patternConfig && typeof patternConfig === 'object' && Object.keys(patternConfig).length > 0; - const hasAnyNLabel = visibleNKeys.size > 0; + const hasAnyNLabel = visibleNKeys.size > 0 || Boolean(modeEntries); for (let i = 1; i <= 8; i++) { const nKey = `n${i}`; @@ -742,6 +1167,7 @@ document.addEventListener('DOMContentLoaded', () => { if (nGrid) { nGrid.style.display = visibleNKeys.size > 0 ? '' : 'none'; } + updateManualModeAvailability(); }; const renderPresets = (presets) => { @@ -762,12 +1188,6 @@ document.addEventListener('DOMContentLoaded', () => { const label = document.createElement('span'); label.textContent = (preset && preset.name) || presetId; - const details = document.createElement('span'); - const pattern = preset && preset.pattern ? preset.pattern : '-'; - details.textContent = pattern; - details.style.color = '#aaa'; - details.style.fontSize = '0.85em'; - const editButton = document.createElement('button'); editButton.className = 'btn btn-secondary btn-small'; editButton.textContent = 'Edit'; @@ -824,7 +1244,6 @@ document.addEventListener('DOMContentLoaded', () => { }); row.appendChild(label); - row.appendChild(details); row.appendChild(editButton); row.appendChild(sendButton); row.appendChild(deleteButton); @@ -872,6 +1291,34 @@ document.addEventListener('DOMContentLoaded', () => { if (presetsCloseButton) { presetsCloseButton.addEventListener('click', closeModal); } + const importPresetBtn = document.getElementById('import-preset-btn'); + if (importPresetBtn) { + importPresetBtn.addEventListener('click', async () => { + const text = await window.pickJsonFile(); + if (!text) return; + const bundle = window.parseJsonFileText(text); + if (!bundle || bundle.kind !== 'preset') { + alert('Invalid preset bundle file.'); + return; + } + try { + const response = await fetch('/presets/import', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify({ bundle }), + }); + if (!response.ok) { + const err = await response.json().catch(() => ({})); + throw new Error(err.error || 'Import failed'); + } + await loadPresets(); + } catch (error) { + console.error('Import preset failed:', error); + alert(error.message || 'Failed to import preset.'); + } + }); + } + if (presetsAddButton) { presetsAddButton.addEventListener('click', () => { clearForm(); @@ -890,12 +1337,17 @@ document.addEventListener('DOMContentLoaded', () => { return; } try { - const targetMacs = - typeof window.tabsManager !== 'undefined' && - typeof window.tabsManager.resolveTabDeviceMacs === 'function' - ? await window.tabsManager.resolveTabDeviceMacs(deviceNames) - : []; - await postDriverSequence([{ v: '1', clear_presets: true, save: true }], targetMacs); + const zoneId = section && section.dataset.zoneId; + let groupIds = []; + if (zoneId) { + const zr = await fetch(`/zones/${zoneId}`, { headers: { Accept: 'application/json' } }); + if (zr.ok) { + groupIds = zoneGroupIdsFromTabData(await zr.json()); + } + } + const clearMsg = { v: '1', clear_presets: true, save: true }; + if (groupIds.length) clearMsg.groups = groupIds; + await postDriverSequence([clearMsg], [], 0.05, { groupIds }); } catch (error) { console.error('Clear device presets failed:', error); alert('Failed to clear presets on devices.'); @@ -922,7 +1374,7 @@ document.addEventListener('DOMContentLoaded', () => { alert('Could not determine current zone.'); return; } - + // Load all presets try { const response = await fetch('/presets', { @@ -958,15 +1410,17 @@ document.addEventListener('DOMContentLoaded', () => { // Create modal const modal = document.createElement('div'); - modal.className = 'modal active'; + modal.className = 'modal active modal-child-overlay'; modal.id = 'add-preset-to-zone-modal'; modal.innerHTML = `