feat: main's import/export, zones, audio API and web UI
Profiles, presets and sequences export and import as main's bundles. Zones carry group_ids, preset_group_ids, sequence_ids, content_kind and brightness; profiles seed rainbow as colour_cycle, and deleting a profile also deletes its sequences. Groups, zones and sequences written by older versions are migrated at boot. /api/audio (status, event stream, start/stop, reset, anchor-bar, devices) maps main's audio detector onto the mic's beat detector. Audio start/stop picks whether mic beats or the BPM clock time sequences; the clock's beats also go to the drivers while the mic is off. /ws now greets from a post-handshake callback (httpd does not call the handler for the upgrade). The web UI is main's, plus v2's outputs editor, list search and hostname/static IP settings; the bridge, Wi-Fi AP and led-tool parts are gone. API tests follow main's behaviour (119 pass on the board). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
04b56c6ef2
commit
bfeeb958df
44 files changed
+8696
-2325
No files matched your search
+1
-1
@@ -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
|
||||
|
||||
@@ -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)) { // /<profiles|presets|sequences>/import and /<id>/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*",
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#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;
|
||||
}
|
||||
@@ -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);
|
||||
+24
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
+3
-1
@@ -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);
|
||||
|
||||
@@ -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 <stdio.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#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;
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -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;
|
||||
|
||||
+92
-15
@@ -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/<id>: 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/<id>: 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");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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
|
||||
+2
-2
@@ -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 <ip>` (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/<name>`), and afterwards they write each one back (`PUT /db/<name>`). 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/<name>`), and afterwards they write each one back (`PUT /db/<name>`). 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
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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):
|
||||
|
||||
@@ -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"]
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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}")
|
||||
+910
-162
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
}
|
||||
};
|
||||
+293
-103
@@ -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;
|
||||
}
|
||||
@@ -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 = '<span class="muted-text">Loading...</span>';
|
||||
try {
|
||||
const data = await fetchGroupsMap();
|
||||
renderGroupsList(data || {});
|
||||
} catch (e) {
|
||||
console.error('loadGroupsModal:', e);
|
||||
container.innerHTML = '<span class="muted-text">Failed to load groups.</span>';
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
});
|
||||
+31
-71
@@ -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 = `
|
||||
<h4>AP Status: <span class="status-connected">Active</span></h4>
|
||||
<p><strong>SSID:</strong> ${config.ssid || 'N/A'}</p>
|
||||
<p><strong>Channel:</strong> ${config.channel || 'Auto'}</p>
|
||||
<p><strong>IP Address:</strong> ${config.ip || 'N/A'}</p>
|
||||
`;
|
||||
} else {
|
||||
statusEl.innerHTML = `
|
||||
<h4>AP Status: <span class="status-disconnected">Inactive</span></h4>
|
||||
<p>Access Point is not currently active</p>
|
||||
`;
|
||||
}
|
||||
if (config.saved_ssid) document.getElementById('ap-ssid').value = config.saved_ssid;
|
||||
if (config.saved_channel) document.getElementById('ap-channel').value = config.saved_channel;
|
||||
} catch (error) {
|
||||
console.error('Error loading AP status:', error);
|
||||
}
|
||||
}
|
||||
|
||||
if (settingsButton && settingsModal) {
|
||||
settingsButton.addEventListener('click', () => {
|
||||
settingsModal.classList.add('active');
|
||||
// Load current WiFi status/config when opening
|
||||
loadDeviceSettings();
|
||||
loadAPStatus();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -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 = '<option value="">Select a serial port</option>';
|
||||
|
||||
for (const port of data.ports || []) {
|
||||
const option = document.createElement('option');
|
||||
option.value = port.device;
|
||||
option.textContent = `${port.device} - ${port.description || 'Unknown'}`;
|
||||
portSelect.appendChild(option);
|
||||
}
|
||||
if (previous) {
|
||||
portSelect.value = previous;
|
||||
} else if ((data.ports || []).some((p) => p.device === defaultPort)) {
|
||||
portSelect.value = defaultPort;
|
||||
} else {
|
||||
const fallback = document.createElement('option');
|
||||
fallback.value = defaultPort;
|
||||
fallback.textContent = `${defaultPort} - default`;
|
||||
portSelect.appendChild(fallback);
|
||||
portSelect.value = defaultPort;
|
||||
}
|
||||
|
||||
if (!data.led_cli_exists) {
|
||||
showMessage('led-tool/cli.py was not found on the host.', 'error');
|
||||
} else if ((data.ports || []).length === 0) {
|
||||
showMessage('No serial ports found.', 'error');
|
||||
} else {
|
||||
showMessage(`Found ${(data.ports || []).length} serial port(s).`, 'success');
|
||||
}
|
||||
} catch (error) {
|
||||
showMessage(`Failed to read serial ports: ${error.message}`, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
openBtn.addEventListener('click', () => {
|
||||
modal.classList.add('active');
|
||||
loadPorts();
|
||||
});
|
||||
|
||||
if (closeBtn) {
|
||||
closeBtn.addEventListener('click', () => {
|
||||
modal.classList.remove('active');
|
||||
});
|
||||
}
|
||||
|
||||
if (refreshPortsBtn) {
|
||||
refreshPortsBtn.addEventListener('click', () => {
|
||||
loadPorts();
|
||||
});
|
||||
}
|
||||
|
||||
if (readBtn) {
|
||||
readBtn.addEventListener('click', async () => {
|
||||
const port = portSelect.value.trim();
|
||||
if (!port) {
|
||||
showMessage('Select a serial port first.', 'error');
|
||||
return;
|
||||
}
|
||||
setOutput('Reading settings from device...');
|
||||
showMessage('Reading settings over USB...', 'success');
|
||||
try {
|
||||
const response = await fetch(`/led-tool/settings?port=${encodeURIComponent(port)}`);
|
||||
const data = await parseApiResponse(response);
|
||||
if (!response.ok) {
|
||||
showMessage(data.error || 'Read failed.', 'error');
|
||||
setOutput(data.error || 'Request failed.');
|
||||
return;
|
||||
}
|
||||
const output = [
|
||||
`exit code: ${data.returncode}`,
|
||||
'',
|
||||
'stdout:',
|
||||
data.stdout || '(none)',
|
||||
'',
|
||||
'stderr:',
|
||||
data.stderr || '(none)',
|
||||
].join('\n');
|
||||
setOutput(output);
|
||||
if (data.ok) {
|
||||
const populated = populateFormFromSettings(data.settings);
|
||||
if (populated) {
|
||||
showMessage('Settings read and fields populated.', 'success');
|
||||
} else {
|
||||
showMessage('Settings read successfully.', 'success');
|
||||
}
|
||||
} else {
|
||||
showMessage('Read completed with errors. Check output.', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showMessage(`Request failed: ${error.message}`, 'error');
|
||||
setOutput(error.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (resetBtn) {
|
||||
resetBtn.addEventListener('click', async () => {
|
||||
const port = portSelect.value.trim();
|
||||
if (!port) {
|
||||
showMessage('Select a serial port first.', 'error');
|
||||
return;
|
||||
}
|
||||
setOutput('Resetting device and following output...');
|
||||
showMessage('Resetting device over USB...', 'success');
|
||||
try {
|
||||
const response = await fetch('/led-tool/reset', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ port }),
|
||||
});
|
||||
const data = await parseApiResponse(response);
|
||||
if (!response.ok) {
|
||||
showMessage(data.error || 'Reset failed.', 'error');
|
||||
setOutput(data.error || 'Request failed.');
|
||||
return;
|
||||
}
|
||||
const output = [
|
||||
`exit code: ${data.returncode}`,
|
||||
'',
|
||||
'stdout:',
|
||||
data.stdout || '(none)',
|
||||
'',
|
||||
'stderr:',
|
||||
data.stderr || '(none)',
|
||||
].join('\n');
|
||||
setOutput(output);
|
||||
if (data.ok) {
|
||||
showMessage('Device reset complete.', 'success');
|
||||
} else {
|
||||
showMessage('Reset completed with errors. Check output.', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showMessage(`Request failed: ${error.message}`, 'error');
|
||||
setOutput(error.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
form.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const port = portSelect.value.trim();
|
||||
if (!port) {
|
||||
showMessage('Select a serial port first.', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
port,
|
||||
name: document.getElementById('led-tool-name')?.value?.trim() || '',
|
||||
num_leds: document.getElementById('led-tool-num-leds')?.value?.trim() || '',
|
||||
led_pin: document.getElementById('led-tool-led-pin')?.value?.trim() || '',
|
||||
brightness: document.getElementById('led-tool-brightness')?.value?.trim() || '',
|
||||
transport: document.getElementById('led-tool-transport')?.value?.trim() || '',
|
||||
ssid: document.getElementById('led-tool-ssid')?.value?.trim() || '',
|
||||
password: document.getElementById('led-tool-password')?.value?.trim() || '',
|
||||
wifi_channel: document.getElementById('led-tool-wifi-channel')?.value?.trim() || '',
|
||||
default: document.getElementById('led-tool-default')?.value?.trim() || '',
|
||||
};
|
||||
|
||||
setOutput('Running led-tool command...');
|
||||
showMessage('Running command over USB...', 'success');
|
||||
try {
|
||||
const response = await fetch('/led-tool/settings', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = await parseApiResponse(response);
|
||||
if (!response.ok) {
|
||||
showMessage(data.error || 'Command failed.', 'error');
|
||||
setOutput(data.error || 'Request failed.');
|
||||
return;
|
||||
}
|
||||
const output = [
|
||||
`exit code: ${data.returncode}`,
|
||||
'',
|
||||
'stdout:',
|
||||
data.stdout || '(none)',
|
||||
'',
|
||||
'stderr:',
|
||||
data.stderr || '(none)',
|
||||
].join('\n');
|
||||
setOutput(output);
|
||||
if (data.ok) {
|
||||
showMessage('Settings applied via USB.', 'success');
|
||||
} else {
|
||||
showMessage('Command completed with errors. Check output.', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showMessage(`Request failed: ${error.message}`, 'error');
|
||||
setOutput(error.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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<string, () => void | Promise<void>>} */
|
||||
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));
|
||||
});
|
||||
})();
|
||||
+55
-45
@@ -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.');
|
||||
|
||||
+958
-175
File diff suppressed because it is too large.
Load diff
@@ -6,12 +6,16 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
const newProfileInput = document.getElementById("new-profile-name");
|
||||
const newProfileSeedDjInput = document.getElementById("new-profile-seed-dj");
|
||||
const createProfileButton = document.getElementById("create-profile-btn");
|
||||
const importProfileButton = document.getElementById("import-profile-btn");
|
||||
|
||||
if (!profilesButton || !profilesModal || !profilesList) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isEditModeActive = () => {
|
||||
if (typeof window.getPresetUiMode === 'function') {
|
||||
return window.getPresetUiMode() === 'edit';
|
||||
}
|
||||
const toggle = document.querySelector('.ui-mode-toggle');
|
||||
return !!(toggle && toggle.getAttribute('aria-pressed') === 'true');
|
||||
};
|
||||
@@ -101,6 +105,26 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
}
|
||||
});
|
||||
|
||||
const exportButton = document.createElement("button");
|
||||
exportButton.className = "btn btn-secondary btn-small";
|
||||
exportButton.textContent = "Export";
|
||||
exportButton.addEventListener("click", async () => {
|
||||
try {
|
||||
const response = await fetch(`/profiles/${profileId}/export`, {
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error("Export failed");
|
||||
}
|
||||
const bundle = await response.json();
|
||||
const safeName = ((profile && profile.name) || profileId).replace(/[^\w.-]+/g, "_");
|
||||
window.downloadJsonFile(`profile-${safeName}.json`, bundle);
|
||||
} catch (error) {
|
||||
console.error("Export profile failed:", error);
|
||||
alert("Failed to export profile.");
|
||||
}
|
||||
});
|
||||
|
||||
const cloneButton = document.createElement("button");
|
||||
cloneButton.className = "btn btn-secondary btn-small";
|
||||
cloneButton.textContent = "Clone";
|
||||
@@ -177,6 +201,7 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
row.appendChild(label);
|
||||
row.appendChild(applyButton);
|
||||
if (editMode) {
|
||||
row.appendChild(exportButton);
|
||||
row.appendChild(cloneButton);
|
||||
row.appendChild(deleteButton);
|
||||
}
|
||||
@@ -276,6 +301,60 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
if (createProfileButton) {
|
||||
createProfileButton.addEventListener("click", createProfile);
|
||||
}
|
||||
|
||||
const importProfile = async () => {
|
||||
if (!isEditModeActive()) {
|
||||
return;
|
||||
}
|
||||
const text = await window.pickJsonFile();
|
||||
if (!text) {
|
||||
return;
|
||||
}
|
||||
const bundle = window.parseJsonFileText(text);
|
||||
if (!bundle || typeof bundle !== "object") {
|
||||
alert("Invalid JSON file.");
|
||||
return;
|
||||
}
|
||||
const defaultName =
|
||||
(bundle.profile && bundle.profile.name) || "Imported profile";
|
||||
const name = prompt("Profile name for import:", defaultName);
|
||||
if (name === null) {
|
||||
return;
|
||||
}
|
||||
const trimmed = String(name).trim();
|
||||
if (!trimmed) {
|
||||
alert("Profile name cannot be empty.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch("/profiles/import", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||||
body: JSON.stringify({ bundle, name: trimmed, apply: true }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
throw new Error(err.error || "Import failed");
|
||||
}
|
||||
const data = await response.json();
|
||||
const newProfileId = data.id || Object.keys(data).find((k) => k !== "id");
|
||||
if (newProfileId) {
|
||||
await fetch(`/profiles/${newProfileId}/apply`, {
|
||||
method: "POST",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
}
|
||||
await loadProfiles();
|
||||
await refreshTabsForActiveProfile();
|
||||
} catch (error) {
|
||||
console.error("Import profile failed:", error);
|
||||
alert(error.message || "Failed to import profile.");
|
||||
}
|
||||
};
|
||||
|
||||
if (importProfileButton) {
|
||||
importProfileButton.addEventListener("click", importProfile);
|
||||
}
|
||||
if (newProfileInput) {
|
||||
newProfileInput.addEventListener("keypress", (event) => {
|
||||
if (event.key === "Enter") {
|
||||
|
||||
+1173
-259
File diff suppressed because it is too large.
Load diff
+1242
-243
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Scrollable device/group list with a fixed add row (dropdown + button) below.
|
||||
* Used by group and zone edit modals.
|
||||
*/
|
||||
function prepareZoneDevicesPanel(containerEl) {
|
||||
if (!containerEl) return null;
|
||||
let listEl = containerEl.querySelector('.zone-devices-list');
|
||||
let addSlot = containerEl.querySelector('.zone-devices-add-slot');
|
||||
if (!listEl) {
|
||||
containerEl.innerHTML = '';
|
||||
containerEl.classList.add('zone-devices-panel');
|
||||
listEl = document.createElement('div');
|
||||
listEl.className = 'zone-devices-list';
|
||||
addSlot = document.createElement('div');
|
||||
addSlot.className = 'zone-devices-add-slot';
|
||||
containerEl.appendChild(listEl);
|
||||
containerEl.appendChild(addSlot);
|
||||
} else {
|
||||
listEl.innerHTML = '';
|
||||
addSlot.innerHTML = '';
|
||||
}
|
||||
return { listEl, addSlot };
|
||||
}
|
||||
|
||||
/**
|
||||
* Search field + scrollable filtered list for picking an item to add.
|
||||
*/
|
||||
function createSearchableAddPicker({
|
||||
entries,
|
||||
excludeIds,
|
||||
labelFor,
|
||||
searchTextFor,
|
||||
onPick,
|
||||
placeholder = 'Search…',
|
||||
emptyMessage = 'No matches.',
|
||||
noItemsMessage = 'Nothing to add.',
|
||||
}) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'zone-device-add-picker';
|
||||
|
||||
const excluded = excludeIds || new Set();
|
||||
const available = (entries || []).filter(([id]) => !excluded.has(id));
|
||||
|
||||
if (!available.length) {
|
||||
const empty = document.createElement('span');
|
||||
empty.className = 'muted-text';
|
||||
empty.textContent = noItemsMessage;
|
||||
wrap.appendChild(empty);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
const search = document.createElement('input');
|
||||
search.type = 'search';
|
||||
search.className = 'zone-device-add-search';
|
||||
search.placeholder = placeholder;
|
||||
search.setAttribute('aria-label', placeholder);
|
||||
|
||||
const results = document.createElement('div');
|
||||
results.className = 'zone-device-add-results';
|
||||
results.setAttribute('role', 'listbox');
|
||||
|
||||
const filterAvailable = (query) => {
|
||||
const q = String(query || '').trim().toLowerCase();
|
||||
return available.filter(([id, item]) => {
|
||||
if (!q) return true;
|
||||
const text = searchTextFor(id, item);
|
||||
return String(text).toLowerCase().includes(q);
|
||||
});
|
||||
};
|
||||
|
||||
const pickEntry = (id, item) => {
|
||||
onPick(id, item);
|
||||
search.value = '';
|
||||
renderResults('');
|
||||
};
|
||||
|
||||
const renderResults = (query) => {
|
||||
results.innerHTML = '';
|
||||
const filtered = filterAvailable(query);
|
||||
|
||||
if (!filtered.length) {
|
||||
const none = document.createElement('div');
|
||||
none.className = 'zone-device-add-results-empty muted-text';
|
||||
none.textContent = emptyMessage;
|
||||
results.appendChild(none);
|
||||
return;
|
||||
}
|
||||
|
||||
filtered.forEach(([id, item]) => {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'zone-device-add-result';
|
||||
btn.setAttribute('role', 'option');
|
||||
btn.textContent = labelFor(id, item);
|
||||
btn.addEventListener('click', () => pickEntry(id, item));
|
||||
results.appendChild(btn);
|
||||
});
|
||||
};
|
||||
|
||||
search.addEventListener('input', () => renderResults(search.value));
|
||||
search.addEventListener('focus', () => renderResults(search.value));
|
||||
|
||||
search.addEventListener('keydown', (event) => {
|
||||
if (event.key !== 'Enter') return;
|
||||
const filtered = filterAvailable(search.value);
|
||||
if (filtered.length === 1) {
|
||||
event.preventDefault();
|
||||
pickEntry(filtered[0][0], filtered[0][1]);
|
||||
}
|
||||
});
|
||||
|
||||
renderResults('');
|
||||
|
||||
wrap.appendChild(search);
|
||||
wrap.appendChild(results);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.prepareZoneDevicesPanel = prepareZoneDevicesPanel;
|
||||
window.createSearchableAddPicker = createSearchableAddPicker;
|
||||
}
|
||||
+546
-257
File diff suppressed because it is too large.
Load diff
+1083
-542
File diff suppressed because it is too large.
Load diff
+4
-118
@@ -170,59 +170,25 @@
|
||||
|
||||
<div class="settings-header">
|
||||
<h1>Device Settings</h1>
|
||||
<p>Configure WiFi Access Point and ESP-NOW options</p>
|
||||
<p>ESP-NOW channel</p>
|
||||
</div>
|
||||
|
||||
<div id="message" class="message"></div>
|
||||
|
||||
<!-- ESP-NOW (LED driver / bridge channel) -->
|
||||
<!-- ESP-NOW channel -->
|
||||
<div class="settings-section">
|
||||
<h2>ESP-NOW</h2>
|
||||
<form id="espnow-form">
|
||||
<div class="form-group">
|
||||
<label for="wifi-channel-page-input">WiFi channel (ESP-NOW)</label>
|
||||
<input type="number" id="wifi-channel-page-input" name="wifi_channel" min="1" max="11" required>
|
||||
<small>STA channel (1–11) for LED drivers and the serial bridge. Use the same value on every device.</small>
|
||||
<small>2.4 GHz channel (1–11) the drivers use. Stored for reference: the controller's channel is set at build time (<code>make menuconfig</code>), and each driver's in its own settings.</small>
|
||||
</div>
|
||||
<div class="btn-group">
|
||||
<button type="submit" class="btn btn-primary btn-full">Save channel</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- WiFi Access Point Settings -->
|
||||
<div class="settings-section">
|
||||
<h2>WiFi Access Point Settings</h2>
|
||||
|
||||
<div id="ap-status" class="status-info">
|
||||
<h3>AP Status</h3>
|
||||
<p>Loading...</p>
|
||||
</div>
|
||||
|
||||
<form id="ap-form">
|
||||
<div class="form-group">
|
||||
<label for="ap-ssid">AP SSID (Network Name)</label>
|
||||
<input type="text" id="ap-ssid" name="ssid" placeholder="Enter AP name" required>
|
||||
<small>The name of the WiFi access point this device creates</small>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="ap-password">AP Password</label>
|
||||
<input type="password" id="ap-password" name="password" placeholder="Enter AP password (min 8 chars)" data-bwignore>
|
||||
<small>Leave empty for open network (min 8 characters if set)</small>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="ap-channel">Channel (1-11)</label>
|
||||
<input type="number" id="ap-channel" name="channel" min="1" max="11" placeholder="Auto">
|
||||
<small>WiFi channel (1-11 for 2.4GHz). Leave empty for auto.</small>
|
||||
</div>
|
||||
|
||||
<div class="btn-group">
|
||||
<button type="submit" class="btn btn-primary btn-full">Configure AP</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -261,7 +227,7 @@
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch('/settings/settings', {
|
||||
const response = await fetch('/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ wifi_channel: wifiChannel }),
|
||||
@@ -277,88 +243,8 @@
|
||||
}
|
||||
});
|
||||
|
||||
// Load AP status and config
|
||||
async function loadAPStatus() {
|
||||
try {
|
||||
const response = await fetch('/settings/wifi/ap');
|
||||
const config = await response.json();
|
||||
|
||||
const statusEl = document.getElementById('ap-status');
|
||||
if (config.active) {
|
||||
statusEl.innerHTML = `
|
||||
<h3>AP Status: <span class="status-connected">Active</span></h3>
|
||||
<p><strong>SSID:</strong> ${config.ssid || 'N/A'}</p>
|
||||
<p><strong>Channel:</strong> ${config.channel || 'Auto'}</p>
|
||||
<p><strong>IP Address:</strong> ${config.ip || 'N/A'}</p>
|
||||
`;
|
||||
} else {
|
||||
statusEl.innerHTML = `
|
||||
<h3>AP Status: <span class="status-disconnected">Inactive</span></h3>
|
||||
<p>Access Point is not currently active</p>
|
||||
`;
|
||||
}
|
||||
|
||||
// Load saved values
|
||||
if (config.saved_ssid) document.getElementById('ap-ssid').value = config.saved_ssid;
|
||||
if (config.saved_channel) document.getElementById('ap-channel').value = config.saved_channel;
|
||||
} catch (error) {
|
||||
console.error('Error loading AP status:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// AP form submission
|
||||
document.getElementById('ap-form').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
const formData = {
|
||||
ssid: document.getElementById('ap-ssid').value,
|
||||
password: document.getElementById('ap-password').value,
|
||||
channel: document.getElementById('ap-channel').value || null
|
||||
};
|
||||
|
||||
// Validate password length if provided
|
||||
if (formData.password && formData.password.length > 0 && formData.password.length < 8) {
|
||||
showMessage('AP password must be at least 8 characters', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// Convert channel to number if provided
|
||||
if (formData.channel) {
|
||||
formData.channel = parseInt(formData.channel);
|
||||
if (formData.channel < 1 || formData.channel > 11) {
|
||||
showMessage('Channel must be between 1 and 11', 'error');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/settings/wifi/ap', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(formData)
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
showMessage('Access Point configured successfully!', 'success');
|
||||
setTimeout(loadAPStatus, 1000);
|
||||
} else {
|
||||
showMessage(`Error: ${result.error || 'Failed to configure AP'}`, 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showMessage(`Error: ${error.message}`, 'error');
|
||||
}
|
||||
});
|
||||
|
||||
// Load all data on page load
|
||||
loadEspnowChannel();
|
||||
loadAPStatus();
|
||||
|
||||
// Refresh status every 10 seconds
|
||||
setInterval(loadAPStatus, 10000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in new issue
Block a user