feat: ping drivers and push groups from the devices modal

POST /devices/ping broadcasts an ESP-NOW PING_REQ, collects the drivers'
PING_RSP for timeout_s and registers or renames the ones that answer. A
reply also counts as the driver being heard, so group updates go to it
again. POST /devices/groups sends every ESP-NOW driver its groups and
reports the acks. The devices modal gets the Ping drivers and Update
groups buttons from main, with per-driver ping dots.

UI files are now served with Cache-Control: no-cache and the firmware
build hash as ETag, so a browser picks up a new UI right after an update
instead of a day later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-11-03 17:53:56 +13:00
1 parent e7f238aebc
commit 19fea0b0a1
10 files changed
+559 -29

No files matched your search

+67 -10
View File
@@ -814,31 +814,40 @@ static esp_err_t send_cmd(const uint8_t mac[6], const uint8_t *env, size_t len,
// GROUPS packet: the ids of every zone whose driver names include `name`. An empty list replaces // GROUPS packet: the ids of every zone whose driver names include `name`. An empty list replaces
// whatever the driver stored, so it is only sent when allow_empty is set (a zone or device was edited); // whatever the driver stored, so it is only sent when allow_empty is set (a zone or device was edited);
// a driver that merely announced itself and is in no zone keeps the groups it already has. // a driver that merely announced itself and is in no zone keeps the groups it already has.
static void send_groups(const uint8_t mac[6], const char *name, bool allow_empty) // GROUPS packet for a driver: [4C][02][count] then per zone [len][zone id]. Returns its length;
// *count gets the number of zones.
static size_t build_groups(uint8_t pkt[REL_FRAG_MAX], const char *name, int *count)
{ {
uint8_t pkt[REL_FRAG_MAX];
size_t off = 3; size_t off = 3;
int count = 0; *count = 0;
const cJSON *z; const cJSON *z;
cJSON_ArrayForEach(z, store_coll("zone")) cJSON_ArrayForEach(z, store_coll("zone"))
{ {
const cJSON *names = cJSON_GetObjectItem(z, "names"); const cJSON *names = cJSON_GetObjectItem(z, "names");
size_t gl = strlen(z->string); size_t gl = strlen(z->string);
if (cJSON_IsArray(names) && name_seen(names, cJSON_GetArraySize(names), name) && off + 1 + gl <= sizeof(pkt) && if (cJSON_IsArray(names) && name_seen(names, cJSON_GetArraySize(names), name) && off + 1 + gl <= REL_FRAG_MAX &&
gl < 16) { gl < 16) {
pkt[off++] = gl; pkt[off++] = gl;
memcpy(pkt + off, z->string, gl); memcpy(pkt + off, z->string, gl);
off += gl; off += gl;
count++; (*count)++;
} }
} }
if (count == 0 && !allow_empty) {
return;
}
pkt[0] = 0x4C; pkt[0] = 0x4C;
pkt[1] = 0x02; // GROUPS pkt[1] = 0x02; // GROUPS
pkt[2] = count; pkt[2] = *count;
rel_send(mac, pkt, off, false, 1); return off;
}
static void send_groups(const uint8_t mac[6], const char *name, bool allow_empty)
{
uint8_t pkt[REL_FRAG_MAX];
int count;
size_t len = build_groups(pkt, name, &count);
if (count == 0 && !allow_empty) {
return;
}
rel_send(mac, pkt, len, false, 1);
} }
static bool hex_mac(const char *s, uint8_t mac[6]) static bool hex_mac(const char *s, uint8_t mac[6])
@@ -902,6 +911,54 @@ void engine_groups_changed(void)
store_unlock(); store_unlock();
} }
#define PUSH_MAX 32
void engine_groups_push_all(int *total, int *sent, int *failed)
{
struct {
uint8_t mac[6];
uint16_t seq;
bool queued;
} out[PUSH_MAX];
int n = 0;
store_lock();
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
const cJSON *name = cJSON_GetObjectItem(d, "name"), *addr = cJSON_GetObjectItem(d, "address");
const cJSON *tr = cJSON_GetObjectItem(d, "transport");
const char *hex = cJSON_IsString(addr) ? addr->valuestring : d->string;
if (n < PUSH_MAX && cJSON_IsString(name) && cJSON_IsString(tr) && !strcmp(tr->valuestring, "espnow") &&
hex_mac(hex, out[n].mac)) {
uint8_t pkt[REL_FRAG_MAX];
int count;
size_t len = build_groups(pkt, name->valuestring, &count);
out[n].queued = false;
for (int i = 0; i < 400 && !out[n].queued; i++) { // wait for room, as tx() does
esp_err_t err = rel_send_seq(out[n].mac, pkt, len, false, 1, &out[n].seq);
out[n].queued = err == ESP_OK;
if (err != ESP_ERR_NO_MEM) {
break;
}
vTaskDelay(pdMS_TO_TICKS(5));
}
n++;
}
}
store_unlock();
// All are in flight at once; then collect each outcome (rel gives up after about 2 s)
*total = n;
*sent = *failed = 0;
for (int i = 0; i < n; i++) {
bool ok = out[i].queued && rel_wait(out[i].mac, out[i].seq, 3000) == ESP_OK;
if (ok) {
(*sent)++;
} else {
(*failed)++;
}
}
}
// A driver said hello at boot: register it, then tell it which zones it belongs to // A driver said hello at boot: register it, then tell it which zones it belongs to
static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len) static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len)
{ {
+3
View File
@@ -32,3 +32,6 @@ cJSON *engine_seq_status(void);
// Zones or devices changed: re-send group membership to every registered ESP-NOW driver // Zones or devices changed: re-send group membership to every registered ESP-NOW driver
void engine_groups_changed(void); void engine_groups_changed(void);
// POST /devices/groups: send every ESP-NOW driver its groups, including silent ones, and wait for the
// acks. Call without the store lock held.
void engine_groups_push_all(int *total, int *sent, int *failed);
+24 -1
View File
@@ -23,6 +23,7 @@
#define M_RESYNC 0x23 #define M_RESYNC 0x23
#define M_ECHO 0x24 #define M_ECHO 0x24
#define M_OTA_STATUS 0x26 #define M_OTA_STATUS 0x26
#define M_PING_RSP 0x06
#define F_ACK 1 #define F_ACK 1
#define F_COMMIT 2 #define F_COMMIT 2
#define HDR 9 #define HDR 9
@@ -279,6 +280,13 @@ void rel_set_ota_status_cb(rel_ota_status_cb_t cb)
s_ota_status_cb = cb; s_ota_status_cb = cb;
} }
static rel_ping_cb_t s_ping_cb;
void rel_set_ping_cb(rel_ping_cb_t cb)
{
s_ping_cb = cb;
}
void rel_set_announce_cb(rel_announce_cb_t cb) void rel_set_announce_cb(rel_announce_cb_t cb)
{ {
s_announce_cb = cb; s_announce_cb = cb;
@@ -294,7 +302,8 @@ static void recv_cb(const esp_now_recv_info_t *info, const uint8_t *data, int le
// care about is a link reply inside 0x4C // care about is a link reply inside 0x4C
bool announce = (data[0] == WIRE_MAGIC && data[1] == M_ANNOUNCE) || data[0] == '{'; bool announce = (data[0] == WIRE_MAGIC && data[1] == M_ANNOUNCE) || data[0] == '{';
bool reply = data[0] == WIRE_MAGIC && bool reply = data[0] == WIRE_MAGIC &&
(data[1] == M_ACK || data[1] == M_RESYNC || data[1] == M_ECHO || data[1] == M_OTA_STATUS); (data[1] == M_ACK || data[1] == M_RESYNC || data[1] == M_ECHO || data[1] == M_OTA_STATUS ||
data[1] == M_PING_RSP);
if (!announce && !reply) { if (!announce && !reply) {
return; return;
} }
@@ -332,6 +341,20 @@ static void handle_rx(const rx_t *rx)
} }
return; return;
} }
if (rx->data[1] == M_PING_RSP) {
// The driver is there: count it as heard, so group updates go to it again
xSemaphoreTake(s_lock, portMAX_DELAY);
peer_t *pe = peer_get(rx->mac, true);
if (pe) {
pe->last_ack_us = esp_timer_get_time();
pe->fails = 0;
}
xSemaphoreGive(s_lock);
if (s_ping_cb) {
s_ping_cb(rx->mac, rx->data, rx->len);
}
return;
}
if (rx->len < 10) { // [4C][21][0][seq u16][cnt][mask u32] if (rx->len < 10) { // [4C][21][0][seq u16][cnt][mask u32]
return; return;
} }
+6
View File
@@ -14,6 +14,7 @@
// resync [4C][23][ver u16] (driver -> us) // resync [4C][23][ver u16] (driver -> us)
// echo [4C][24][beat_idx u16] (driver -> us, bench) // echo [4C][24][beat_idx u16] (driver -> us, bench)
// ota [4C][26][sess u16][op][code] + arg (driver -> us, see drv_ota.h) // ota [4C][26][sess u16][op][code] + arg (driver -> us, see drv_ota.h)
// ping [4C][06][ping_id u32][len][name] (driver -> us, reply to [4C][05][ping_id])
#define REL_FRAG_MAX 238 // inner packet bytes per frame; 4C 03/04 wrappers plus an envelope fit in one #define REL_FRAG_MAX 238 // inner packet bytes per frame; 4C 03/04 wrappers plus an envelope fit in one
#define REL_MAX_FRAGS 32 #define REL_MAX_FRAGS 32
@@ -58,6 +59,11 @@ void rel_set_announce_cb(rel_announce_cb_t cb);
// A driver's OTA status reply (0x26), called from the rel task // A driver's OTA status reply (0x26), called from the rel task
typedef void (*rel_ota_status_cb_t)(const uint8_t mac[6], const uint8_t *pkt, int len); typedef void (*rel_ota_status_cb_t)(const uint8_t mac[6], const uint8_t *pkt, int len);
void rel_set_ota_status_cb(rel_ota_status_cb_t cb); void rel_set_ota_status_cb(rel_ota_status_cb_t cb);
// A driver's PING_RSP ([4C][06][ping_id u32][name len][name]), called from the rel task. Drivers
// answer a broadcast PING_REQ ([4C][05][ping_id u32]) after a random 50-500 ms.
typedef void (*rel_ping_cb_t)(const uint8_t mac[6], const uint8_t *pkt, int len);
void rel_set_ping_cb(rel_ping_cb_t cb);
void rel_stats(rel_stats_t *out); void rel_stats(rel_stats_t *out);
// Milliseconds since the driver last acked; -1 if never. fails = consecutive unacked messages // Milliseconds since the driver last acked; -1 if never. fails = consecutive unacked messages
+180
View File
@@ -9,6 +9,9 @@
#include "engine.h" #include "engine.h"
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
#include "esp_random.h"
#include "esp_timer.h"
#include "espnow_tx.h"
#include "rel.h" #include "rel.h"
#include "store.h" #include "store.h"
@@ -289,6 +292,175 @@ static esp_err_t identify(httpd_req_t *req, const cJSON *dev, const char *mac)
return api_message(req, "200 OK", "Identify sent"); return api_message(req, "200 OK", "Identify sent");
} }
/* ------------------------------------------------------------------- ping */
#define PING_MAX 32
typedef struct {
uint8_t mac[6];
char name[33];
int rtt_ms;
} ping_rsp_t;
static struct {
uint32_t id; // 0 = no ping running
int64_t sent_us;
int count;
ping_rsp_t rsp[PING_MAX];
} s_ping;
static portMUX_TYPE s_ping_mux = portMUX_INITIALIZER_UNLOCKED;
// Rel task: [4C][06][ping_id u32 LE][len][name]
static void on_ping_rsp(const uint8_t mac[6], const uint8_t *pkt, int len)
{
if (len < 7) {
return;
}
uint32_t id = pkt[2] | (pkt[3] << 8) | (pkt[4] << 16) | ((uint32_t)pkt[5] << 24);
int nl = pkt[6] < len - 7 ? pkt[6] : len - 7;
int64_t now = esp_timer_get_time();
portENTER_CRITICAL(&s_ping_mux);
if (id && id == s_ping.id && s_ping.count < PING_MAX) {
bool seen = false;
for (int i = 0; i < s_ping.count && !seen; i++) {
seen = !memcmp(s_ping.rsp[i].mac, mac, 6);
}
if (!seen) {
ping_rsp_t *r = &s_ping.rsp[s_ping.count++];
memcpy(r->mac, mac, 6);
nl = nl < (int)sizeof(r->name) - 1 ? nl : (int)sizeof(r->name) - 1;
memcpy(r->name, pkt + 7, nl);
r->name[nl] = 0;
r->rtt_ms = (int)((now - s_ping.sent_us) / 1000);
}
}
portEXIT_CRITICAL(&s_ping_mux);
}
// Add a driver that answered but is not registered yet, or take its new name. True when stored.
static bool register_from_ping(const char *hex, const char *name)
{
char label[48];
snprintf(label, sizeof(label), "%s", name);
if (!label[0]) {
snprintf(label, sizeof(label), "led-%s", hex);
}
cJSON *devs = store_coll("device");
cJSON *rec = cJSON_GetObjectItem(devs, hex);
if (!rec) {
rec = cJSON_AddObjectToObject(devs, hex);
cJSON_AddStringToObject(rec, "id", hex);
cJSON_AddStringToObject(rec, "name", label);
cJSON_AddStringToObject(rec, "type", "led");
cJSON_AddStringToObject(rec, "transport", "espnow");
cJSON_AddStringToObject(rec, "address", hex);
return true;
}
const cJSON *old = cJSON_GetObjectItem(rec, "name");
if (is_espnow(rec) && (!cJSON_IsString(old) || strcmp(old->valuestring, label))) {
api_set(rec, "name", cJSON_CreateString(label));
return true;
}
return false;
}
// POST /devices/ping {timeout_s}: broadcast PING_REQ and collect replies for timeout_s (0.5-30, default 3)
static esp_err_t ping_devices(httpd_req_t *req)
{
static bool hooked; // replies only matter while a ping runs, so the callback is set on first use
if (!hooked) {
rel_set_ping_cb(on_ping_rsp);
hooked = true;
}
cJSON *body = api_body_opt(req);
if (!body) {
return ESP_OK;
}
const cJSON *t = cJSON_GetObjectItem(body, "timeout_s");
if (t && !cJSON_IsNull(t) && !cJSON_IsNumber(t)) {
cJSON_Delete(body);
return api_error(req, "400 Bad Request", "Invalid timeout_s");
}
double timeout_s = cJSON_IsNumber(t) ? t->valuedouble : 3.0;
timeout_s = timeout_s < 0.5 ? 0.5 : (timeout_s > 30 ? 30 : timeout_s);
cJSON_Delete(body);
portENTER_CRITICAL(&s_ping_mux);
bool busy = s_ping.id != 0;
uint32_t id = (esp_random() | 1);
if (!busy) {
s_ping.id = id;
s_ping.count = 0;
s_ping.sent_us = esp_timer_get_time();
}
portEXIT_CRITICAL(&s_ping_mux);
if (busy) {
return api_error(req, "409 Conflict", "a ping is already running");
}
uint8_t pkt[6] = { 0x4C, 0x05, id & 255, (id >> 8) & 255, (id >> 16) & 255, id >> 24 };
esp_err_t err = espnow_tx_send(NULL, pkt, sizeof(pkt));
vTaskDelay(pdMS_TO_TICKS(20));
espnow_tx_send(NULL, pkt, sizeof(pkt)); // a second copy against a lost broadcast; replies are deduplicated
if (err == ESP_OK) {
store_unlock(); // replies take up to timeout_s; HTTP and the sequencer keep going
vTaskDelay(pdMS_TO_TICKS((int)(timeout_s * 1000)));
store_lock();
}
static ping_rsp_t got[PING_MAX];
portENTER_CRITICAL(&s_ping_mux);
int n = s_ping.count;
memcpy(got, s_ping.rsp, n * sizeof(got[0]));
s_ping.id = 0;
portEXIT_CRITICAL(&s_ping_mux);
if (err != ESP_OK) {
return api_error(req, "503 Service Unavailable", "Send failed");
}
cJSON *o = cJSON_CreateObject(), *responses;
cJSON_AddTrueToObject(o, "ok");
cJSON_AddNumberToObject(o, "ping_id", id);
cJSON_AddNumberToObject(o, "timeout_s", timeout_s);
responses = cJSON_AddObjectToObject(o, "responses");
int registered = 0;
for (int i = 0; i < n; i++) {
char hex[13];
const uint8_t *m = got[i].mac;
snprintf(hex, sizeof(hex), "%02x%02x%02x%02x%02x%02x", m[0], m[1], m[2], m[3], m[4], m[5]);
cJSON *r = cJSON_AddObjectToObject(responses, hex);
cJSON_AddStringToObject(r, "mac", hex);
cJSON_AddStringToObject(r, "name", got[i].name);
cJSON_AddNumberToObject(r, "rtt_ms", got[i].rtt_ms);
registered += register_from_ping(hex, got[i].name);
}
cJSON_AddNumberToObject(o, "registered", registered);
if (registered) {
store_save("device");
engine_groups_changed();
}
return api_json(req, "200 OK", o, true);
}
// POST /devices/groups: push group membership to every ESP-NOW driver and report the acks
static esp_err_t push_groups(httpd_req_t *req)
{
int total, sent, failed;
store_unlock(); // waits up to a few seconds for acks
engine_groups_push_all(&total, &sent, &failed);
store_lock();
if (!total) {
cJSON *o = cJSON_CreateObject();
cJSON_AddFalseToObject(o, "ok");
cJSON_AddStringToObject(o, "error", "No ESP-NOW devices in registry");
return api_json(req, "400 Bad Request", o, true);
}
cJSON *o = cJSON_CreateObject();
cJSON_AddBoolToObject(o, "ok", failed == 0);
cJSON_AddNumberToObject(o, "total", total);
cJSON_AddNumberToObject(o, "sent", sent);
cJSON_AddNumberToObject(o, "failed", failed);
return api_json(req, failed ? "503 Service Unavailable" : "200 OK", o, true);
}
// Per-driver delivery health from the acked link // Per-driver delivery health from the acked link
static esp_err_t device_status(httpd_req_t *req) static esp_err_t device_status(httpd_req_t *req)
{ {
@@ -321,6 +493,14 @@ bool devices_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret)
*ret = device_status(req); *ret = device_status(req);
return true; return true;
} }
if (n == 2 && method == HTTP_POST && !strcmp(seg[1], "ping")) {
*ret = ping_devices(req);
return true;
}
if (n == 2 && method == HTTP_POST && !strcmp(seg[1], "groups")) {
*ret = push_groups(req);
return true;
}
if (n == 1) { if (n == 1) {
if (method == HTTP_GET) { if (method == HTTP_GET) {
cJSON *o = cJSON_CreateObject(), *d; cJSON *o = cJSON_CreateObject(), *d;
+27 -6
View File
@@ -1,8 +1,10 @@
#include "web.h" #include "web.h"
#include <stddef.h> #include <stddef.h>
#include <stdio.h>
#include <stdint.h> #include <stdint.h>
#include <string.h> #include <string.h>
#include "esp_app_desc.h"
#include "esp_log.h" #include "esp_log.h"
static const char *TAG = "web"; static const char *TAG = "web";
@@ -98,8 +100,21 @@ void web_each(const char *prefix, void (*fn)(const char *name, void *ctx), void
} }
} }
// Every file changes only with the firmware, so the build's hash is the ETag: browsers revalidate on
// each load (no-cache) and get a 304 until the next update, instead of running a stale UI for a day.
static const char *etag(void)
{
static char tag[20];
if (!tag[0]) {
const uint8_t *sha = esp_app_get_description()->app_elf_sha256;
snprintf(tag, sizeof(tag), "\"%02x%02x%02x%02x%02x%02x%02x%02x\"", sha[0], sha[1], sha[2], sha[3], sha[4], sha[5],
sha[6], sha[7]);
}
return tag;
}
// path is the URL-relative name, e.g. "static/zones.js" // path is the URL-relative name, e.g. "static/zones.js"
static esp_err_t send_gz(httpd_req_t *req, const char *path, bool immutable) static esp_err_t send_gz(httpd_req_t *req, const char *path)
{ {
const uint8_t *data; const uint8_t *data;
uint32_t len; uint32_t len;
@@ -109,25 +124,31 @@ static esp_err_t send_gz(httpd_req_t *req, const char *path, bool immutable)
if (!find_file(path, &data, &len)) { if (!find_file(path, &data, &len)) {
return httpd_resp_send_404(req); return httpd_resp_send_404(req);
} }
httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
httpd_resp_set_hdr(req, "ETag", etag());
char inm[24];
if (httpd_req_get_hdr_value_str(req, "If-None-Match", inm, sizeof(inm)) == ESP_OK && !strcmp(inm, etag())) {
httpd_resp_set_status(req, "304 Not Modified");
return httpd_resp_send(req, NULL, 0);
}
httpd_resp_set_type(req, mime_for(path)); httpd_resp_set_type(req, mime_for(path));
httpd_resp_set_hdr(req, "Content-Encoding", "gzip"); httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
httpd_resp_set_hdr(req, "Cache-Control", immutable ? "public, max-age=86400" : "no-cache");
return httpd_resp_send(req, (const char *)data, len); return httpd_resp_send(req, (const char *)data, len);
} }
esp_err_t web_send_page(httpd_req_t *req, const char *name) esp_err_t web_send_page(httpd_req_t *req, const char *name)
{ {
return send_gz(req, name, false); return send_gz(req, name);
} }
static esp_err_t index_handler(httpd_req_t *req) static esp_err_t index_handler(httpd_req_t *req)
{ {
return send_gz(req, "index.html", false); return send_gz(req, "index.html");
} }
static esp_err_t audio_page_handler(httpd_req_t *req) static esp_err_t audio_page_handler(httpd_req_t *req)
{ {
return send_gz(req, "audio.html", false); return send_gz(req, "audio.html");
} }
static esp_err_t static_handler(httpd_req_t *req) static esp_err_t static_handler(httpd_req_t *req)
@@ -140,7 +161,7 @@ static esp_err_t static_handler(httpd_req_t *req)
} }
memcpy(path, uri, n); memcpy(path, uri, n);
path[n] = 0; path[n] = 0;
return send_gz(req, path, true); return send_gz(req, path);
} }
static esp_err_t favicon_handler(httpd_req_t *req) static esp_err_t favicon_handler(httpd_req_t *req)
+28
View File
@@ -118,3 +118,31 @@ def test_status(c):
def test_delete(c, espnow_dev): def test_delete(c, espnow_dev):
assert c.delete(f"/devices/{ESPNOW_MAC}").status_code == 200 assert c.delete(f"/devices/{ESPNOW_MAC}").status_code == 200
assert c.get(f"/devices/{ESPNOW_MAC}").status_code == 404 assert c.get(f"/devices/{ESPNOW_MAC}").status_code == 404
def test_ping(c):
resp = c.post("/devices/ping", json={"timeout_s": 0.5})
assert resp.status_code == 200
data = resp.json()
assert data["ok"] is True
assert data["timeout_s"] == 0.5
assert isinstance(data["responses"], dict)
for mac, info in data["responses"].items():
assert info["mac"] == mac and "name" in info and info["rtt_ms"] >= 0
assert mac in c.get("/devices").json() # repliers are registered
def test_ping_rejects_bad_timeout(c):
assert c.post("/devices/ping", json={"timeout_s": "soon"}).status_code == 400
def test_update_groups(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"]
assert resp.status_code == (200 if data["failed"] == 0 else 503)
+212 -10
View File
@@ -18,6 +18,15 @@ const DEVICES_MODAL_POLL_MS = 1000;
let devicesModalLiveTimer = null; let devicesModalLiveTimer = null;
/** Last ESP-NOW ping result per MAC (hex, no separators). Cleared only when a new ping marks offline. */
const espnowPingStatusByMac = new Map();
/** Aggregate ping dot state (Devices / Settings ping buttons). */
let lastEspnowPingAggregate = {
state: 'unknown',
title: 'Not pinged yet',
};
function stopDevicesModalLiveRefresh() { function stopDevicesModalLiveRefresh() {
if (devicesModalLiveTimer != null) { if (devicesModalLiveTimer != null) {
clearInterval(devicesModalLiveTimer); clearInterval(devicesModalLiveTimer);
@@ -53,11 +62,189 @@ function startDevicesModalLiveRefresh() {
}, DEVICES_MODAL_POLL_MS); }, DEVICES_MODAL_POLL_MS);
} }
const DEVICE_DOT_CLASSES = [
'device-status-dot--online',
'device-status-dot--offline',
'device-status-dot--unknown',
'device-status-dot--pinging',
];
function normalizeDeviceMacKey(mac) {
return String(mac || '')
.trim()
.toLowerCase()
.replace(/[:-]/g, '');
}
function findPingResponse(responses, deviceId) {
if (!responses || typeof responses !== 'object') return null;
const want = normalizeDeviceMacKey(deviceId);
for (const [mac, info] of Object.entries(responses)) {
if (normalizeDeviceMacKey(mac) === want) return info;
}
return null;
}
function setDeviceStatusDot(dot, state, title) {
if (!dot) return;
dot.classList.remove(...DEVICE_DOT_CLASSES);
if (state === 'online') dot.classList.add('device-status-dot--online');
else if (state === 'offline') dot.classList.add('device-status-dot--offline');
else if (state === 'pinging') dot.classList.add('device-status-dot--pinging');
else dot.classList.add('device-status-dot--unknown');
dot.title = title;
dot.setAttribute('aria-label', title);
}
function updatePingStatusDot(dotEl, state, title) {
if (!dotEl) return;
dotEl.classList.remove(...DEVICE_DOT_CLASSES);
if (state === 'online') dotEl.classList.add('device-status-dot--online');
else if (state === 'offline') dotEl.classList.add('device-status-dot--offline');
else if (state === 'pinging') dotEl.classList.add('device-status-dot--pinging');
else dotEl.classList.add('device-status-dot--unknown');
dotEl.title = title;
dotEl.setAttribute('aria-label', title);
}
function rememberEspnowPingAggregate(state, title) {
lastEspnowPingAggregate = { state, title };
}
function applyEspnowPingAggregateToDots() {
for (const id of ['devices-ping-dot']) {
updatePingStatusDot(document.getElementById(id), lastEspnowPingAggregate.state, lastEspnowPingAggregate.title);
}
}
async function runUpdateGroups(btn) {
const statusEl = document.getElementById('devices-groups-status');
const prevLabel = btn ? btn.textContent : '';
if (btn) {
btn.disabled = true;
btn.textContent = 'Updating…';
}
if (statusEl) statusEl.textContent = 'Sending group membership…';
try {
const res = await fetch('/devices/groups', {
method: 'POST',
headers: { Accept: 'application/json' },
});
const data = await res.json().catch(() => ({}));
if (!res.ok || !data.ok) {
const err = data.error || 'Update groups failed';
if (statusEl) statusEl.textContent = err;
return;
}
const sent = Number(data.sent) || 0;
const failed = Number(data.failed) || 0;
if (statusEl) {
statusEl.textContent =
failed > 0
? `Sent to ${sent} driver${sent === 1 ? '' : 's'}, ${failed} failed`
: `Sent to ${sent} driver${sent === 1 ? '' : 's'}`;
}
} catch (error) {
if (statusEl) statusEl.textContent = error.message;
} finally {
if (btn) {
btn.disabled = false;
btn.textContent = prevLabel;
}
}
}
async function runEspnowPing({ btn, dot, statusEl } = {}) {
const prevLabel = btn ? btn.textContent : '';
if (btn) {
btn.disabled = true;
btn.textContent = 'Pinging…';
}
updatePingStatusDot(dot, 'pinging', 'Ping in progress…');
if (statusEl) statusEl.textContent = 'Waiting for replies (3 s)…';
applyEspnowPingToDeviceRows(null, 'pinging');
try {
const res = await fetch('/devices/ping', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ timeout_s: 3 }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok || !data.ok) {
const err = data.error || 'Ping failed';
rememberEspnowPingAggregate('offline', err);
updatePingStatusDot(dot, 'offline', err);
applyEspnowPingAggregateToDots();
if (statusEl) statusEl.textContent = err;
return;
}
const count = Object.keys(data.responses || {}).length;
const registered = Number(data.registered) || 0;
const aggState = count > 0 ? 'online' : 'offline';
const aggTitle =
count > 0
? `${count} driver${count === 1 ? '' : 's'} replied`
: 'No drivers replied';
rememberEspnowPingAggregate(aggState, aggTitle);
updatePingStatusDot(dot, aggState, aggTitle);
applyEspnowPingAggregateToDots();
if (statusEl) {
let msg = `${count} response${count === 1 ? '' : 's'}`;
if (registered > 0) {
msg += ` · ${registered} new in list`;
}
statusEl.textContent = msg;
}
await refreshDevicesListQuiet();
applyEspnowPingToDeviceRows(data.responses, 'done');
} catch (error) {
const msg = `Error: ${error.message}`;
rememberEspnowPingAggregate('offline', msg);
updatePingStatusDot(dot, 'offline', msg);
applyEspnowPingAggregateToDots();
if (statusEl) statusEl.textContent = error.message;
} finally {
if (btn) {
btn.disabled = false;
btn.textContent = prevLabel;
}
}
}
function applyEspnowPingToDeviceRows(responses, phase) {
const container = document.getElementById('devices-list-modal');
if (!container) return;
container.querySelectorAll('.profiles-row[data-device-transport="espnow"]').forEach((row) => {
const dot = row.querySelector('.device-status-dot');
if (!dot) return;
if (phase === 'pinging') {
setDeviceStatusDot(dot, 'pinging', 'Ping in progress…');
return;
}
const macKey = normalizeDeviceMacKey(row.dataset.deviceId);
const info = findPingResponse(responses, row.dataset.deviceId);
if (info) {
const rtt = info.rtt_ms != null ? `${info.rtt_ms} ms` : 'ok';
const title = `Ping reply (${rtt})`;
setDeviceStatusDot(dot, 'online', title);
espnowPingStatusByMac.set(macKey, { state: 'online', title });
} else {
const title = 'No ping reply';
setDeviceStatusDot(dot, 'offline', title);
espnowPingStatusByMac.set(macKey, { state: 'offline', title });
}
});
}
function espnowPingStatusForMac(devId) {
return espnowPingStatusByMac.get(normalizeDeviceMacKey(devId)) || null;
}
function updateWifiRowDot(row, connected) { function updateWifiRowDot(row, connected) {
const dot = row.querySelector('.device-status-dot'); const dot = row.querySelector('.device-status-dot');
if (!dot) return; if (!dot) return;
if ((row.dataset.deviceTransport || '') !== 'wifi') return; if ((row.dataset.deviceTransport || '') !== 'wifi') return;
dot.classList.remove('device-status-dot--online', 'device-status-dot--offline', 'device-status-dot--unknown'); dot.classList.remove(...DEVICE_DOT_CLASSES);
if (connected) { if (connected) {
dot.classList.add('device-status-dot--online'); dot.classList.add('device-status-dot--online');
dot.title = 'Connected (Wi-Fi TCP session)'; dot.title = 'Connected (Wi-Fi TCP session)';
@@ -218,17 +405,16 @@ function renderDevicesList(devices) {
dot.setAttribute('role', 'img'); dot.setAttribute('role', 'img');
const live = dev && Object.prototype.hasOwnProperty.call(dev, 'connected') ? dev.connected : null; const live = dev && Object.prototype.hasOwnProperty.call(dev, 'connected') ? dev.connected : null;
if (live === true) { if (live === true) {
dot.classList.add('device-status-dot--online'); setDeviceStatusDot(dot, 'online', 'Connected (Wi-Fi TCP session)');
dot.title = 'Connected (Wi-Fi TCP session)';
dot.setAttribute('aria-label', dot.title);
} else if (live === false) { } else if (live === false) {
dot.classList.add('device-status-dot--offline'); setDeviceStatusDot(dot, 'offline', 'Not connected (no Wi-Fi TCP session)');
dot.title = 'Not connected (no Wi-Fi TCP session)';
dot.setAttribute('aria-label', dot.title);
} else { } else {
dot.classList.add('device-status-dot--unknown'); const pingCached = espnowPingStatusForMac(devId);
dot.title = 'ESP-NOW — TCP status does not apply'; if (pingCached) {
dot.setAttribute('aria-label', dot.title); setDeviceStatusDot(dot, pingCached.state, pingCached.title);
} else {
setDeviceStatusDot(dot, 'unknown', 'ESP-NOW — ping or identify to test reachability');
}
} }
const label = document.createElement('span'); const label = document.createElement('span');
@@ -434,6 +620,22 @@ document.addEventListener('DOMContentLoaded', () => {
}); });
} }
const devicesPingBtn = document.getElementById('devices-ping-btn');
if (devicesPingBtn) {
devicesPingBtn.addEventListener('click', () => {
runEspnowPing({
btn: devicesPingBtn,
dot: document.getElementById('devices-ping-dot'),
statusEl: document.getElementById('devices-ping-status'),
});
});
}
const devicesUpdateGroupsBtn = document.getElementById('devices-update-groups-btn');
if (devicesUpdateGroupsBtn) {
devicesUpdateGroupsBtn.addEventListener('click', () => runUpdateGroups(devicesUpdateGroupsBtn));
}
const devicesModalEl = document.getElementById('devices-modal'); const devicesModalEl = document.getElementById('devices-modal');
if (devicesModalEl) { if (devicesModalEl) {
new MutationObserver(() => { new MutationObserver(() => {
+6 -1
View File
@@ -654,7 +654,7 @@ body.preset-ui-run .edit-mode-only {
color: #f44336; color: #f44336;
} }
/* Devices modal: live TCP presence (Wi-Fi only) */ /* Devices modal: Wi-Fi TCP presence, ESP-NOW ping results */
.device-status-dot { .device-status-dot {
width: 10px; width: 10px;
height: 10px; height: 10px;
@@ -677,6 +677,11 @@ body.preset-ui-run .edit-mode-only {
border: 1px solid #757575; border: 1px solid #757575;
} }
.device-status-dot--pinging {
background: #ffb300;
box-shadow: 0 0 6px rgba(255, 179, 0, 0.45);
}
.btn-group { .btn-group {
display: flex; display: flex;
gap: 0.5rem; gap: 0.5rem;
+6 -1
View File
@@ -133,7 +133,12 @@
<h2>Devices</h2> <h2>Devices</h2>
<input type="search" id="devices-search" class="list-search-input" placeholder="Search devices…" autocomplete="off"> <input type="search" id="devices-search" class="list-search-input" placeholder="Search devices…" autocomplete="off">
<div id="devices-list-modal" class="profiles-list"></div> <div id="devices-list-modal" class="profiles-list"></div>
<div class="modal-actions"> <div class="modal-actions" style="align-items:center;gap:0.75rem;flex-wrap:wrap;">
<button type="button" class="btn btn-secondary" id="devices-ping-btn" title="ESP-NOW broadcast ping (3 s)">Ping drivers</button>
<span id="devices-ping-dot" class="device-status-dot device-status-dot--unknown" role="img" title="Not pinged yet" aria-label="Not pinged yet"></span>
<span id="devices-ping-status" class="muted-text" aria-live="polite"></span>
<button type="button" class="btn btn-secondary" id="devices-update-groups-btn" title="Push group membership to all ESP-NOW drivers">Update groups</button>
<span id="devices-groups-status" class="muted-text" aria-live="polite"></span>
<button type="button" class="btn btn-secondary" id="devices-close-btn">Close</button> <button type="button" class="btn btn-secondary" id="devices-close-btn">Close</button>
</div> </div>
</div> </div>