feat: browser simulator served by the controller, desktop build, browser bridge

- led-simulator: the rig runs the C++ led-driver as WebAssembly (sim-driver/),
  one single-threaded worker per bar, no cross-origin isolation needed. Rooms
  (one JSON per room) with an on-page editor, and a pattern gallery. The
  Python server, Pyodide boot and ring buffer are removed.
- sim-controller sim_rig.c: serves /sim/ from an embedded pack, the page's
  WebSocket and the rooms/flash API. The desktop build embeds it too.
- bridge.c: a "browser" bridge kind that carries ESP-NOW frames to the page;
  devices announced through it are marked sim.
- UI: Simulator in the Menu, split view with resize and pop-out, swipe
  between controller and rig on phones; SIM/REAL badges in Devices.
- Fades: preset pushes and Wi-Fi driver bodies always carry fade and
  beat_time, so "off" no longer inherits an earlier fade.
- Also the sequences-v2 work in progress: desktop port, bridge firmware,
  serial bridge, Wi-Fi drivers, sequence timeline, audio and API changes.
- led-driver: ESP-NOW link, beat sync, control messages, sim hooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-11-16 19:32:46 +13:00
1 parent 698c1463c0
commit 581b751904
506 files changed
+42336 -3599

No files matched your search

+6 -6
View File
@@ -2,17 +2,17 @@ if(IDF_TARGET STREQUAL "linux")
# Host build for led-simulator (sim-controller/): no Ethernet, Wi-Fi, mic or OTA. The sim
# component has app_main and stands in for main.c, mic.c and ota.c.
idf_component_register(SRCS "beat.c" "beat_dsp.c" "espnow_tx.c" "bridge.c" "store.c" "api.c" "web.c" "envelope.c" "engine.c" "rel.c" "bench.c" "audio.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 "." "../sim-controller/components/sim/include"
REQUIRES esp_http_server esp_timer esp_event json
"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" "ws_client.c" "wifi_drv.c" "bridge_serial.c"
INCLUDE_DIRS "." "../sim-controller/components/sim/include" "../bridge/main"
REQUIRES esp_http_server esp_timer esp_event cjson
PRIV_REQUIRES mbedtls lwip esp_app_format)
else()
idf_component_register(SRCS "main.c" "mic.c" "beat.c" "beat_dsp.c" "espnow_tx.c" "bridge.c" "store.c" "api.c" "web.c" "envelope.c" "engine.c" "rel.c" "bench.c" "audio.c" "ota.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"
"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" "ws_client.c" "wifi_drv.c"
INCLUDE_DIRS "."
REQUIRES esp_eth esp_netif esp_event esp_driver_spi esp_driver_gpio nvs_flash app_update esp_app_format
esp_http_server esp_timer esp_driver_i2s esp_wifi esp_rom json esp_driver_gpio
PRIV_REQUIRES littlefs mdns mbedtls lwip)
esp_http_server esp_timer esp_driver_i2s esp_wifi esp_rom cjson esp_driver_gpio
PRIV_REQUIRES littlefs mdns mbedtls lwip w5500)
endif()
# The gzipped web UI is embedded in the app image (run tools/build_web.sh first)
+121
View File
@@ -8,7 +8,10 @@
#include "cJSON.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "bench.h"
#include "bridge.h"
#include "engine.h"
#include "espnow_tx.h"
#include "sdkconfig.h"
@@ -408,6 +411,10 @@ static esp_err_t put_settings(httpd_req_t *req)
if (!bad && br && !cJSON_IsNull(br) && !(cJSON_IsString(br) && strlen(br->valuestring) < 64)) {
bad = "bridge must be \"host:port\", empty or null";
}
const cJSON *brs = cJSON_GetObjectItem(body, "bridges");
if (!bad && brs && !cJSON_IsNull(brs) && !(cJSON_IsArray(brs) && cJSON_GetArraySize(brs) <= BRIDGE_MAX_LINKS)) {
bad = "bridges must be a list of up to 8 addresses";
}
const cJSON *sw = cJSON_GetObjectItem(body, "sequence_switch_wait");
if (!bad && sw && !cJSON_IsNull(sw) &&
!(cJSON_IsString(sw) && (!strcasecmp(sw->valuestring, "beat") || !strcasecmp(sw->valuestring, "downbeat")))) {
@@ -430,6 +437,114 @@ static esp_err_t put_settings(httpd_req_t *req)
return api_message(req, "200 OK", "Settings updated successfully");
}
// The bridges the controller sends its ESP-NOW frames to (USB boards, network boards, the simulator).
// GET /settings/bridge: {supported, bridges: [{addr, kind, status}], ports}.
// PUT /settings/bridge: {bridges: [addr, ...]} sets the whole list; {addr, channel} sets a board's channel.
// Both apply at once on the host; a device reads the list at the next restart.
static esp_err_t bridge_get(httpd_req_t *req)
{
char links[1536], ports[512];
bridge_status_json(links, sizeof(links));
bridge_ports_json(ports, sizeof(ports));
cJSON *out = cJSON_CreateObject();
#if CONFIG_IDF_TARGET_LINUX
cJSON_AddBoolToObject(out, "supported", true);
#else
cJSON_AddBoolToObject(out, "supported", false);
#endif
cJSON_AddItemToObject(out, "bridges", cJSON_Parse(links));
cJSON_AddItemToObject(out, "ports", cJSON_Parse(ports));
return api_json(req, "200 OK", out, true);
}
// Save the list the running bridges actually have (a bridge that failed to open is not kept)
static void bridge_store(void)
{
char addrs[BRIDGE_MAX_LINKS][BRIDGE_ADDR_MAX];
size_t n = bridge_list(addrs, BRIDGE_MAX_LINKS);
cJSON *list = cJSON_CreateArray();
for (size_t i = 0; i < n; i++) {
cJSON_AddItemToArray(list, cJSON_CreateString(addrs[i]));
}
cJSON *patch = cJSON_CreateObject();
cJSON_AddItemToObject(patch, "bridges", list);
cJSON_AddStringToObject(patch, "bridge", n ? addrs[0] : "");
api_merge(store_settings(), patch);
cJSON_Delete(patch);
store_save("settings");
}
static esp_err_t bridge_put(httpd_req_t *req)
{
#if !CONFIG_IDF_TARGET_LINUX
return api_error(req, "404 Not Found", "the bridges are set in the controller settings on this build");
#endif
cJSON *body = api_body(req);
if (!body) {
return ESP_OK;
}
const cJSON *list = cJSON_GetObjectItem(body, "bridges");
const cJSON *addr = cJSON_GetObjectItem(body, "addr");
const cJSON *ch = cJSON_GetObjectItem(body, "channel");
const char *bad = NULL;
if (!list && !(addr && ch)) {
bad = "send bridges (a list), or addr and channel";
} else if (list && !cJSON_IsArray(list)) {
bad = "bridges must be a list of addresses";
} else if (list && cJSON_GetArraySize(list) > BRIDGE_MAX_LINKS) {
bad = "too many bridges";
} else if (addr && !cJSON_IsString(addr)) {
bad = "addr must be a board port (/dev/...) or host:port";
} else if (ch && !(cJSON_IsNumber(ch) && ch->valueint >= 1 && ch->valueint <= 13)) {
bad = "channel must be 1 to 13";
}
const cJSON *item = NULL;
if (!bad && list) {
cJSON_ArrayForEach(item, list) {
if (!cJSON_IsString(item) || strlen(item->valuestring) >= BRIDGE_ADDR_MAX) {
bad = "each bridge must be a board port (/dev/...), host:port or serial:/dev/...";
}
}
}
if (bad) {
cJSON_Delete(body);
return api_error(req, "400 Bad Request", bad);
}
if (list) {
char addrs[BRIDGE_MAX_LINKS][BRIDGE_ADDR_MAX];
size_t n = 0;
cJSON_ArrayForEach(item, list) {
snprintf(addrs[n], BRIDGE_ADDR_MAX, "%s", item->valuestring);
n++;
}
esp_err_t err = espnow_tx_change_bridges(addrs, n);
bridge_store();
if (err != ESP_OK) {
cJSON_Delete(body);
return api_error(req, "400 Bad Request", "one of the bridges could not be opened (the others are running)");
}
}
if (addr && ch) {
// A board just switched in answers its INFO a moment later: wait up to 3 s for it before giving up
esp_err_t err = ESP_OK;
for (int tries = 0; tries < 30; tries++) {
err = bridge_board_set_channel(addr->valuestring, (uint8_t)ch->valueint);
if (err != ESP_ERR_INVALID_STATE) {
break;
}
vTaskDelay(pdMS_TO_TICKS(100));
}
if (err != ESP_OK) {
cJSON_Delete(body);
return api_error(req, "400 Bad Request",
err == ESP_ERR_INVALID_STATE ? "the board did not answer, so its channel was not set"
: "no running bridge board has that address");
}
}
cJSON_Delete(body);
return api_message(req, "200 OK", "Bridges updated");
}
static esp_err_t settings_handler_inner(httpd_req_t *req)
{
api_seg_t seg;
@@ -443,6 +558,12 @@ static esp_err_t settings_handler_inner(httpd_req_t *req)
if (n == 1 && req->method == HTTP_GET) {
return api_json(req, "200 OK", store_settings(), false);
}
if (n == 2 && strcmp(seg[1], "bridge") == 0 && req->method == HTTP_GET) {
return bridge_get(req);
}
if (n == 2 && strcmp(seg[1], "bridge") == 0 && req->method == HTTP_PUT) {
return bridge_put(req);
}
if (req->method == HTTP_PUT && (n == 1 || (n == 2 && strcmp(seg[1], "settings") == 0))) {
return put_settings(req);
}
+2
View File
@@ -62,6 +62,8 @@ void api_seed_defaults(void);
// A new group with the defaults, saved; its id in id
void api_add_group(const char *name, char *id, size_t len);
void api_migrate_zones(void);
// Move a zone's older animation_ids into sequence_ids (one-shots and looping sequences sit together)
bool api_zone_fold_oneshots(cJSON *z);
void api_migrate_groups(void);
// Resource handlers, called with the store locked. Each returns true when it answered the request
+73
View File
@@ -32,6 +32,27 @@ static int setting_int(const char *key, int dflt, int lo, int hi)
return x < lo ? lo : (x > hi ? hi : x);
}
#ifdef LED_DESKTOP_ALSA
// Desktop: the microphone reads the device chosen in the settings while audio is running
static void mic_follow_setting(bool start)
{
if (!start) {
mic_close();
return;
}
char dev[128] = "";
store_lock();
const cJSON *sel = cJSON_GetObjectItem(store_settings(), "audio_device_select");
if (cJSON_IsString(sel) && strlen(sel->valuestring) < sizeof(dev)) {
strcpy(dev, sel->valuestring);
}
store_unlock();
if (mic_open(dev) != ESP_OK) {
ESP_LOGW(TAG, "cannot use audio device \"%s\"", dev);
}
}
#endif
static cJSON *audio_run(void)
{
cJSON *o = cJSON_CreateObject();
@@ -57,8 +78,23 @@ static cJSON *status_payload(void)
store_lock();
int sim_bpm = setting_int("audio_simulated_bpm", 120, 60, 200);
cJSON_AddBoolToObject(o, "running", running);
#ifdef LED_DESKTOP_ALSA
const cJSON *dev = cJSON_GetObjectItem(store_settings(), "audio_device_select");
cJSON_AddStringToObject(o, "device", cJSON_IsString(dev) ? dev->valuestring : "");
#else
cJSON_AddStringToObject(o, "device", "i2s");
#endif
#ifdef LED_DESKTOP_ALSA
char mic_err[160];
mic_error(mic_err, sizeof(mic_err));
if (mic_err[0]) {
cJSON_AddStringToObject(o, "error", mic_err);
} else {
cJSON_AddNullToObject(o, "error");
}
#else
cJSON_AddNullToObject(o, "error");
#endif
if (!running) {
cJSON_AddNumberToObject(o, "bpm", sim_bpm);
} else if (bi.locked && bi.bpm > 0) {
@@ -238,6 +274,23 @@ static esp_err_t audio_handler(httpd_req_t *req)
if (req->method == HTTP_GET && !strcmp(act, "events")) {
return events(req);
}
#ifdef LED_DESKTOP_ALSA
if (req->method == HTTP_GET && !strcmp(act, "devices")) {
cJSON *o = cJSON_CreateObject(), *devs = cJSON_AddArrayToObject(o, "devices");
mic_device_t found[16];
int n = mic_list_devices(found, 16);
for (int i = 0; i < n; i++) {
cJSON *d = cJSON_CreateObject();
cJSON_AddStringToObject(d, "id", found[i].id);
cJSON_AddStringToObject(d, "name", found[i].name);
cJSON_AddStringToObject(d, "display_name", found[i].name);
cJSON_AddStringToObject(d, "label", found[i].label);
cJSON_AddItemToArray(devs, d);
}
cJSON_AddObjectToObject(o, "diagnostics");
return send_json(req, "200 OK", o);
}
#endif
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");
@@ -257,10 +310,18 @@ static esp_err_t audio_handler(httpd_req_t *req)
store_lock();
api_set(store_settings(), "audio_device_select", cJSON_CreateString(cJSON_IsString(sel) ? sel->valuestring : ""));
store_save("settings");
#ifdef LED_DESKTOP_ALSA
bool reopen = mic_is_open(); // switch a running detector to the new device, after the store unlock
#endif
cJSON *o = cJSON_CreateObject();
cJSON_AddTrueToObject(o, "ok");
cJSON_AddItemToObject(o, "audio_run", audio_run());
store_unlock();
#ifdef LED_DESKTOP_ALSA
if (reopen) {
mic_follow_setting(true);
}
#endif
cJSON_Delete(body);
return send_json(req, "200 OK", o);
}
@@ -269,6 +330,9 @@ static esp_err_t audio_handler(httpd_req_t *req)
}
if (!strcmp(act, "start") || !strcmp(act, "stop")) {
seqplay_set_audio(act[2] == 'a'); // st[a]rt
#ifdef LED_DESKTOP_ALSA
mic_follow_setting(act[2] == 'a');
#endif
ESP_LOGI(TAG, "mic beats %s sequences", act[2] == 'a' ? "time" : "no longer time");
return ok_with_status(req);
}
@@ -289,6 +353,15 @@ static esp_err_t audio_handler(httpd_req_t *req)
return httpd_resp_send_404(req);
}
#ifdef LED_DESKTOP_ALSA
void audio_api_resume_mic(void)
{
if (seqplay_audio()) {
mic_follow_setting(true);
}
}
#endif
esp_err_t audio_api_register(httpd_handle_t server)
{
static const httpd_method_t METHODS[] = { HTTP_GET, HTTP_POST, HTTP_PUT };
+4
View File
@@ -5,3 +5,7 @@
// /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);
#ifdef LED_DESKTOP_ALSA
// Desktop: after seqplay_init, open the saved input if audio was left running
void audio_api_resume_mic(void);
#endif
+610 -38
View File
@@ -4,96 +4,668 @@
#include <stdlib.h>
#include <string.h>
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "lwip/netdb.h"
#include "lwip/sockets.h"
#include "sdkconfig.h"
#include "bridge_proto.h"
#if CONFIG_IDF_TARGET_LINUX
#include "bridge_serial.h"
#endif
static const char *TAG = "bridge";
static int s_sock = -1;
static struct sockaddr_in s_peer;
// One running bridge. A slot keeps its UDP tasks once it has them; closing only clears used.
typedef struct {
bool used;
bool serial; // a USB board (bridge_serial), else UDP
bool browser; // the rig page of the host build (sim_rig.c), over its WebSocket
char addr[BRIDGE_ADDR_MAX]; // as the settings store it
bridge_serial_t *board; // serial: the board (linux)
int sock; // UDP data socket (port), -1 when closed
int ctl; // UDP control socket (port + 1): HELLO/INFO and microphone audio
bool rx_task, ctl_task; // this slot's receive tasks exist
uint32_t tx, rx, audio; // UDP datagrams sent, received, and audio datagrams received
// from the control port: the board's INFO, and when it last answered
bool linked;
int64_t seen_ms;
uint8_t mac[6], channel, caps, ip[4];
} link_t;
static link_t s_links[BRIDGE_MAX_LINKS];
static SemaphoreHandle_t s_lock;
static bridge_rx_cb_t s_cb;
static char s_addr[80];
static bridge_audio_cb_t s_audio_cb;
static int s_mic_slot = -1; // the UDP board recording (-1: none)
// Frames heard by more than one bridge arrive once: a frame seen again within DEDUPE_MS is dropped
#define DEDUPE_MS 300
#define DEDUPE_LEN 64
#define CTL_TIMEOUT_MS 3000
static struct {
uint32_t hash;
int64_t ms;
} s_seen[DEDUPE_LEN];
static unsigned s_seen_next;
// MACs whose frames came in on the browser bridge: the simulated drivers of the rig page
#define BROWSER_MACS_MAX 64
static uint8_t s_browser_macs[BROWSER_MACS_MAX][6];
static int s_n_browser_macs;
static bool is_serial_addr(const char *addr)
{
return strncmp(addr, "/dev/", 5) == 0 || strncmp(addr, "serial:", 7) == 0;
}
static bool is_browser_addr(const char *addr)
{
return strcmp(addr, BRIDGE_BROWSER) == 0;
}
#if CONFIG_IDF_TARGET_LINUX
// The rig page's link (sim-controller/components/sim/sim_rig.c): dst_mac(6) + packet to the page, if it is open
bool sim_rig_tx(const uint8_t *frame, size_t len);
bool sim_rig_page_open(void);
#endif
static int64_t now_ms(void)
{
return esp_timer_get_time() / 1000;
}
static uint32_t fnv1a(const uint8_t *p, size_t n, uint32_t h)
{
for (size_t i = 0; i < n; i++) {
h = (h ^ p[i]) * 16777619u;
}
return h;
}
// A frame from any bridge, once
static void deliver(const uint8_t *src_mac, const uint8_t *data, int len)
{
uint32_t h = fnv1a(src_mac, 6, 2166136261u);
h = fnv1a(data, (size_t)len, h);
int64_t now = now_ms();
for (unsigned i = 0; i < DEDUPE_LEN; i++) {
if (s_seen[i].hash == h && now - s_seen[i].ms < DEDUPE_MS) {
return;
}
}
s_seen[s_seen_next].hash = h;
s_seen[s_seen_next].ms = now;
s_seen_next = (s_seen_next + 1) % DEDUPE_LEN;
if (s_cb) {
s_cb(src_mac, data, len);
}
}
static void rx_task(void *arg)
{
(void)arg;
int i = (int)(intptr_t)arg;
uint8_t buf[6 + 256];
for (;;) {
int n = recv(s_sock, buf, sizeof(buf), 0);
int sock = s_links[i].sock;
if (sock < 0) {
vTaskDelay(pdMS_TO_TICKS(100));
continue;
}
int n = recv(sock, buf, sizeof(buf), 0);
if (n < 0) {
vTaskDelay(pdMS_TO_TICKS(100));
continue;
}
if (n > 6 && s_cb) {
s_cb(buf, buf + 6, n - 6);
if (n > 6) {
s_links[i].rx++;
deliver(buf, buf + 6, n - 6);
}
}
}
esp_err_t bridge_start(const char *addr, bridge_rx_cb_t cb)
// The control port: INFO answers HELLO, and AUDIO datagrams carry the board's microphone
static void ctl_rx_task(void *arg)
{
if (s_sock >= 0 || !addr || !addr[0]) {
return ESP_ERR_INVALID_STATE;
int i = (int)(intptr_t)arg;
uint8_t buf[1 + BRIDGE_AUDIO_BYTES + 8];
int16_t pcm[BRIDGE_AUDIO_SAMPLES];
for (;;) {
int sock = s_links[i].ctl;
if (sock < 0) {
vTaskDelay(pdMS_TO_TICKS(100));
continue;
}
int n = recv(sock, buf, sizeof(buf), 0);
if (n < 1) {
vTaskDelay(pdMS_TO_TICKS(100));
continue;
}
if (buf[0] == BRIDGE_MSG_INFO && n >= 1 + 24 && buf[1] == BRIDGE_PROTO_VERSION) {
const uint8_t *b = buf + 1;
if (!s_lock) {
continue;
}
xSemaphoreTake(s_lock, portMAX_DELAY);
link_t *l = &s_links[i];
memcpy(l->mac, b + 1, 6);
l->channel = b[7];
l->caps = n >= 1 + 25 ? b[24] : 0;
if (n >= 1 + BRIDGE_INFO_LEN) {
memcpy(l->ip, b + 25, 4);
}
l->linked = true;
l->seen_ms = now_ms();
xSemaphoreGive(s_lock);
} else if (buf[0] == BRIDGE_MSG_AUDIO && n == 1 + BRIDGE_AUDIO_BYTES) {
for (size_t k = 0; k < BRIDGE_AUDIO_SAMPLES; k++) {
pcm[k] = (int16_t)((uint16_t)buf[1 + 2 * k] | ((uint16_t)buf[2 + 2 * k] << 8));
}
s_links[i].audio++;
if (s_audio_cb) {
s_audio_cb(pcm, BRIDGE_AUDIO_SAMPLES);
}
}
}
char host[64];
int port = BRIDGE_DEFAULT_PORT;
snprintf(host, sizeof(host), "%s", addr);
}
// Every 500 ms: HELLO to each UDP board every second, the microphone request to the recording board, and the
// link state from how recently each board answered
static void keepalive_task(void *arg)
{
(void)arg;
unsigned tick = 0;
for (;;) {
vTaskDelay(pdMS_TO_TICKS(500));
tick++;
if (!s_lock) {
continue;
}
xSemaphoreTake(s_lock, portMAX_DELAY);
int64_t now = now_ms();
for (int i = 0; i < BRIDGE_MAX_LINKS; i++) {
link_t *l = &s_links[i];
if (!l->used || l->serial || l->ctl < 0) {
continue;
}
if (tick % 2 == 0) {
uint8_t hello = BRIDGE_MSG_HELLO;
send(l->ctl, &hello, 1, 0);
}
if (l->linked && now - l->seen_ms > CTL_TIMEOUT_MS) {
l->linked = false;
}
if (i == s_mic_slot) {
uint8_t on[2] = { BRIDGE_MSG_SET_MIC, 1 };
send(l->ctl, on, sizeof(on), 0);
}
}
xSemaphoreGive(s_lock);
}
}
// host:port: the address, split. Returns false if it does not parse.
static bool split_udp(const char *addr, char *host, size_t host_len, int *port)
{
snprintf(host, host_len, "%s", addr);
*port = BRIDGE_DEFAULT_PORT;
char *colon = strrchr(host, ':');
if (colon) {
*colon = 0;
port = atoi(colon + 1);
}
if (port <= 0 || port > 65535 || !host[0]) {
ESP_LOGE(TAG, "bad bridge address %s", addr);
return ESP_ERR_INVALID_ARG;
*port = atoi(colon + 1);
}
return *port > 0 && *port < 65535 && host[0];
}
// A connected UDP socket to host:port, or -1. The peer is written to peer_out.
static int connect_udp(const char *host, int port, struct sockaddr_in *peer_out)
{
struct addrinfo hints = { .ai_family = AF_INET, .ai_socktype = SOCK_DGRAM }, *res = NULL;
if (getaddrinfo(host, NULL, &hints, &res) != 0 || !res) {
ESP_LOGE(TAG, "cannot resolve %s", host);
return ESP_FAIL;
return -1;
}
memcpy(&s_peer, res->ai_addr, sizeof(s_peer));
struct sockaddr_in peer;
memcpy(&peer, res->ai_addr, sizeof(peer));
freeaddrinfo(res);
s_peer.sin_port = htons(port);
peer.sin_port = htons(port);
int s = socket(AF_INET, SOCK_DGRAM, 0);
if (s < 0) {
return ESP_FAIL;
return -1;
}
// connect() fixes the peer, so only its datagrams are received
if (connect(s, (struct sockaddr *)&s_peer, sizeof(s_peer)) != 0) {
if (connect(s, (struct sockaddr *)&peer, sizeof(peer)) != 0) {
close(s);
return ESP_FAIL;
return -1;
}
s_sock = s;
s_cb = cb;
snprintf(s_addr, sizeof(s_addr), "%s:%d", host, port);
xTaskCreate(rx_task, "bridge_rx", 4096, NULL, 6, NULL);
ESP_LOGW(TAG, "ESP-NOW frames go to the UDP bridge %s, not the radio", s_addr);
if (peer_out) {
*peer_out = peer;
}
return s;
}
static int find_link(const char *addr)
{
for (int i = 0; i < BRIDGE_MAX_LINKS; i++) {
if (s_links[i].used && strcmp(s_links[i].addr, addr) == 0) {
return i;
}
}
return -1;
}
// Open one bridge into a free slot. Lock held.
static esp_err_t activate(const char *addr)
{
int slot = -1;
for (int i = 0; i < BRIDGE_MAX_LINKS && slot < 0; i++) {
if (!s_links[i].used) {
slot = i;
}
}
if (slot < 0) {
return ESP_ERR_NO_MEM;
}
link_t *l = &s_links[slot];
l->browser = false;
if (is_browser_addr(addr)) {
#if CONFIG_IDF_TARGET_LINUX
l->browser = true;
l->serial = false;
l->sock = -1;
l->ctl = -1;
ESP_LOGW(TAG, "ESP-NOW frames go to the rig page (/sim/), not the radio");
#else
return ESP_ERR_NOT_SUPPORTED;
#endif
} else if (is_serial_addr(addr)) {
#if CONFIG_IDF_TARGET_LINUX
const char *dev = strncmp(addr, "serial:", 7) == 0 ? addr + 7 : addr;
l->board = bridge_serial_open(dev, deliver);
if (!l->board) {
return ESP_FAIL;
}
l->serial = true;
#else
return ESP_ERR_NOT_SUPPORTED;
#endif
} else {
char host[64];
int port;
if (!split_udp(addr, host, sizeof(host), &port)) {
ESP_LOGE(TAG, "bad bridge address %s", addr);
return ESP_ERR_INVALID_ARG;
}
struct sockaddr_in peer;
int s = connect_udp(host, port, &peer);
if (s < 0) {
return ESP_FAIL;
}
// The control port is the next one up: HELLO and INFO, and microphone audio
int c = connect_udp(host, port + 1, NULL);
l->sock = s;
l->ctl = c; // -1 if it could not open: the link still works, it just reports no board
l->serial = false;
if (!l->rx_task) {
xTaskCreate(rx_task, "bridge_rx", 4096, (void *)(intptr_t)slot, 6, NULL);
l->rx_task = true;
}
if (!l->ctl_task) {
xTaskCreate(ctl_rx_task, "bridge_ctl", 4096, (void *)(intptr_t)slot, 6, NULL);
l->ctl_task = true;
}
ESP_LOGW(TAG, "ESP-NOW frames go to the UDP bridge %s, not the radio", addr);
}
snprintf(l->addr, sizeof(l->addr), "%s", addr);
l->tx = l->rx = l->audio = 0;
l->linked = false;
l->caps = 0;
l->used = true;
return ESP_OK;
}
// Close one running bridge. Lock held.
static void deactivate(int i)
{
link_t *l = &s_links[i];
#if CONFIG_IDF_TARGET_LINUX
if (l->serial) {
bridge_serial_close(l->board);
}
#endif
if (!l->serial && l->sock >= 0) {
close(l->sock);
l->sock = -1;
}
if (!l->serial && l->ctl >= 0) {
close(l->ctl);
l->ctl = -1;
}
if (s_mic_slot == i) {
s_mic_slot = -1;
}
l->used = false;
}
static void ensure_tasks(void)
{
static bool started;
if (!started) {
started = true;
xTaskCreate(keepalive_task, "bridge_keep", 3072, NULL, 4, NULL);
}
}
esp_err_t bridge_set_all(const char addrs[][BRIDGE_ADDR_MAX], size_t n, bridge_rx_cb_t cb)
{
if (n > BRIDGE_MAX_LINKS) {
return ESP_ERR_INVALID_ARG;
}
if (!s_lock) {
s_lock = xSemaphoreCreateMutex();
}
xSemaphoreTake(s_lock, portMAX_DELAY);
s_cb = cb;
for (int i = 0; i < BRIDGE_MAX_LINKS; i++) {
if (!s_links[i].used) {
continue;
}
bool wanted = false;
for (size_t j = 0; j < n; j++) {
wanted = wanted || strcmp(s_links[i].addr, addrs[j]) == 0;
}
if (!wanted) {
deactivate(i);
}
}
esp_err_t first = ESP_OK;
for (size_t j = 0; j < n; j++) {
if (!addrs[j][0] || find_link(addrs[j]) >= 0) {
continue;
}
esp_err_t err = activate(addrs[j]);
if (err != ESP_OK && first == ESP_OK) {
first = err;
}
}
xSemaphoreGive(s_lock);
ensure_tasks();
return first;
}
bool bridge_active(void)
{
return s_sock >= 0;
for (int i = 0; i < BRIDGE_MAX_LINKS; i++) {
if (s_links[i].used) {
return true;
}
}
return false;
}
const char *bridge_addr(void)
size_t bridge_list(char addrs[][BRIDGE_ADDR_MAX], size_t max)
{
return s_sock >= 0 ? s_addr : NULL;
size_t n = 0;
for (int i = 0; i < BRIDGE_MAX_LINKS && n < max; i++) {
if (s_links[i].used) {
snprintf(addrs[n], BRIDGE_ADDR_MAX, "%s", s_links[i].addr);
n++;
}
}
return n;
}
esp_err_t bridge_send(const uint8_t *dst_mac, const void *data, size_t len)
{
if (s_sock < 0 || len > 250) {
return ESP_ERR_INVALID_STATE;
if (len > 250) {
return ESP_ERR_INVALID_SIZE;
}
uint8_t buf[6 + 250];
memcpy(buf, dst_mac, 6);
memcpy(buf + 6, data, len);
// A refused datagram (the simulator is not running yet) is a lost frame, as on air
send(s_sock, buf, 6 + len, 0);
return ESP_OK;
bool any = false;
if (!s_lock) {
return ESP_ERR_INVALID_STATE;
}
xSemaphoreTake(s_lock, portMAX_DELAY);
for (int i = 0; i < BRIDGE_MAX_LINKS; i++) {
link_t *l = &s_links[i];
if (!l->used) {
continue;
}
any = true;
if (l->browser) {
#if CONFIG_IDF_TARGET_LINUX
if (sim_rig_tx(buf, 6 + len)) { // no page open: the frame is lost, as on air
l->tx++;
}
#endif
} else if (l->serial) {
#if CONFIG_IDF_TARGET_LINUX
bridge_serial_send(l->board, dst_mac, data, len); // a closed port loses the frame, as on air
#endif
} else if (l->sock >= 0) {
// A refused datagram (the simulator is not running yet) is a lost frame, as on air
send(l->sock, buf, 6 + len, 0);
l->tx++;
}
}
xSemaphoreGive(s_lock);
return any ? ESP_OK : ESP_ERR_INVALID_STATE;
}
size_t bridge_status_json(char *out, size_t n)
{
size_t used = (size_t)snprintf(out, n, "[");
bool first = true;
if (!s_lock) {
return used + (size_t)snprintf(out + used, n > used ? n - used : 0, "]");
}
xSemaphoreTake(s_lock, portMAX_DELAY);
for (int i = 0; i < BRIDGE_MAX_LINKS && used < n; i++) {
link_t *l = &s_links[i];
if (!l->used) {
continue;
}
char body[400];
if (l->browser) {
#if CONFIG_IDF_TARGET_LINUX
snprintf(body, sizeof(body), "{\"page\":%s,\"tx\":%lu,\"rx\":%lu}",
sim_rig_page_open() ? "true" : "false", (unsigned long)l->tx, (unsigned long)l->rx);
#else
snprintf(body, sizeof(body), "{}");
#endif
} else if (l->serial) {
#if CONFIG_IDF_TARGET_LINUX
bridge_serial_status(l->board, body, sizeof(body));
#else
snprintf(body, sizeof(body), "{}");
#endif
} else {
char ip[24] = "null";
if (l->ip[0] || l->ip[1] || l->ip[2] || l->ip[3]) {
snprintf(ip, sizeof(ip), "\"%u.%u.%u.%u\"", l->ip[0], l->ip[1], l->ip[2], l->ip[3]);
}
snprintf(body, sizeof(body),
"{\"port\":null,\"linked\":%s,\"mac\":\"%02x:%02x:%02x:%02x:%02x:%02x\",\"channel\":%u,"
"\"mic\":%s,\"ip\":%s,\"tx\":%lu,\"rx\":%lu,\"audio\":%lu}",
l->linked ? "true" : "false", l->mac[0], l->mac[1], l->mac[2], l->mac[3], l->mac[4], l->mac[5],
(unsigned)l->channel, (l->caps & BRIDGE_CAP_MIC) ? "true" : "false", ip,
(unsigned long)l->tx, (unsigned long)l->rx, (unsigned long)l->audio);
}
int w = snprintf(out + used, n - used, "%s{\"addr\":\"%s\",\"kind\":\"%s\",\"status\":%s}",
first ? "" : ",", l->addr, l->browser ? "browser" : (l->serial ? "serial" : "udp"), body);
if (w < 0 || (size_t)w >= n - used) {
break;
}
used += (size_t)w;
first = false;
}
xSemaphoreGive(s_lock);
if (used + 2 <= n) {
out[used++] = ']';
out[used] = 0;
}
return used;
}
size_t bridge_ports_json(char *out, size_t n)
{
#if CONFIG_IDF_TARGET_LINUX
return bridge_serial_ports_json(out, n);
#else
return (size_t)snprintf(out, n, "[]");
#endif
}
esp_err_t bridge_board_set_channel(const char *addr, uint8_t channel)
{
#if CONFIG_IDF_TARGET_LINUX
if (!s_lock) {
return ESP_ERR_NOT_FOUND;
}
xSemaphoreTake(s_lock, portMAX_DELAY);
int i = find_link(addr);
esp_err_t err = (i >= 0 && s_links[i].serial) ? bridge_serial_set_channel(s_links[i].board, channel) : ESP_ERR_NOT_FOUND;
xSemaphoreGive(s_lock);
return err;
#else
(void)addr;
(void)channel;
return ESP_ERR_NOT_SUPPORTED;
#endif
}
void bridge_browser_rx(const uint8_t *frame, int len)
{
if (len <= 6 || !s_lock) {
return;
}
bool on = false;
xSemaphoreTake(s_lock, portMAX_DELAY);
for (int i = 0; i < BRIDGE_MAX_LINKS; i++) {
if (s_links[i].used && s_links[i].browser) {
s_links[i].rx++;
on = true;
}
}
bool known = false;
for (int i = 0; i < s_n_browser_macs && !known; i++) {
known = memcmp(s_browser_macs[i], frame, 6) == 0;
}
if (on && !known && s_n_browser_macs < BROWSER_MACS_MAX) {
memcpy(s_browser_macs[s_n_browser_macs++], frame, 6);
}
xSemaphoreGive(s_lock);
if (on) { // with no browser bridge in the list, the page's frames are not heard
deliver(frame, frame + 6, len - 6);
}
}
bool bridge_mac_is_browser(const uint8_t mac[6])
{
bool hit = false;
if (!s_lock) {
return false;
}
xSemaphoreTake(s_lock, portMAX_DELAY);
for (int i = 0; i < s_n_browser_macs && !hit; i++) {
hit = memcmp(s_browser_macs[i], mac, 6) == 0;
}
xSemaphoreGive(s_lock);
return hit;
}
bool bridge_has_browser(void)
{
bool on = false;
if (!s_lock) {
return false;
}
xSemaphoreTake(s_lock, portMAX_DELAY);
for (int i = 0; i < BRIDGE_MAX_LINKS; i++) {
on = on || (s_links[i].used && s_links[i].browser);
}
xSemaphoreGive(s_lock);
return on;
}
void bridge_set_audio_cb(bridge_audio_cb_t cb)
{
s_audio_cb = cb;
#if CONFIG_IDF_TARGET_LINUX
bridge_serial_set_audio_cb(cb);
#endif
}
static bool serial_has_mic(void)
{
#if CONFIG_IDF_TARGET_LINUX
return bridge_serial_has_mic();
#else
return false;
#endif
}
bool bridge_has_mic(void)
{
if (serial_has_mic()) {
return true;
}
bool any = false;
if (!s_lock) {
return false;
}
xSemaphoreTake(s_lock, portMAX_DELAY);
for (int i = 0; i < BRIDGE_MAX_LINKS; i++) {
any = any || (s_links[i].used && !s_links[i].serial && s_links[i].linked && (s_links[i].caps & BRIDGE_CAP_MIC));
}
xSemaphoreGive(s_lock);
return any;
}
// The microphone comes from a USB board when one has a mic, else from the first network board that does
esp_err_t bridge_mic(bool on)
{
if (!s_lock) {
return ESP_ERR_INVALID_STATE;
}
xSemaphoreTake(s_lock, portMAX_DELAY);
esp_err_t err = ESP_OK;
if (!on) {
if (s_mic_slot >= 0 && s_links[s_mic_slot].used && s_links[s_mic_slot].ctl >= 0) {
uint8_t off[2] = { BRIDGE_MSG_SET_MIC, 0 };
send(s_links[s_mic_slot].ctl, off, sizeof(off), 0);
}
s_mic_slot = -1;
} else if (serial_has_mic()) {
s_mic_slot = -1;
err = ESP_OK;
} else {
int pick = -1;
for (int i = 0; i < BRIDGE_MAX_LINKS && pick < 0; i++) {
link_t *l = &s_links[i];
if (l->used && !l->serial && l->linked && (l->caps & BRIDGE_CAP_MIC) && l->ctl >= 0) {
pick = i;
}
}
if (pick < 0) {
err = ESP_ERR_NOT_SUPPORTED;
} else {
s_mic_slot = pick;
uint8_t onb[2] = { BRIDGE_MSG_SET_MIC, 1 };
send(s_links[pick].ctl, onb, sizeof(onb), 0);
}
}
xSemaphoreGive(s_lock);
#if CONFIG_IDF_TARGET_LINUX
if (!on || s_mic_slot < 0) {
bridge_serial_mic(on && serial_has_mic());
} else {
bridge_serial_mic(false);
}
#endif
return err;
}
+42 -8
View File
@@ -1,8 +1,14 @@
#pragma once
// UDP bridge: carries the controller's ESP-NOW frames to a host that stands in for the radio, such as
// led-simulator (settings "bridge": "host:port"). Down: dst_mac(6) + packet. Up: src_mac(6) + packet.
// While it runs, nothing goes out over the air.
// Bridges: carry the controller's ESP-NOW frames to hosts that stand in for the radio. Several can run at
// once; every frame goes to all of them, and frames from any of them count as received (a frame heard by
// two boards arrives once). The list is settings "bridges" (or "bridge", one address, before that list):
// "host:port" UDP, e.g. led-simulator (bridge_sim.py), or a network bridge board.
// Down: dst_mac(6) + packet. Up: src_mac(6) + packet.
// "/dev/ttyACM1" serial, the USB ESP-NOW bridge board in bridge/ (linux target only), or "serial:/dev/...".
// "browser" the rig page the host build serves at /sim/ (linux target only): the simulated drivers
// run in the browser and get the frames over the page's WebSocket (sim_rig.c).
// While one runs, nothing goes out over the air.
#include <stdbool.h>
#include <stddef.h>
@@ -11,11 +17,39 @@
typedef void (*bridge_rx_cb_t)(const uint8_t *src_mac, const uint8_t *data, int len);
#define BRIDGE_DEFAULT_PORT 8766
// Microphone audio from a board that has one: 16 kHz mono samples, BRIDGE_AUDIO_SAMPLES at a time
typedef void (*bridge_audio_cb_t)(const int16_t *pcm, size_t n);
// addr "host" or "host:port". Starts the receive task; frames arrive on cb.
esp_err_t bridge_start(const char *addr, bridge_rx_cb_t cb);
#define BRIDGE_DEFAULT_PORT 8766
#define BRIDGE_MAX_LINKS 8
#define BRIDGE_ADDR_MAX 80
#define BRIDGE_BROWSER "browser"
// Make the running set of bridges addrs[0..n-1] (see above). Bridges not in the list are closed, new ones
// opened, and frames received from any of them go to cb. Returns the first error, if any; the bridges that
// could open stay up.
esp_err_t bridge_set_all(const char addrs[][BRIDGE_ADDR_MAX], size_t n, bridge_rx_cb_t cb);
bool bridge_active(void);
// A frame the rig page's drivers sent: src_mac(6) + packet (linux; sim_rig.c). Dropped unless "browser" runs.
void bridge_browser_rx(const uint8_t *frame, int len);
// The driver with this MAC was heard on the browser bridge since start: a simulated driver of the rig page
bool bridge_mac_is_browser(const uint8_t mac[6]);
// The "browser" bridge is running
bool bridge_has_browser(void);
// Send to every running bridge
esp_err_t bridge_send(const uint8_t *dst_mac, const void *data, size_t len);
// "host:port" while active, else NULL
const char *bridge_addr(void);
// The running bridges' addresses, in order; returns how many (at most max)
size_t bridge_list(char addrs[][BRIDGE_ADDR_MAX], size_t max);
// JSON array describing each running bridge: {addr, kind, ...}; returns its length
size_t bridge_status_json(char *out, size_t n);
// Serial ports a board may be on, as a JSON array of paths ("[]" off linux); returns its length
size_t bridge_ports_json(char *out, size_t n);
// Microphone audio from whichever board is recording (any bridge type)
void bridge_set_audio_cb(bridge_audio_cb_t cb);
// A running board has a microphone (USB or network)
bool bridge_has_mic(void);
// Start (true) or stop (false) the microphone on the board that has one. Network boards are asked every
// half second while they record, so a stop from the host is never needed for safety.
esp_err_t bridge_mic(bool on);
// Set the radio channel of the serial board at addr (linux). ESP_ERR_NOT_FOUND if no such board is running.
esp_err_t bridge_board_set_channel(const char *addr, uint8_t channel);
+420
View File
@@ -0,0 +1,420 @@
// Serial bridge boards: SLIP frames to the ESP-NOW bridge boards (bridge/), see bridge_proto.h. Linux only.
// Each open board has its own port, queue, writer and link task.
#include "bridge_serial.h"
#include <errno.h>
#include <fcntl.h>
#include <glob.h>
#include <stdio.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "bridge_proto.h"
static const char *TAG = "bridge_serial";
// Messages are encoded by the caller and queued; the writer task puts them on the port. A caller (the
// engine's send path) never waits for USB: when the queue is full the message is dropped and counted.
#define TX_QUEUE_LEN 64
#define MAX_BOARDS BRIDGE_MAX_LINKS
typedef struct {
uint16_t len;
uint8_t data[BRIDGE_ENC_MAX];
} tx_frame_t;
struct bridge_serial {
char dev[80];
bool used; // a slot holds a board (closed boards keep their slot and tasks)
bool active; // the link task keeps the port open while this is set
bridge_rx_cb_t cb;
SemaphoreHandle_t lock; // guards fd, the flags below and the writes
QueueHandle_t txq;
int fd; // -1 while the port is closed
bool warned; // "waiting for the port" logged once
bool have_info; // an INFO frame arrived on this open
uint8_t mac[6];
uint8_t channel;
uint8_t caps; // BRIDGE_CAP_* from INFO (0 for boards that predate it)
uint8_t eth_ip[4]; // the board's Ethernet address from INFO (0.0.0.0 without one)
bool mic_wanted; // the host is recording: SET_MIC 1 is re-sent after each reconnect
uint32_t sent; // frames this host handed to the board
uint32_t tx_queue_drops;
uint32_t tx, tx_fail, rx, drop; // the board's counters, from INFO
int16_t pcm[BRIDGE_AUDIO_SAMPLES];
};
static bridge_serial_t s_boards[MAX_BOARDS];
static bridge_audio_cb_t s_audio_cb;
static uint32_t get_u32(const uint8_t *p)
{
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
static bool open_port(bridge_serial_t *b)
{
int fd = open(b->dev, O_RDWR | O_NOCTTY);
if (fd < 0) {
return false;
}
struct termios t;
if (tcgetattr(fd, &t) == 0) {
cfmakeraw(&t);
cfsetispeed(&t, B921600); // the USB-Serial-JTAG port ignores the rate
cfsetospeed(&t, B921600);
t.c_cflag |= CLOCAL | CREAD;
tcsetattr(fd, TCSANOW, &t);
}
tcflush(fd, TCIOFLUSH);
// Non-blocking: a blocked read would hold the host's FreeRTOS task, and with it the web server
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
b->fd = fd;
return true;
}
// Queue one message for the writer. Never blocks.
static esp_err_t send_frame(bridge_serial_t *b, uint8_t type, const uint8_t *body, size_t n)
{
tx_frame_t f;
f.len = (uint16_t)bridge_encode(f.data, sizeof(f.data), type, body, n);
if (!f.len) {
return ESP_ERR_INVALID_SIZE;
}
if (xQueueSend(b->txq, &f, 0) != pdTRUE) {
b->tx_queue_drops++;
return ESP_ERR_NO_MEM;
}
return ESP_OK;
}
// The only writer for a board. It waits briefly for the port to take each message, then moves on: a
// message that cannot be written is lost, as on the air.
static void writer_task(void *arg)
{
bridge_serial_t *b = arg;
tx_frame_t f;
for (;;) {
if (xQueueReceive(b->txq, &f, pdMS_TO_TICKS(20)) != pdTRUE) {
continue;
}
xSemaphoreTake(b->lock, portMAX_DELAY);
if (b->fd >= 0) {
size_t off = 0;
int stalls = 0;
while (off < f.len) {
ssize_t w = write(b->fd, f.data + off, f.len - off);
if (w > 0) {
off += (size_t)w;
stalls = 0;
continue;
}
if (w < 0 && (errno == EINTR || errno == EAGAIN) && stalls++ < 200) {
vTaskDelay(pdMS_TO_TICKS(1)); // the port is full: give the board a moment
continue;
}
break;
}
}
xSemaphoreGive(b->lock);
}
}
static void handle_frame(bridge_serial_t *b, const uint8_t *msg, size_t len)
{
if (len < 1) {
return;
}
const uint8_t *body = msg + 1;
size_t n = len - 1;
switch (msg[0]) {
case BRIDGE_MSG_PKT:
if (n > 6 && b->cb) {
b->cb(body, body + 6, (int)(n - 6));
}
break;
case BRIDGE_MSG_INFO:
// 24 bytes from older boards, 25 with the capabilities byte
// 24 bytes from the oldest boards, 25 with capabilities, 29 with the Ethernet address
if (n >= 24 && body[0] == BRIDGE_PROTO_VERSION) {
memcpy(b->mac, body + 1, 6);
b->channel = body[7];
b->tx = get_u32(body + 8);
b->tx_fail = get_u32(body + 12);
b->rx = get_u32(body + 16);
b->drop = get_u32(body + 20);
b->caps = n >= 25 ? body[24] : 0;
memset(b->eth_ip, 0, sizeof(b->eth_ip));
if (n >= BRIDGE_INFO_LEN) {
memcpy(b->eth_ip, body + 25, 4);
}
b->have_info = true;
if (b->mic_wanted && (b->caps & BRIDGE_CAP_MIC)) {
uint8_t on = 1;
send_frame(b, BRIDGE_MSG_SET_MIC, &on, 1);
}
}
break;
case BRIDGE_MSG_AUDIO:
if (s_audio_cb && n >= BRIDGE_AUDIO_BYTES) {
for (size_t i = 0; i < BRIDGE_AUDIO_SAMPLES; i++) {
b->pcm[i] = (int16_t)((uint16_t)body[2 * i] | ((uint16_t)body[2 * i + 1] << 8));
}
s_audio_cb(b->pcm, BRIDGE_AUDIO_SAMPLES);
}
break;
case BRIDGE_MSG_LOG:
ESP_LOGI(TAG, "%s: %.*s", b->dev, (int)n, (const char *)body);
break;
default:
break;
}
}
static void link_task(void *arg)
{
bridge_serial_t *b = arg;
bridge_decoder_t dec;
uint8_t buf[256];
int64_t last_hello = 0; // ms, esp_timer clock
memset(&dec, 0, sizeof(dec));
for (;;) {
if (b->fd < 0) {
xSemaphoreTake(b->lock, portMAX_DELAY);
bool ok = b->active && open_port(b);
if (ok) {
b->warned = false;
memset(&dec, 0, sizeof(dec));
ESP_LOGI(TAG, "bridge board on %s", b->dev);
} else if (b->active && !b->warned) {
ESP_LOGW(TAG, "waiting for the bridge board on %s", b->dev);
b->warned = true;
}
xSemaphoreGive(b->lock);
if (!ok) {
vTaskDelay(pdMS_TO_TICKS(b->active ? 1000 : 200));
continue;
}
send_frame(b, BRIDGE_MSG_HELLO, NULL, 0); // the board answers with INFO
last_hello = esp_timer_get_time() / 1000;
}
// A board that is still booting after a reset misses the first HELLO: ask again until INFO arrives
if (!b->have_info && esp_timer_get_time() / 1000 - last_hello >= 1000) {
send_frame(b, BRIDGE_MSG_HELLO, NULL, 0);
last_hello = esp_timer_get_time() / 1000;
}
ssize_t n = read(b->fd, buf, sizeof(buf));
if (n < 0 && (errno == EINTR || errno == EAGAIN)) {
vTaskDelay(pdMS_TO_TICKS(5)); // nothing yet: let the other tasks run
continue;
}
if (n <= 0 || !b->active) {
xSemaphoreTake(b->lock, portMAX_DELAY);
if (b->fd >= 0) {
close(b->fd);
b->fd = -1;
ESP_LOGW(TAG, "bridge board on %s went away", b->dev);
}
b->have_info = false;
xSemaphoreGive(b->lock);
vTaskDelay(pdMS_TO_TICKS(b->active ? 1000 : 200));
continue;
}
for (ssize_t i = 0; i < n; i++) {
if (bridge_decode_feed(&dec, buf[i])) {
handle_frame(b, dec.buf, dec.frame_len);
}
}
}
}
bridge_serial_t *bridge_serial_open(const char *dev, bridge_rx_cb_t cb)
{
if (!dev || !dev[0] || strlen(dev) >= sizeof(((bridge_serial_t *)0)->dev)) {
return NULL;
}
bridge_serial_t *b = NULL;
for (int i = 0; i < MAX_BOARDS; i++) {
if (s_boards[i].used && strcmp(s_boards[i].dev, dev) == 0) {
b = &s_boards[i];
break;
}
}
if (!b) {
for (int i = 0; i < MAX_BOARDS && !b; i++) {
if (!s_boards[i].used) {
b = &s_boards[i];
}
}
if (!b) {
return NULL;
}
memset(b, 0, sizeof(*b));
snprintf(b->dev, sizeof(b->dev), "%s", dev);
b->fd = -1;
b->lock = xSemaphoreCreateMutex();
b->txq = xQueueCreate(TX_QUEUE_LEN, sizeof(tx_frame_t));
if (!b->lock || !b->txq) {
return NULL;
}
b->used = true;
xTaskCreate(writer_task, "bridge_write", 6144, b, 6, NULL);
xTaskCreate(link_task, "bridge_serial", 6144, b, 6, NULL);
}
xSemaphoreTake(b->lock, portMAX_DELAY);
b->cb = cb;
b->active = true;
xSemaphoreGive(b->lock);
ESP_LOGW(TAG, "ESP-NOW frames go to the bridge board on %s, not the radio", dev);
return b;
}
void bridge_serial_close(bridge_serial_t *b)
{
if (!b) {
return;
}
xSemaphoreTake(b->lock, portMAX_DELAY);
b->active = false;
b->mic_wanted = false;
if (b->fd >= 0) {
close(b->fd); // the link task sees fd < 0 and idles while the board is closed
b->fd = -1;
}
b->have_info = false;
xSemaphoreGive(b->lock);
}
esp_err_t bridge_serial_send(bridge_serial_t *b, const uint8_t *dst_mac, const void *data, size_t len)
{
if (!b || !b->active) {
return ESP_ERR_INVALID_STATE;
}
if (len > BRIDGE_PKT_MAX) {
return ESP_ERR_INVALID_SIZE;
}
uint8_t buf[BRIDGE_BODY_MAX];
memcpy(buf, dst_mac, 6);
memcpy(buf + 6, data, len);
esp_err_t err = send_frame(b, BRIDGE_MSG_PKT, buf, 6 + len);
if (err == ESP_OK) {
b->sent++;
}
return err;
}
esp_err_t bridge_serial_set_channel(bridge_serial_t *b, uint8_t channel)
{
if (!b) {
return ESP_ERR_INVALID_STATE;
}
if (channel < 1 || channel > 13) {
return ESP_ERR_INVALID_ARG;
}
if (!b->have_info) {
return ESP_ERR_INVALID_STATE; // the board has not answered: there is no radio to set
}
return send_frame(b, BRIDGE_MSG_SET_CHANNEL, &channel, 1);
}
size_t bridge_serial_status(bridge_serial_t *b, char *out, size_t n)
{
bool linked = b->have_info;
char ip_json[24] = "null";
if (b->have_info && (b->eth_ip[0] || b->eth_ip[1] || b->eth_ip[2] || b->eth_ip[3])) {
snprintf(ip_json, sizeof(ip_json), "\"%u.%u.%u.%u\"", b->eth_ip[0], b->eth_ip[1], b->eth_ip[2], b->eth_ip[3]);
}
return (size_t)snprintf(out, n,
"{\"port\":\"%s\",\"linked\":%s,\"mac\":\"%02x:%02x:%02x:%02x:%02x:%02x\",\"channel\":%u,"
"\"mic\":%s,\"ip\":%s,\"sent\":%lu,\"queue_drops\":%lu,\"tx\":%lu,\"tx_fail\":%lu,\"rx\":%lu,\"drop\":%lu}",
b->dev, linked ? "true" : "false", b->mac[0], b->mac[1], b->mac[2], b->mac[3], b->mac[4], b->mac[5],
(unsigned)b->channel, (b->have_info && (b->caps & BRIDGE_CAP_MIC)) ? "true" : "false",
ip_json,
(unsigned long)b->sent, (unsigned long)b->tx_queue_drops, (unsigned long)b->tx,
(unsigned long)b->tx_fail, (unsigned long)b->rx, (unsigned long)b->drop);
}
void bridge_serial_set_audio_cb(bridge_audio_cb_t cb)
{
s_audio_cb = cb;
}
bool bridge_serial_has_mic(void)
{
for (int i = 0; i < MAX_BOARDS; i++) {
bridge_serial_t *b = &s_boards[i];
if (b->used && b->active && b->have_info && (b->caps & BRIDGE_CAP_MIC)) {
return true;
}
}
return false;
}
// The recording board: the first open one with a mic. Any other board's mic stays off.
esp_err_t bridge_serial_mic(bool on)
{
bridge_serial_t *mic = NULL;
for (int i = 0; i < MAX_BOARDS && !mic; i++) {
bridge_serial_t *b = &s_boards[i];
if (b->used && b->active && b->have_info && (b->caps & BRIDGE_CAP_MIC)) {
mic = b;
}
}
for (int i = 0; i < MAX_BOARDS; i++) {
bridge_serial_t *b = &s_boards[i];
if (b->used && b != mic && b->mic_wanted) {
b->mic_wanted = false;
uint8_t off = 0;
send_frame(b, BRIDGE_MSG_SET_MIC, &off, 1);
}
}
if (!on) {
if (mic) {
mic->mic_wanted = false;
uint8_t off = 0;
return send_frame(mic, BRIDGE_MSG_SET_MIC, &off, 1);
}
return ESP_OK;
}
if (!mic) {
return ESP_ERR_NOT_SUPPORTED;
}
mic->mic_wanted = true;
uint8_t onb = 1;
return send_frame(mic, BRIDGE_MSG_SET_MIC, &onb, 1);
}
size_t bridge_serial_ports_json(char *out, size_t n)
{
static const char *const pats[] = { "/dev/ttyACM*", "/dev/ttyUSB*", "/dev/led-bridge" };
glob_t g;
memset(&g, 0, sizeof(g));
for (size_t i = 0; i < sizeof(pats) / sizeof(pats[0]); i++) {
glob(pats[i], i ? GLOB_APPEND : 0, NULL, &g);
}
size_t used = (size_t)snprintf(out, n, "[");
bool first = true;
for (size_t i = 0; i < g.gl_pathc && used < n; i++) {
const char *p = g.gl_pathv[i];
if (strchr(p, '"') || strchr(p, '\\')) {
continue;
}
int w = snprintf(out + used, n - used, "%s\"%s\"", first ? "" : ",", p);
if (w < 0 || (size_t)w >= n - used) {
break;
}
used += (size_t)w;
first = false;
}
if (used + 2 <= n) {
out[used++] = ']';
out[used] = 0;
}
globfree(&g);
return used;
}
+41
View File
@@ -0,0 +1,41 @@
#pragma once
// Serial bridge boards (linux target only): USB ESP-NOW bridge boards (bridge/) on serial ports. Several
// boards can be open at once; bridge.c owns the list and routes frames. Frames are in bridge_proto.h.
#include <stddef.h>
#include <stdbool.h>
#include <stdint.h>
#include "esp_err.h"
#include "bridge.h"
typedef struct bridge_serial bridge_serial_t;
// Open a board on dev (e.g. /dev/ttyACM1), or reopen it if it was closed. The port may come and go: its
// link task keeps reopening it, so a missing board is not an error. Frames from it go to cb.
bridge_serial_t *bridge_serial_open(const char *dev, bridge_rx_cb_t cb);
// Stop using the board: its port closes and stays closed until bridge_serial_open(dev) again.
void bridge_serial_close(bridge_serial_t *b);
// Send dst_mac + packet to the board, which puts it on ESP-NOW. ESP_ERR_INVALID_STATE while the board is closed.
esp_err_t bridge_serial_send(bridge_serial_t *b, const uint8_t *dst_mac, const void *data, size_t len);
// Change the board's ESP-NOW channel (1-13). It keeps the setting in its NVS. ESP_ERR_INVALID_STATE until it answers.
esp_err_t bridge_serial_set_channel(bridge_serial_t *b, uint8_t channel);
// JSON object describing the board: port, linked, MAC, channel, mic and counters; returns its length
size_t bridge_serial_status(bridge_serial_t *b, char *out, size_t n);
// Audio from whichever board is recording (one at a time)
void bridge_serial_set_audio_cb(bridge_audio_cb_t cb);
// A linked board reports a microphone (its INFO capabilities)
bool bridge_serial_has_mic(void);
// Start (true) or stop (false) microphone audio on the first open board that has a mic. A start is re-sent
// after a reconnect.
esp_err_t bridge_serial_mic(bool on);
// Serial ports a board may be on, as a JSON array of paths; returns its length
size_t bridge_serial_ports_json(char *out, size_t n);
+306 -1
View File
@@ -6,11 +6,13 @@
#include <stdlib.h>
#include <string.h>
#include "api_util.h"
#include "bridge.h"
#include "envelope.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "espnow_tx.h"
#include "rel.h"
#include "wifi_drv.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "store.h"
@@ -276,6 +278,180 @@ static bool driver_in_zone(const uint8_t mac[6], const char *name, const char *z
return false;
}
/* Wi-Fi drivers (transport "wifi") get the preset as a JSON API call, not an ESP-NOW frame */
static bool is_wifi(const cJSON *dev)
{
const cJSON *tr = cJSON_GetObjectItem(dev, "transport");
return cJSON_IsString(tr) && !strcmp(tr->valuestring, "wifi");
}
// Whether the Wi-Fi device (its id and record) is in group gid: a group id, "z<zone>" or "d<mac>"
static bool wifi_in_group(const cJSON *dev, const char *id, const char *gid)
{
if (gid[0] == 'z') {
const cJSON *name = cJSON_GetObjectItem(dev, "name"), *names = zone_names(gid + 1);
return cJSON_IsString(name) && names && name_seen(names, cJSON_GetArraySize(names), name->valuestring);
}
if (gid[0] == 'd') {
return false; // a driver's own group is an ESP-NOW MAC
}
const cJSON *group = cJSON_GetObjectItem(store_coll("group"), gid);
const cJSON *list = group ? cJSON_GetObjectItem(group, "devices") : NULL, *it;
cJSON_ArrayForEach(it, list)
{
if (cJSON_IsString(it) && !strcmp(it->valuestring, id)) {
return true;
}
}
return false;
}
// Wi-Fi drivers in the zone's groups get its preset (payload), or off when payload is NULL
static void wifi_zone(const char *zone_id, const cJSON *payload)
{
char t[ZONE_TARGETS_MAX][GROUP_ID_MAX];
int n = engine_zone_targets(zone_id, t, ZONE_TARGETS_MAX);
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
if (!is_wifi(d)) {
continue;
}
bool in = false;
for (int i = 0; i < n && !in; i++) {
in = wifi_in_group(d, d->string, t[i]);
}
if (!in) {
continue;
}
cJSON *body = NULL;
if (payload) {
body = wifi_drv_preset_body(payload);
} else {
body = cJSON_CreateObject();
cJSON_AddStringToObject(body, "pattern", "off");
}
if (body) {
wifi_drv_post(d->string, "/api/pattern", body);
}
}
}
// Whether a Wi-Fi device is addressed by a message: its targets (ids), else its groups, else all of them
static bool wifi_selected(const cJSON *dev, const char *id, const cJSON *targets, const cJSON *groups)
{
if (cJSON_IsArray(targets) && cJSON_GetArraySize(targets) > 0) {
const cJSON *t;
cJSON_ArrayForEach(t, targets)
{
if (cJSON_IsString(t) && !strcmp(t->valuestring, id)) {
return true;
}
}
return false;
}
if (cJSON_IsArray(groups) && groups->child) {
const cJSON *g;
cJSON_ArrayForEach(g, groups)
{
if (cJSON_IsString(g) && wifi_in_group(dev, id, g->valuestring)) {
return true;
}
}
return false;
}
return true;
}
// The Wi-Fi part of a v1 message: select (["preset", step], or {group: preset}) becomes /api/pattern,
// b becomes /api/brightness. The preset travels with the select, so a driver never runs a stale one.
static void wifi_push(const cJSON *m, const cJSON *targets)
{
const cJSON *groups = cJSON_GetObjectItem(m, "groups");
const cJSON *sel = cJSON_GetObjectItem(m, "select");
const cJSON *presets = cJSON_GetObjectItem(m, "presets");
const cJSON *b = cJSON_GetObjectItem(m, "b");
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
const char *id = d->string;
if (!is_wifi(d) || !wifi_selected(d, id, targets, groups)) {
continue;
}
const char *name = NULL;
if (cJSON_IsArray(sel)) {
const cJSON *p0 = cJSON_GetArrayItem(sel, 0);
name = cJSON_IsString(p0) ? p0->valuestring : NULL;
} else if (cJSON_IsObject(sel)) {
const cJSON *it;
cJSON_ArrayForEach(it, sel)
{
const cJSON *v = cJSON_IsArray(it) ? cJSON_GetArrayItem(it, 0) : it;
// A key is "*", the device's id or name, or a group the device is in
const cJSON *dn = cJSON_GetObjectItem(d, "name");
bool named = !strcmp(it->string, id) || (cJSON_IsString(dn) && !strcmp(it->string, dn->valuestring));
if (cJSON_IsString(v) && (!strcmp(it->string, "*") || named || wifi_in_group(d, id, it->string))) {
name = v->valuestring;
break;
}
}
} else if (cJSON_IsNumber(b)) {
cJSON *body = cJSON_CreateObject();
cJSON_AddNumberToObject(body, "brightness", b->valuedouble);
wifi_drv_post(id, "/api/brightness", body);
continue;
}
if (!name) {
continue;
}
cJSON *body = NULL, *stored = NULL;
if (!strcmp(name, "off")) {
body = cJSON_CreateObject();
cJSON_AddStringToObject(body, "pattern", "off");
cJSON_AddNumberToObject(body, "fade", 0); // not the fade of the preset it replaces
} else {
const cJSON *pv = presets ? cJSON_GetObjectItem(presets, name) : NULL;
if (!pv) {
stored = engine_preset_payload(name);
pv = stored;
}
body = wifi_drv_preset_body(pv);
cJSON_Delete(stored);
}
if (body) {
cJSON_AddTrueToObject(body, "select"); // a select restarts the pattern and fades in (fade)
wifi_drv_post(id, "/api/pattern", body);
}
}
}
// Wi-Fi drivers keep their own preset store: each preset sent is saved on the drivers it is addressed to
// (every Wi-Fi device when the send has no targets), and def becomes their startup preset
static void wifi_store_presets(const cJSON *presets, const cJSON *targets, const char *def)
{
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
if (!is_wifi(d) || !wifi_selected(d, d->string, targets, NULL)) {
continue;
}
const cJSON *p;
cJSON_ArrayForEach(p, presets)
{
cJSON *body = wifi_drv_preset_body(p);
if (body) {
cJSON_AddStringToObject(body, "name", p->string);
wifi_drv_post(d->string, "/api/presets", body);
}
}
if (def && def[0] && cJSON_GetObjectItem(presets, def)) {
cJSON *body = cJSON_CreateObject();
cJSON_AddStringToObject(body, "name", def);
wifi_drv_post(d->string, "/api/presets/startup", body);
}
}
}
// Send one envelope frame to every group the zone plays to, as GROUP_CMDs
static esp_err_t emit_zone(const char *zone_id, const uint8_t *frame, size_t len, bool commit)
{
@@ -340,6 +516,7 @@ static esp_err_t play_locked(const char *zone_id, const char *preset_id)
if (!payload) {
return ESP_ERR_NOT_FOUND;
}
wifi_zone(zone_id, payload);
uint8_t frame[ENV_FRAME_MAX];
env_blob_t pb;
env_blob_init(&pb);
@@ -359,6 +536,13 @@ static esp_err_t play_locked(const char *zone_id, const char *preset_id)
return ret;
}
void engine_zone_note(const char *zone_id, const char *preset_id)
{
store_lock();
zone_cur_set(zone_id, preset_id);
store_unlock();
}
const char *engine_zone_current(const char *zone_id)
{
for (int i = 0; i < 16; i++) {
@@ -398,6 +582,7 @@ esp_err_t engine_stop(const char *zone_id)
store_lock();
rel_bump_ver();
esp_err_t ret = select_zone(zone_id, "off");
wifi_zone(zone_id, NULL);
if (ret == ESP_OK) {
zone_cur_set(zone_id, "off");
}
@@ -666,6 +851,7 @@ esp_err_t engine_push(const cJSON *messages, const cJSON *targets)
if (!cJSON_IsObject(m)) {
continue;
}
wifi_push(m, targets);
if (!cJSON_IsArray(targets) || cJSON_GetArraySize(targets) == 0) {
rel_bump_ver(); // a broadcast state change: drivers that miss it resync from the digest
}
@@ -731,6 +917,7 @@ esp_err_t engine_send_presets(const cJSON *ids, bool save, const char *def, cons
if (!cJSON_IsArray(targets) || cJSON_GetArraySize(targets) == 0) {
rel_bump_ver();
}
wifi_store_presets(presets, targets, def);
ret = push_binary(msg, targets);
// The startup preset needs the driver names (the driver checks it is addressed); targeted sends only
if (ret == ESP_OK && def && cJSON_GetObjectItem(presets, def) && cJSON_IsArray(targets)) {
@@ -957,6 +1144,94 @@ void engine_groups_push_all(int *total, int *sent, int *failed)
}
// A driver said hello at boot: register it, then tell it which zones it belongs to
// Groups that list key from list to instead
static void groups_rename(const char *from, const char *to)
{
cJSON *g;
cJSON_ArrayForEach(g, store_coll("group"))
{
cJSON *list = cJSON_GetObjectItem(g, "devices");
for (int i = 0; list && i < cJSON_GetArraySize(list); i++) {
cJSON *it = cJSON_GetArrayItem(list, i);
if (cJSON_IsString(it) && !strcmp(it->valuestring, from)) {
cJSON_ReplaceItemInArray(list, i, cJSON_CreateString(to));
}
}
}
}
// Move a device to a new key and transport, keeping its fields. Groups that listed the old key list the
// new one. ESP-NOW devices are keyed by MAC and Wi-Fi devices by hostname, so a board that changes
// mode changes key. Caller holds the store lock.
static void device_rekey(const char *from, const char *to, const char *transport, const char *address)
{
cJSON *devs = store_coll("device");
cJSON *old = cJSON_GetObjectItem(devs, from);
if (!old || !strcmp(from, to)) {
return;
}
cJSON *rec = cJSON_Duplicate(old, 1);
api_set(rec, "id", cJSON_CreateString(to));
api_set(rec, "transport", cJSON_CreateString(transport));
api_set(rec, "address", cJSON_CreateString(address));
cJSON_DeleteItemFromObject(devs, from);
cJSON_DeleteItemFromObject(devs, to); // a record discovery made for the same board
cJSON_AddItemToObject(devs, to, rec);
groups_rename(from, to);
store_save("device");
store_save("group");
ESP_LOGI(TAG, "device %s is now %s (%s)", from, transport, to);
}
// Keep the record under key to (its settings and zones) and drop from, which is the same board on the other
// transport. Falls back to a move when there is no record under to.
static void device_fold(const char *from, const char *to, const char *transport, const char *address)
{
cJSON *devs = store_coll("device");
cJSON *keep = cJSON_GetObjectItem(devs, to);
if (!keep) {
device_rekey(from, to, transport, address);
return;
}
// The configured record wins: its settings and zones go onto the record discovery made
const cJSON *old = cJSON_GetObjectItem(devs, from);
for (const cJSON *c = old ? old->child : NULL; c; c = c->next) {
if (c->string && strcmp(c->string, "id") && strcmp(c->string, "transport") &&
strcmp(c->string, "address") && strcmp(c->string, "mac")) {
api_set(keep, c->string, cJSON_Duplicate(c, 1));
}
}
cJSON_DeleteItemFromObject(devs, from);
api_set(keep, "transport", cJSON_CreateString(transport));
api_set(keep, "address", cJSON_CreateString(address));
groups_rename(from, to);
store_save("device");
store_save("group");
ESP_LOGI(TAG, "device %s is now %s (%s), settings kept", from, transport, to);
}
// A Wi-Fi driver reported its MAC (its status). Remember it on its record. An ESP-NOW record with the same
// MAC is the same board, now on Wi-Fi: it becomes the Wi-Fi device under the hostname.
void engine_wifi_mac(const char *host, const char *mac)
{
store_lock();
cJSON *devs = store_coll("device");
const cJSON *esp = cJSON_GetObjectItem(devs, mac);
const cJSON *et = esp ? cJSON_GetObjectItem(esp, "transport") : NULL;
if (cJSON_IsString(et) && !strcmp(et->valuestring, "espnow")) {
char addr[WIFI_DRV_ID_MAX + 8];
snprintf(addr, sizeof(addr), "%s.local", host);
device_fold(mac, host, "wifi", addr);
}
cJSON *rec = cJSON_GetObjectItem(devs, host);
const cJSON *m = rec ? cJSON_GetObjectItem(rec, "mac") : NULL;
if (rec && !(cJSON_IsString(m) && !strcmp(m->valuestring, mac))) {
api_set(rec, "mac", cJSON_CreateString(mac));
store_save("device");
}
store_unlock();
}
static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len)
{
char name[48] = "";
@@ -992,8 +1267,27 @@ static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len)
snprintf(hex, sizeof(hex), "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
store_lock();
cJSON *devs = store_coll("device");
// A board that was a Wi-Fi device (keyed by hostname) and is back on ESP-NOW: same MAC, new key
if (!cJSON_GetObjectItem(devs, hex)) {
const cJSON *d;
char from[WIFI_DRV_ID_MAX + 1] = "";
cJSON_ArrayForEach(d, devs)
{
const cJSON *m = cJSON_GetObjectItem(d, "mac");
if (cJSON_IsString(m) && !strcmp(m->valuestring, hex)) {
snprintf(from, sizeof(from), "%s", d->string);
break;
}
}
if (from[0]) {
device_rekey(from, hex, "espnow", hex);
}
}
cJSON *rec = cJSON_GetObjectItem(devs, hex);
const cJSON *old = cJSON_GetObjectItem(rec, "name");
// A driver heard on the browser bridge is one of the rig page's simulated drivers: "sim": true (a real
// board has no "sim" key)
const bool sim = bridge_mac_is_browser(mac);
if (!rec) {
rec = cJSON_AddObjectToObject(devs, hex);
cJSON_AddStringToObject(rec, "id", hex);
@@ -1002,8 +1296,11 @@ static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len)
cJSON_AddStringToObject(rec, "transport", "espnow");
cJSON_AddStringToObject(rec, "address", hex);
api_apply_driver_cfg(rec, cfg, cfg_len);
if (sim) {
cJSON_AddTrueToObject(rec, "sim");
}
store_save("device");
ESP_LOGI(TAG, "new driver %s (%s)", name, hex);
ESP_LOGI(TAG, "new %sdriver %s (%s)", sim ? "simulated " : "", name, hex);
} else {
bool changed = false;
if (!cJSON_IsString(old) || strcmp(old->valuestring, name) != 0) {
@@ -1013,6 +1310,13 @@ static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len)
if (api_apply_driver_cfg(rec, cfg, cfg_len)) {
changed = true;
}
if (sim != cJSON_IsTrue(cJSON_GetObjectItem(rec, "sim"))) {
cJSON_DeleteItemFromObject(rec, "sim");
if (sim) {
cJSON_AddTrueToObject(rec, "sim");
}
changed = true;
}
if (changed) {
store_save("device");
}
@@ -1065,6 +1369,7 @@ static void resync_driver(const uint8_t mac[6])
esp_err_t engine_init(void)
{
wifi_drv_init();
rel_set_resync_cb(resync_driver);
rel_set_announce_cb(on_announce);
return ESP_OK;
+6
View File
@@ -24,6 +24,8 @@ cJSON *engine_preset_payload(const char *preset_id);
int engine_group_macs(const char *gid, char out[][13], int max);
// The preset a zone last played (engine_play / engine_stop), or NULL. Call with the store locked.
const char *engine_zone_current(const char *zone_id);
// Record preset_id as what zone_id plays, when the UI has sent it to the drivers itself
void engine_zone_note(const char *zone_id, const char *preset_id);
// Select a preset on every driver in the zone's groups (broadcast, sent twice)
esp_err_t engine_play(const char *zone_id, const char *preset_id);
@@ -35,6 +37,10 @@ esp_err_t engine_push(const cJSON *messages, const cJSON *targets);
// POST /presets/send: presets from the current profile by id
esp_err_t engine_send_presets(const cJSON *ids, bool save, const char *def, const cJSON *targets, int *sent);
// A Wi-Fi driver reported its MAC (hex, no separators): record it, and merge an ESP-NOW record for the same
// board into the Wi-Fi device. Call without the store lock held.
void engine_wifi_mac(const char *host, const char *mac);
// Zones or devices changed: re-send group membership to every registered ESP-NOW driver
void engine_groups_changed(void);
// POST /devices/groups: send every ESP-NOW driver its groups, including silent ones, and wait for the
+18 -6
View File
@@ -1,5 +1,6 @@
#include "espnow_tx.h"
#include <stdio.h>
#include <string.h>
#include "esp_check.h"
#include "esp_event.h"
@@ -50,11 +51,16 @@ static espnow_stats_t s_stats;
static volatile int s_loss_pct;
static volatile bool s_loss_beats = true;
static espnow_rx_cb_t s_rx_cb;
static char s_bridge[80];
static char s_bridges[BRIDGE_MAX_LINKS][BRIDGE_ADDR_MAX]; // the bridges to open at init
static size_t s_nbridges;
void espnow_tx_set_bridge(const char *addr)
void espnow_tx_set_bridges(const char addrs[][BRIDGE_ADDR_MAX], size_t n)
{
snprintf(s_bridge, sizeof(s_bridge), "%s", addr ? addr : "");
if (n > BRIDGE_MAX_LINKS) {
n = BRIDGE_MAX_LINKS;
}
memcpy(s_bridges, addrs, n * sizeof(s_bridges[0]));
s_nbridges = n;
}
// One frame onto the air, or to the UDP bridge while one is set
@@ -349,18 +355,24 @@ int espnow_tx_ap_clients(char *out, size_t n)
}
#endif
esp_err_t espnow_tx_change_bridges(const char addrs[][BRIDGE_ADDR_MAX], size_t n)
{
espnow_tx_set_bridges(addrs, n);
return bridge_set_all(addrs, n, bridge_rx);
}
esp_err_t espnow_tx_init(const char *ap_ssid, const char *ap_password)
{
#if CONFIG_IDF_TARGET_LINUX
(void)ap_ssid;
(void)ap_password;
ESP_RETURN_ON_FALSE(s_bridge[0], ESP_ERR_INVALID_STATE, TAG, "the host build needs a bridge address");
ESP_RETURN_ON_FALSE(s_nbridges, ESP_ERR_INVALID_STATE, TAG, "the host build needs a bridge address");
#else
// The radio still comes up behind a bridge: the access point serves the web UI
ESP_RETURN_ON_ERROR(radio_init(ap_ssid, ap_password), TAG, "radio");
#endif
if (s_bridge[0]) {
ESP_RETURN_ON_ERROR(bridge_start(s_bridge, bridge_rx), TAG, "bridge");
if (s_nbridges) {
ESP_RETURN_ON_ERROR(bridge_set_all(s_bridges, s_nbridges, bridge_rx), TAG, "bridge");
}
s_bulk_q = xQueueCreate(BULK_QUEUE_LEN, sizeof(bulk_t));
+5 -3
View File
@@ -5,6 +5,7 @@
#include <stdbool.h>
#include "esp_err.h"
#include "beat.h"
#include "bridge.h"
// Beat frame, broadcast. Little endian, 8 bytes.
#define BEAT_FRAME_MAGIC 0x4C // 0x4C wire protocol, message type 0x25
@@ -38,9 +39,10 @@ esp_err_t espnow_tx_init(const char *ap_ssid, const char *ap_password);
// JSON array [{"mac","ip"}] of stations on the access point (DHCP leases); "[]" when it is off. Returns its length.
int espnow_tx_ap_clients(char *out, size_t n);
// Before espnow_tx_init: send every frame to this UDP bridge ("host:port", see bridge.h) instead of
// the radio. NULL or "" keeps the radio.
void espnow_tx_set_bridge(const char *addr);
// Before espnow_tx_init: send every frame to these bridges (see bridge.h) instead of the radio. None keeps the radio.
void espnow_tx_set_bridges(const char addrs[][BRIDGE_ADDR_MAX], size_t n);
// While running (host build): make these the bridges (see bridge_set_all). Returns the first error, if any.
esp_err_t espnow_tx_change_bridges(const char addrs[][BRIDGE_ADDR_MAX], size_t n);
// Frames received from drivers (radio or bridge). Runs in the Wi-Fi or bridge task.
typedef void (*espnow_rx_cb_t)(const uint8_t *src_mac, const uint8_t *data, int len);
+6
View File
@@ -7,3 +7,9 @@ dependencies:
version: "^1.4.0"
rules:
- if: "target != linux"
espressif/cjson:
version: "^1.7.19"
espressif/w5500:
version: "^2.0.1"
rules:
- if: "target != linux"
+8 -3
View File
@@ -11,6 +11,8 @@
#include <stdlib.h>
#include "esp_netif.h"
#include "esp_eth.h"
#include "esp_eth_mac_w5500.h"
#include "esp_eth_phy_w5500.h"
#include "esp_mac.h"
#include "nvs_flash.h"
#include "driver/gpio.h"
@@ -20,6 +22,7 @@
#include "esp_heap_caps.h"
#include "esp_system.h"
#include "mdns.h"
#include "wifi_drv.h"
#include "lwip/ip4_addr.h"
#include "lwip/etharp.h"
#include "lwip/netif.h"
@@ -285,6 +288,7 @@ static void start_mdns(void)
mdns_instance_name_set("LED controller");
mdns_service_add(NULL, "_http", "_tcp", 80, NULL, 0);
ESP_LOGI(TAG, "mDNS: %s.local", host);
wifi_drv_start_discovery();
}
static void start_webserver(void)
@@ -396,9 +400,9 @@ static esp_err_t w5500_init(esp_eth_handle_t *eth_handle_out)
};
eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(CONFIG_W5500_SPI_HOST, &spi_devcfg);
w5500_config.int_gpio_num = CONFIG_W5500_INT_GPIO;
w5500_config.base.int_gpio_num = CONFIG_W5500_INT_GPIO;
if (CONFIG_W5500_INT_GPIO < 0) {
w5500_config.poll_period_ms = CONFIG_W5500_POLL_PERIOD_MS;
w5500_config.base.poll_period_ms = CONFIG_W5500_POLL_PERIOD_MS;
}
eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG();
@@ -454,7 +458,8 @@ void app_main(void)
bool held = ap_button_held();
s_ap_on = settings_bool("ap_enabled", true) || held;
ESP_LOGI(TAG, "AP %s%s", s_ap_on ? "on" : "off", held ? " (button held)" : "");
espnow_tx_set_bridge(settings_str("bridge")); // led-simulator stands in for the radio
char bridges[BRIDGE_MAX_LINKS][BRIDGE_ADDR_MAX]; // led-simulator or a network/USB bridge stands in for the radio
espnow_tx_set_bridges(bridges, store_bridges(bridges, BRIDGE_MAX_LINKS));
ESP_ERROR_CHECK(espnow_tx_init(s_ap_on ? (host ? host : DEFAULT_HOSTNAME) : NULL, settings_str("ap_password")));
// Ethernet is optional: without it the web UI is still served over the AP
+16
View File
@@ -1,5 +1,6 @@
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include "esp_err.h"
#include "freertos/FreeRTOS.h"
@@ -23,3 +24,18 @@ void mic_get_level(mic_level_t *out);
esp_err_t mic_stream_open(void);
size_t mic_stream_read(void *buf, size_t len, TickType_t timeout);
void mic_stream_close(void);
#ifdef LED_DESKTOP_ALSA
// Desktop only: pick the capture device the microphone reads from (ALSA name; "" or "default" = system default)
typedef struct {
char id[128]; // ALSA name, passed back to mic_open
char name[160]; // description for the device list
char label[160]; // ALSA name, shown as a tooltip
} mic_device_t;
int mic_list_devices(mic_device_t *out, int max);
esp_err_t mic_open(const char *device);
void mic_close(void);
bool mic_is_open(void);
// Why the last open failed, "" if it did not
void mic_error(char *out, size_t len);
#endif
+25
View File
@@ -152,6 +152,31 @@ static const struct {
{ "spin", "{\"n1\":\"Arms\",\"n2\":\"Arm width (degrees)\",\"n3\":\"Tail (degrees)\",\"n4\":\"1 = clockwise\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "grow", "{\"n1\":\"From: 0 centre, 1 edges, 2 round, 3 across\",\"n2\":\"Then: 0 stay, 1 empty back, 2 empty on, 3 off\",\"n3\":\"Direction (degrees, from = 3)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "field_wave", "{\"n1\":\"Direction (degrees)\",\"n2\":\"Wavelength (‰ of rig)\",\"n3\":\"Kind: 0 linear, 1 rings, 2 swirl, 3 plasma\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "blink", "{\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "aurora", "{\"n1\":\"Bands (wave: period in LEDs)\",\"n2\":\"Shimmer (wave: contrast)\",\"n3\":\"Drift\",\"n6\":\"Style: 0 bands, 1 northern wave\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "bar_graph", "{\"n1\":\"Level (0-100 %)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "blizzard", "{\"n1\":\"Flake density (0-255)\",\"n2\":\"Speed\",\"n3\":\"Wind (128 still, below/above blows one way/other)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "candle_glow", "{\"n1\":\"Candles\",\"n2\":\"Candle width (LEDs)\",\"n3\":\"Flicker (0-255)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "chase", "{\"n1\":\"Segment on (LEDs)\",\"n2\":\"Segment off (LEDs)\",\"n3\":\"Step (LEDs, negative = backwards)\",\"n4\":\"Step B, chase only (negative = backwards)\",\"n6\":\"Style: 0 chase, 1 marquee\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "circle", "{\"n1\":\"Head speed (LEDs/s)\",\"n2\":\"Max length (LEDs)\",\"n3\":\"Tail speed (LEDs/s)\",\"n4\":\"Min length (LEDs)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "clock_sweep", "{\"n1\":\"Hand width (LEDs)\",\"n2\":\"Marker every (LEDs, 0 = none)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "colour_cycle", "{\"n1\":\"Step\",\"n6\":\"Style: 0 colours, 1 rainbow wheel\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "flame", "{\"n1\":\"Min brightness (0-255)\",\"n2\":\"Breath period (ms)\",\"n3\":\"Spark gap min (ms)\",\"n4\":\"Spark gap max (ms, 0 and 0 = 10-30 s)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "flicker", "{\"n1\":\"Min level (0-255)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "gradient_wipe", "{\"n1\":\"From LED\",\"n2\":\"To LED\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "icicles", "{\"n1\":\"Spacing (LEDs)\",\"n2\":\"Max length (LEDs)\",\"n3\":\"Growth step\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "meteor", "{\"n1\":\"Tail (LEDs; scanner: width)\",\"n2\":\"Speed (scanner: end pause ms)\",\"n3\":\"Fade (meteor) / gap (comet)\",\"n6\":\"Style: 0 meteor, 1 comet, 2 scanner\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "orbit", "{\"n1\":\"Orbits\",\"n2\":\"Speed\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "palette_morph", "{\"n1\":\"Morph time (ms)\",\"n2\":\"Warp\",\"n3\":\"Turbulence\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "particles", "{\"n1\":\"Density (snow) / rate (starfall)\",\"n2\":\"Speed\",\"n3\":\"Tail (starfall)\",\"n6\":\"Style: 0 snow, 1 starfall\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "plasma", "{\"n1\":\"Scale\",\"n2\":\"Speed\",\"n3\":\"Contrast\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "pulse", "{\"n1\":\"Attack (ms)\",\"n2\":\"Hold (ms)\",\"n3\":\"Decay (ms)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "radiate", "{\"n1\":\"Spacing (LEDs)\",\"n2\":\"Outward (ms)\",\"n3\":\"Return (ms)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "rain_drops", "{\"n1\":\"Rate\",\"n2\":\"Width (LEDs)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "rime", "{\"n1\":\"Chill (1-255)\",\"n2\":\"Melt (1-255)\",\"n3\":\"Sparkle cap (LEDs)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "sparkle", "{\"n1\":\"Density (trail) / rate (ice) / count (fireflies)\",\"n2\":\"Decay (trail, ice) / speed (fireflies)\",\"n3\":\"Halo 0-3 (ice)\",\"n6\":\"Style: 0 trail, 1 ice, 2 fireflies\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "strobe_burst", "{\"n1\":\"Flashes\",\"n2\":\"Flash gap (ms)\",\"n3\":\"Cooldown (ms)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
{ "twinkle", "{\"n1\":\"Rate (1-255)\",\"n2\":\"Density (0-255)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" },
};
// Stored metadata plus the built-ins and {} for every other pattern file, as {name: {...}}
+3 -2
View File
@@ -1,7 +1,7 @@
// 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). Animations are sequences with kind "animation"; a profile
// bundle carries the ones its zones and sequence steps fire. Imports get new ids and belong to the importing profile.
// one record (a sequence with its presets). A profile bundle also carries the one-shot sequences its
// sequences play as clips (step animation_id); older bundles' zone animation_ids fold into sequence_ids. Imports get new ids and belong to the importing profile.
#include <stdio.h>
#include <string.h>
@@ -351,6 +351,7 @@ static const char *import_profile(const cJSON *b, const char *name, char *pid, s
}
remap_ids(copy, "sequence_ids", smap);
remap_ids(copy, "animation_ids", smap);
api_zone_fold_oneshots(copy);
char nid[16];
api_add("zone", copy, nid, sizeof(nid));
cJSON_AddItemToArray(zone_ids, cJSON_CreateString(nid));
+111 -12
View File
@@ -16,6 +16,7 @@
#include "espnow_tx.h"
#include "rel.h"
#include "store.h"
#include "wifi_drv.h"
#define IDENTIFY_OFF_MS 2000
@@ -93,12 +94,40 @@ static const char *normalize_device(cJSON *dev, const char *mac)
return NULL;
}
// Copy of a device with "connected": null for ESP-NOW (no link state), false for Wi-Fi (the
// controller keeps no Wi-Fi driver connections)
// A Wi-Fi driver's id is its mDNS hostname: the address without ".local", lower case, 12 characters or fewer
static bool wifi_id(const cJSON *body, char id[13])
{
char buf[64];
if (!trimmed(cJSON_GetObjectItem(body, "address"), buf, sizeof(buf))) {
return false;
}
size_t n = strlen(buf);
if (n > 6 && !strcmp(buf + n - 6, ".local")) {
buf[n - 6] = 0;
n -= 6;
}
if (n == 0 || n > 12) {
return false;
}
for (size_t i = 0; i < n; i++) {
if (!isalnum((unsigned char)buf[i]) && buf[i] != '-') {
return false;
}
buf[i] = (char)tolower((unsigned char)buf[i]);
}
memcpy(id, buf, n);
id[n] = 0;
return true;
}
// Copy of a device with "connected": null for ESP-NOW (no link state), and for Wi-Fi whether its
// WebSocket to the driver is up
static cJSON *with_connected(const cJSON *dev)
{
cJSON *o = cJSON_Duplicate(dev, true);
api_set(o, "connected", is_espnow(dev) ? cJSON_CreateNull() : cJSON_CreateFalse());
const cJSON *id = cJSON_GetObjectItem(dev, "id");
bool up = cJSON_IsString(id) && wifi_drv_connected(id->valuestring);
api_set(o, "connected", is_espnow(dev) ? cJSON_CreateNull() : cJSON_CreateBool(up));
return o;
}
@@ -125,9 +154,12 @@ static esp_err_t create_device(httpd_req_t *req)
bool wifi = cJSON_IsString(tr) && !strcmp(tr->valuestring, "wifi");
if (!trimmed(cJSON_GetObjectItem(body, "name"), name, sizeof(name))) {
err = "name is required";
} else if (!api_mac(cJSON_GetObjectItem(body, "mac"), mac) &&
(wifi || !api_mac(cJSON_GetObjectItem(body, "address"), mac))) {
err = "mac is required (12 hex digits); for Wi-Fi include mac plus IP in address";
} else if (wifi) {
if (!wifi_id(body, mac)) {
err = "address must be the driver's hostname (letters, digits and '-', 12 characters or fewer)";
}
} else if (!api_mac(cJSON_GetObjectItem(body, "mac"), mac) && !api_mac(cJSON_GetObjectItem(body, "address"), mac)) {
err = "mac is required (12 hex digits)";
}
cJSON_DeleteItemFromObject(body, "id");
cJSON_DeleteItemFromObject(body, "connected");
@@ -135,6 +167,11 @@ static esp_err_t create_device(httpd_req_t *req)
if (!err) {
err = normalize_device(body, mac);
}
if (!err && wifi) {
char addr[WIFI_DRV_ID_MAX + 8];
snprintf(addr, sizeof(addr), "%s.local", mac);
api_set(body, "address", cJSON_CreateString(addr));
}
if (err) {
cJSON_Delete(body);
return api_error(req, "400 Bad Request", err);
@@ -204,14 +241,48 @@ static esp_err_t push_to(const char *mac, cJSON *msg)
return err;
}
// Settings a Wi-Fi driver takes at /api/hardware. Its name is its hostname and its id, so it is not sent.
static esp_err_t push_wifi_hw(const char *address, cJSON *dc)
{
char host[64];
snprintf(host, sizeof(host), "%s", address);
size_t n = strlen(host);
if (n > 6 && !strcmp(host + n - 6, ".local")) {
host[n - 6] = 0;
}
cJSON *body = cJSON_CreateObject();
const cJSON *v = cJSON_GetObjectItem(dc, "color_order");
if (cJSON_IsString(v)) {
cJSON_AddStringToObject(body, "rgb_order", v->valuestring);
}
v = cJSON_GetObjectItem(dc, "max_brightness");
if (cJSON_IsNumber(v)) {
cJSON_AddNumberToObject(body, "max_brightness", v->valuedouble);
}
v = cJSON_GetObjectItem(dc, "num_leds");
if (cJSON_IsNumber(v)) {
cJSON_AddNumberToObject(body, "num_leds", v->valuedouble);
}
cJSON_Delete(dc);
if (!body->child) {
cJSON_Delete(body);
return ESP_OK;
}
wifi_drv_post(host, "/api/hardware", body); // takes ownership of body
return ESP_OK;
}
// Send changed settings to an ESP-NOW driver; takes ownership of dc
static esp_err_t push_device_config(const cJSON *dev, cJSON *dc)
{
const cJSON *addr = cJSON_GetObjectItem(dev, "address");
if (!is_espnow(dev) || !cJSON_IsString(addr)) {
if (!cJSON_IsString(addr)) {
cJSON_Delete(dc);
return ESP_ERR_INVALID_ARG;
}
if (!is_espnow(dev)) {
return push_wifi_hw(addr->valuestring, dc);
}
cJSON *msg = cJSON_CreateObject();
cJSON_AddStringToObject(msg, "v", "1");
cJSON_AddItemToObject(msg, "device_config", dc);
@@ -314,8 +385,9 @@ esp_err_t api_identify_group(const char *group_id)
static esp_err_t identify(httpd_req_t *req, const cJSON *dev, const char *mac)
{
if (!is_espnow(dev)) {
return api_error(req, "503 Service Unavailable", "Wi-Fi driver not connected");
if (!is_espnow(dev)) { // a Wi-Fi driver is identified over its own link (its id is mac)
wifi_drv_identify(mac);
return api_message(req, "200 OK", "Identify sent");
}
if (identify_start(mac, NULL) != ESP_OK) {
return api_error(req, "503 Service Unavailable", "Identify send failed");
@@ -441,7 +513,7 @@ static esp_err_t device_brightness(httpd_req_t *req, const char *mac)
}
// POST /devices/<id>/driver-config {name, num_leds, color_order, startup_mode}
static esp_err_t device_driver_config(httpd_req_t *req, const char *mac)
static esp_err_t device_driver_config(httpd_req_t *req, const cJSON *dev, const char *mac)
{
cJSON *body = api_body_opt(req);
if (!body) {
@@ -453,6 +525,15 @@ static esp_err_t device_driver_config(httpd_req_t *req, const char *mac)
if (!dc) {
return api_error(req, "400 Bad Request", "Provide at least one of name, num_leds, color_order, startup_mode");
}
if (!is_espnow(dev)) {
const cJSON *addr = cJSON_GetObjectItem(dev, "address");
if (!cJSON_IsString(addr)) {
cJSON_Delete(dc);
return api_error(req, "500 Internal Server Error", "device has no address");
}
push_wifi_hw(addr->valuestring, dc);
return api_message(req, "200 OK", "driver-config sent");
}
cJSON *msg = cJSON_CreateObject();
cJSON_AddStringToObject(msg, "v", "1");
cJSON_AddItemToObject(msg, "device_config", dc);
@@ -588,7 +669,9 @@ static esp_err_t ping_devices(httpd_req_t *req)
cJSON_ArrayForEach(d, store_coll("device"))
{
unsigned m[6];
if (d->string && sscanf(d->string, "%2x%2x%2x%2x%2x%2x", &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) == 6) {
const cJSON *tr = cJSON_GetObjectItem(d, "transport");
bool wifi = cJSON_IsString(tr) && !strcmp(tr->valuestring, "wifi"); // ids are hostnames, not MACs
if (!wifi && d->string && sscanf(d->string, "%2x%2x%2x%2x%2x%2x", &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) == 6) {
uint8_t mac[6] = { m[0], m[1], m[2], m[3], m[4], m[5] };
esp_err_t e = espnow_tx_send(mac, pkt, sizeof(pkt));
err = e != ESP_OK ? e : err;
@@ -613,6 +696,10 @@ static esp_err_t ping_devices(httpd_req_t *req)
if (err != ESP_OK) {
return api_error(req, "503 Service Unavailable", "Send failed");
}
wifi_drv_ping_t wr[WIFI_DRV_PING_MAX];
store_unlock(); // Wi-Fi drivers answer over their own links; this waits up to timeout_s
int wn = wifi_drv_ping_all((int)(timeout_s * 1000), wr, WIFI_DRV_PING_MAX);
store_lock();
cJSON *o = cJSON_CreateObject(), *responses;
cJSON_AddTrueToObject(o, "ok");
@@ -636,6 +723,18 @@ static esp_err_t ping_devices(httpd_req_t *req)
}
registered += register_from_ping(hex, got[i].name, got[i].cfg);
}
for (int i = 0; i < wn; i++) {
if (wr[i].rtt_ms < 0) {
continue;
}
const cJSON *dev = cJSON_GetObjectItem(store_coll("device"), wr[i].id);
const cJSON *name = dev ? cJSON_GetObjectItem(dev, "name") : NULL;
cJSON *r = cJSON_AddObjectToObject(responses, wr[i].id);
cJSON_AddStringToObject(r, "mac", wr[i].id);
cJSON_AddStringToObject(r, "name", cJSON_IsString(name) ? name->valuestring : wr[i].id);
cJSON_AddNumberToObject(r, "rtt_ms", wr[i].rtt_ms);
cJSON_AddStringToObject(r, "transport", "wifi");
}
cJSON_AddNumberToObject(o, "registered", registered);
if (registered) {
store_save("device");
@@ -868,7 +967,7 @@ bool devices_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret)
} else if (method == HTTP_POST && !strcmp(seg[2], "brightness")) {
*ret = device_brightness(req, mac);
} else if (method == HTTP_POST && !strcmp(seg[2], "driver-config")) {
*ret = device_driver_config(req, mac);
*ret = device_driver_config(req, dev, mac);
} else if (method == HTTP_POST && !strcmp(seg[2], "patterns")) {
*ret = api_error(req, "400 Bad Request", "Pattern OTA push is not supported for ESP-NOW devices");
} else {
+15 -2
View File
@@ -219,6 +219,16 @@ static void apply_update(cJSON *doc, cJSON *data)
cJSON_AddItemToArray(lanes, cJSON_Duplicate(steps, true));
api_set(data, "lanes", lanes);
}
// `loop` decides whether a sequence is a one-shot. Older clients sent kind "animation" for one;
// without a `loop` of their own that means loop off. kind itself is no longer kept.
const cJSON *kind = cJSON_GetObjectItem(data, "kind");
if (cJSON_IsString(kind) && !strcmp(kind->valuestring, "animation") && !cJSON_GetObjectItem(data, "loop")) {
api_set(data, "loop", cJSON_CreateFalse());
}
cJSON_DeleteItemFromObject(data, "kind");
if (cJSON_GetObjectItem(data, "loop")) {
cJSON_DeleteItemFromObject(doc, "kind");
}
api_merge(doc, data);
}
@@ -240,7 +250,10 @@ static esp_err_t play_sequence(httpd_req_t *req, const char *id)
return api_error(req, "400 Bad Request", "zone_id required");
}
const char *msg;
esp_err_t err = seqplay_start(id, zone, profile, &msg);
// A one-shot (loop off) plays once over whatever runs, then the zone goes back to its last looping
// preset or sequence
esp_err_t err = seqplay_is_oneshot(id) ? seqplay_fire(id, zone, profile, "now", &msg)
: seqplay_start(id, zone, profile, &msg);
if (err != ESP_OK) {
return api_error(req, "400 Bad Request", msg ? msg : "sequence not found");
}
@@ -271,7 +284,7 @@ static esp_err_t fire_sequence(httpd_req_t *req, const char *id)
esp_err_t err = seqplay_fire(id, zone, profile, wait, &msg);
if (err != ESP_OK) {
return api_error(req, err == ESP_ERR_NOT_FOUND ? "404 Not Found" : "400 Bad Request",
msg ? msg : "animation not found");
msg ? msg : "sequence not found");
}
cJSON *o = cJSON_CreateObject();
cJSON_AddTrueToObject(o, "ok");
+44 -1
View File
@@ -813,7 +813,15 @@ bool zones_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret)
*ret = api_error(req, "404 Not Found", "Preset not found");
return true;
}
esp_err_t err = skip ? ESP_OK : engine_play(seg[1], key);
// A looping preset takes over the zone from a looping sequence; a one-shot playing over the
// zone comes back to this preset when it ends
seqplay_end_base_in(seg[1]);
esp_err_t err = ESP_OK;
if (skip) {
engine_zone_note(seg[1], key);
} else {
err = engine_play(seg[1], key);
}
if (err != ESP_OK) {
*ret = api_result(req, err, "");
return true;
@@ -859,6 +867,40 @@ static bool zone_has_presets(const cJSON *z)
return false;
}
// Older zones list one-shot sequences ("animations") apart, in animation_ids: move them to the end of
// sequence_ids, where one-shots and looping sequences now sit together. True when the zone changed.
bool api_zone_fold_oneshots(cJSON *z)
{
cJSON *anims = cJSON_GetObjectItem(z, "animation_ids");
if (!anims) {
return false;
}
cJSON *seqs = cJSON_GetObjectItem(z, "sequence_ids");
if (!cJSON_IsArray(seqs)) {
seqs = cJSON_CreateArray();
api_set(z, "sequence_ids", seqs);
}
const cJSON *a;
cJSON_ArrayForEach(a, anims)
{
char id[24], have[24];
if (!api_id(a, id, sizeof(id))) {
continue;
}
bool dup = false;
const cJSON *s;
cJSON_ArrayForEach(s, seqs)
{
dup = dup || (api_id(s, have, sizeof(have)) && !strcmp(have, id));
}
if (!dup) {
cJSON_AddItemToArray(seqs, cJSON_CreateString(id));
}
}
cJSON_DeleteItemFromObject(z, "animation_ids");
return true;
}
// main's Zone.load: group_ids, preset_group_ids, sequence_ids and content_kind on every zone
void api_migrate_zones(void)
{
@@ -881,6 +923,7 @@ void api_migrate_zones(void)
api_set(z, "sequence_ids", cJSON_CreateArray());
changed = true;
}
changed = api_zone_fold_oneshots(z) || changed;
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;
+61 -24
View File
@@ -87,11 +87,11 @@ typedef struct {
// Everything below is guarded by the store lock (the beat task and the HTTP handlers both take it).
// Lanes and targets live in PSRAM, allocated by seqplay_init.
static player_t s_base; // the sequence
static player_t s_ovl; // a one-shot animation over it
static macs_t s_covered; // drivers the animation lights; the sequence's sends skip them
static player_t s_ovl; // a one-shot sequence over it
static macs_t s_covered; // drivers the one-shot lights; the sequence's sends skip them
static macs_t s_restore; // while set (n > 0), sends go only to these drivers
static bool s_restoring;
static bool s_base_clear_pending; // the sequence ended under the animation: clear once it is over
static bool s_base_clear_pending; // the sequence ended under the one-shot: clear once it is over
static struct {
bool set;
@@ -145,6 +145,19 @@ static bool str_is(const cJSON *o, const char *k, const char *want)
return cJSON_IsString(v) && !strcmp(v->valuestring, want);
}
// A sequence loops unless its `loop` is off. Older records: kind "animation" with no `loop` plays once.
static bool seq_oneshot(const cJSON *seq)
{
const cJSON *loop = cJSON_GetObjectItem(seq, "loop");
if (cJSON_IsBool(loop)) {
return cJSON_IsFalse(loop);
}
if (cJSON_IsNumber(loop)) {
return loop->valuedouble == 0;
}
return str_is(seq, "kind", "animation");
}
/* ---------------------------------------------------------------- targets */
static void add_id(cJSON *arr, const char *id)
@@ -309,7 +322,7 @@ static cJSON *groups_for(const player_t *p, uint32_t mask)
return drivers;
}
static void send(cJSON *msg)
static void send_msg(cJSON *msg)
{
cJSON *messages = cJSON_CreateArray();
cJSON_AddItemToArray(messages, msg);
@@ -343,7 +356,7 @@ static void upload(const player_t *p, uint32_t mask, cJSON *presets)
return;
}
cJSON_AddItemToObject(m, "presets", presets);
send(m);
send_msg(m);
}
// Upload presets of steps [from, to) of a lane (each once) to all of the lane's targets
@@ -373,7 +386,7 @@ static void select_on(const player_t *p, uint32_t mask, const char *preset)
if (m) {
cJSON *sel = cJSON_AddArrayToObject(m, "select");
cJSON_AddItemToArray(sel, cJSON_CreateString(preset));
send(m);
send_msg(m);
}
}
@@ -470,7 +483,8 @@ static int load_lanes(player_t *p, const cJSON *seq)
const int nuser = p->ntargets;
const cJSON *lgs = cJSON_GetObjectItem(seq, "lanes_group_ids");
const cJSON *opts = cJSON_GetObjectItem(seq, "lane_opts");
const bool seq_timed = str_is(seq, "advance_mode", "time");
// A one-shot is always timed in seconds, whatever its advance_mode or lane modes say
const bool seq_timed = seq_oneshot(seq) || str_is(seq, "advance_mode", "time");
int n = 0, src = -1;
cJSON_ArrayForEach(l, lanes)
{
@@ -482,7 +496,7 @@ static int load_lanes(player_t *p, const cJSON *seq)
lane_t *lane = &p->lane[n];
memset(lane, 0, sizeof(*lane));
const cJSON *mode = cJSON_GetObjectItem(o, "mode");
lane->timed = cJSON_IsString(mode) ? !strcmp(mode->valuestring, "time") : seq_timed;
lane->timed = seq_oneshot(seq) || (cJSON_IsString(mode) ? !strcmp(mode->valuestring, "time") : seq_timed);
double rate = num(o, "rate", 1);
rate = rate < 0.25 ? 0.25 : (rate > 4 ? 4 : rate);
// Targets: the lane's own list, else the older group fields, else the zone's
@@ -599,7 +613,7 @@ static void clear_drivers(const char *zone)
if (m) {
cJSON_AddTrueToObject(m, "clear_presets");
cJSON_AddTrueToObject(m, "save");
send(m);
send_msg(m);
}
}
@@ -656,9 +670,8 @@ static esp_err_t load(player_t *p, const char *seq_id, const char *zone_id, cons
*msg = "sequence has no steps";
return ESP_ERR_INVALID_SIZE;
}
const cJSON *loop = cJSON_GetObjectItem(seq, "loop");
bool on = cJSON_IsTrue(loop) || (cJSON_IsNumber(loop) && loop->valuedouble != 0);
p->loop = p->overlay ? on : (!loop || on); // a sequence loops unless told not to; an animation plays once
// Over the zone (a one-shot, or a clip in another sequence) it always plays once
p->loop = !p->overlay && !seq_oneshot(seq);
p->synced = synced;
p->loop_beat = 0;
p->lane0_looped = false;
@@ -706,7 +719,7 @@ static esp_err_t start_now(const char *seq_id, const char *zone_id, const char *
return ESP_OK;
}
// Drivers an animation may light: every target its lanes name
// Drivers a one-shot may light: every target its lanes name
static void covered_by(const player_t *p, macs_t *out)
{
out->n = 0;
@@ -725,7 +738,7 @@ static void covered_by(const player_t *p, macs_t *out)
}
}
// Bring back what the drivers in `drivers` showed before the animation: the sequence's current steps,
// Bring back what the drivers in `drivers` showed before the one-shot: the sequence's current steps,
// else the zone's last preset, else off
static void restore(const macs_t *drivers, const char *zone)
{
@@ -775,13 +788,13 @@ static void overlay_end(void)
return;
}
s_ovl.active = false;
ESP_LOGI(TAG, "animation %s over", s_ovl.seq);
ESP_LOGI(TAG, "one-shot %s over", s_ovl.seq);
macs_t was = s_covered;
s_covered.n = 0;
restore(&was, s_ovl.zone);
}
// Play animation seq_id once over whatever runs. A new one replaces the one playing; drivers the new one
// Play sequence seq_id once over whatever runs (a one-shot). A new one replaces the one playing; drivers the new one
// leaves alone go back to what they showed.
static void fire(const char *seq_id, const char *zone_id, const char *profile_id, bool synced)
{
@@ -789,10 +802,10 @@ static void fire(const char *seq_id, const char *zone_id, const char *profile_id
macs_t was = s_ovl.active ? s_covered : (macs_t){ 0 };
s_ovl.active = false;
const char *msg = NULL;
// Work out what the animation covers before it sends anything, so the sequence keeps off those drivers
// Work out what the one-shot covers before it sends anything, so the sequence keeps off those drivers
s_covered.n = 0;
if (load(&s_ovl, seq_id, zone_id, profile_id, synced, &msg) != ESP_OK) {
ESP_LOGW(TAG, "animation %s did not start: %s", seq_id, msg ? msg : "not found");
ESP_LOGW(TAG, "one-shot %s did not start: %s", seq_id, msg ? msg : "not found");
restore(&was, zone_id);
return;
}
@@ -804,7 +817,7 @@ static void fire(const char *seq_id, const char *zone_id, const char *profile_id
}
}
restore(&back, zone_id);
ESP_LOGI(TAG, "animation %s in zone %s: %d lane(s), %d driver(s)", seq_id, zone_id, s_ovl.nlanes, s_covered.n);
ESP_LOGI(TAG, "one-shot %s in zone %s: %d lane(s), %d driver(s)", seq_id, zone_id, s_ovl.nlanes, s_covered.n);
}
// Move a lane on once its step is over
@@ -859,7 +872,7 @@ static void finish_if_done(player_t *p)
readout(s_done_readout, sizeof(s_done_readout));
p->active = false;
if (s_ovl.active) {
s_base_clear_pending = true; // the animation still shows; clear once it is over
s_base_clear_pending = true; // the one-shot still shows; clear once it is over
} else {
clear_drivers(p->zone);
}
@@ -1072,6 +1085,15 @@ esp_err_t seqplay_init(void)
return xTaskCreate(beat_task, "seqplay", 8192, NULL, 4, NULL) == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
}
bool seqplay_is_oneshot(const char *seq_id)
{
store_lock();
const cJSON *seq = cJSON_GetObjectItem(store_coll("sequence"), seq_id);
bool one = seq && seq_oneshot(seq);
store_unlock();
return one;
}
static bool owned(const char *seq_id, const char *profile_id)
{
const cJSON *seq = cJSON_GetObjectItem(store_coll("sequence"), seq_id);
@@ -1103,7 +1125,7 @@ esp_err_t seqplay_fire(const char *seq_id, const char *zone_id, const char *prof
{
*msg = NULL;
if (!owned(seq_id, profile_id)) {
*msg = "animation not found";
*msg = "sequence not found";
return ESP_ERR_NOT_FOUND;
}
if (!zone_id || !zone_id[0]) {
@@ -1123,7 +1145,7 @@ esp_err_t seqplay_fire(const char *seq_id, const char *zone_id, const char *prof
}
fire(seq_id, zone_id, profile_id, false);
if (!s_ovl.active) {
*msg = "animation has no steps";
*msg = "sequence has no steps";
return ESP_ERR_INVALID_SIZE;
}
return ESP_OK;
@@ -1161,6 +1183,21 @@ void seqplay_stop(bool clear)
store_unlock();
}
void seqplay_end_base_in(const char *zone_id)
{
store_lock();
if (s_pend.set && !strcmp(s_pend.zone, zone_id)) {
s_pend.set = false;
s_base.pending_switch = false;
}
if (s_base.active && !strcmp(s_base.zone, zone_id)) {
s_base.active = false;
s_base_clear_pending = false;
ESP_LOGI(TAG, "sequence %s in zone %s: a preset took over", s_base.seq, zone_id);
}
store_unlock();
}
void seqplay_stop_if(const char *seq_id)
{
store_lock();
@@ -1210,7 +1247,7 @@ void seqplay_length(const char *seq_id, double *beats, double *secs)
{
const cJSON *seq = cJSON_GetObjectItem(store_coll("sequence"), seq_id);
const cJSON *opts = cJSON_GetObjectItem(seq, "lane_opts");
bool seq_timed = str_is(seq, "advance_mode", "time");
bool seq_timed = seq_oneshot(seq) || str_is(seq, "advance_mode", "time");
double b = 0, s = 0;
int src = -1;
const cJSON *l;
@@ -1219,7 +1256,7 @@ void seqplay_length(const char *seq_id, double *beats, double *secs)
src++;
const cJSON *o = cJSON_GetArrayItem(opts, src);
const cJSON *mode = cJSON_GetObjectItem(o, "mode");
bool timed = cJSON_IsString(mode) ? !strcmp(mode->valuestring, "time") : seq_timed;
bool timed = seq_oneshot(seq) || (cJSON_IsString(mode) ? !strcmp(mode->valuestring, "time") : seq_timed);
double rate = num(o, "rate", 1);
rate = rate < 0.25 ? 0.25 : (rate > 4 ? 4 : rate);
double total = 0;
+11 -6
View File
@@ -15,16 +15,21 @@ esp_err_t seqplay_init(void);
// Start sequence seq_id in zone_id. While another sequence plays, the switch waits for the next beat
// (or downbeat, settings.sequence_switch_wait) and *queued is set. ESP_ERR_NOT_FOUND: no such sequence
// in the profile; ESP_ERR_INVALID_ARG: no zone (msg says which); ESP_ERR_INVALID_SIZE: no steps.
// Call with the store locked.
// Call with the store locked. A one-shot (loop off) belongs to seqplay_fire instead.
esp_err_t seqplay_start(const char *seq_id, const char *zone_id, const char *profile_id, const char **msg);
// Play sequence seq_id once as an animation over whatever runs in the zone (zone_id NULL or "": the
// playing sequence's zone). wait: "now" (default), "beat" or "downbeat". The sequence underneath keeps
// time and skips the drivers the animation lights; when it ends they go back to the sequence's current
// step, or the zone's last preset. A new animation replaces the one playing. Call with the store locked.
// Play sequence seq_id once (a one-shot) over whatever runs in the zone (zone_id NULL or "": the
// playing sequence's zone). wait: "now" (default), "beat" or "downbeat". The looping sequence underneath
// keeps time and skips the drivers the one-shot lights; when it ends they go back to that sequence's
// current step, or the zone's last preset. A new one-shot replaces the one playing. Call with the store locked.
esp_err_t seqplay_fire(const char *seq_id, const char *zone_id, const char *profile_id, const char *wait,
const char **msg);
// End the animation now and restore its drivers
// A looping preset was picked in zone_id: the looping sequence playing there (or queued for it) ends,
// without clearing the drivers. A one-shot playing over the zone carries on, and comes back to the preset.
void seqplay_end_base_in(const char *zone_id);
// Whether sequence seq_id is a one-shot: its `loop` is off (older records: kind "animation")
bool seqplay_is_oneshot(const char *seq_id);
// End the one-shot now and restore its drivers
void seqplay_overlay_stop(void);
// How long sequence seq_id plays once: *beats and *secs (each converted from the other at the current
// tempo); unchanged when it has no steps. Call with the store locked.
+23
View File
@@ -186,6 +186,29 @@ cJSON *store_settings(void)
return store_coll("settings");
}
size_t store_bridges(char addrs[][80], size_t max)
{
size_t n = 0;
cJSON *settings = store_settings();
cJSON *list = cJSON_GetObjectItem(settings, "bridges");
if (cJSON_IsArray(list)) {
cJSON *item = NULL;
cJSON_ArrayForEach(item, list) {
if (n < max && cJSON_IsString(item) && item->valuestring[0]) {
snprintf(addrs[n], 80, "%s", item->valuestring);
n++;
}
}
return n;
}
cJSON *one = cJSON_GetObjectItem(settings, "bridge");
if (max && cJSON_IsString(one) && one->valuestring[0]) {
snprintf(addrs[0], 80, "%s", one->valuestring);
n = 1;
}
return n;
}
void store_lock(void)
{
xSemaphoreTakeRecursive(s_lock, portMAX_DELAY);
+4
View File
@@ -25,6 +25,10 @@ void store_next_id(const char *name, char *buf, size_t len);
// Settings are one flat object (the "settings" collection itself)
cJSON *store_settings(void);
// The bridges to run (see bridge.h): settings "bridges" (a list), else the older "bridge" (one address).
// Writes them into addrs (up to max, each BRIDGE_ADDR_MAX bytes); returns the count.
size_t store_bridges(char addrs[][80], size_t max);
// Recursive lock around every read or write of the collections (HTTP handlers and the sequencer)
void store_lock(void);
void store_unlock(void);
+8 -5
View File
@@ -100,15 +100,18 @@ 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.
// Every file changes only with the web pack, so a hash of the pack is the ETag: browsers revalidate on
// each load (no-cache) and get a 304 until the UI changes, instead of running a stale UI for a day.
// (Not the app's ELF hash: the desktop and sim builds have none, so their ETag never changed.)
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]);
uint64_t h = 1469598103934665603ULL; // FNV-1a
for (const uint8_t *p = www_pack_start; p < www_pack_end; p++) {
h = (h ^ *p) * 1099511628211ULL;
}
snprintf(tag, sizeof(tag), "\"%016llx\"", (unsigned long long)h);
}
return tag;
}
+557
View File
@@ -0,0 +1,557 @@
// Wi-Fi LED drivers: discovery over mDNS, one WebSocket per driver, and a sender task so the engine
// never waits on the network. Requests are sent one at a time per driver, each answered before the next.
#include "wifi_drv.h"
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "engine.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "store.h"
#include "ws_client.h"
#if !defined(CONFIG_IDF_TARGET_LINUX) || defined(LED_DESKTOP_MDNS) // the desktop build has its own mDNS browser
#include "esp_netif_ip_addr.h"
#include "mdns.h"
#endif
static const char *TAG = "wifi_drv";
#define LINKS_MAX 16
#define QUEUE_LEN 24
#define BODY_MAX 1024
#define REPLY_MAX 1024
#define DISCOVER_MS 30000
typedef struct {
char id[WIFI_DRV_ID_MAX + 1]; // "" when the slot is free
char ip[16]; // from mDNS; "" when not known (the hostname is used then)
int fd; // sender task only
bool up; // read by wifi_drv_connected
int fails;
int64_t retry_us;
} link_t;
typedef struct {
char id[WIFI_DRV_ID_MAX + 1];
char method[8];
char path[40];
char *body; // JSON object text, owned by the job
bool ping; // a batch ping of every Wi-Fi driver (no id, no body)
} job_t;
#define PING_MAX WIFI_DRV_PING_MAX
static struct {
bool busy; // set while a batch runs, cleared by the sender when it finishes
int n;
wifi_drv_ping_t r[PING_MAX];
} s_ping; // guarded by s_mu
static SemaphoreHandle_t s_ping_done;
static link_t s_links[LINKS_MAX];
static QueueHandle_t s_q;
static SemaphoreHandle_t s_mu; // guards s_links[].id, .ip and .up
// Find or claim the link slot for id. Call with s_mu held.
static link_t *link_for(const char *id)
{
link_t *free_slot = NULL;
for (int i = 0; i < LINKS_MAX; i++) {
if (s_links[i].id[0] && !strcmp(s_links[i].id, id)) {
return &s_links[i];
}
if (!s_links[i].id[0] && !free_slot) {
free_slot = &s_links[i];
}
}
if (free_slot) {
snprintf(free_slot->id, sizeof(free_slot->id), "%s", id);
free_slot->fd = -1;
free_slot->up = false;
free_slot->fails = 0;
free_slot->retry_us = 0;
}
return free_slot;
}
static void mark_down(link_t *l)
{
ws_client_close(l->fd);
l->fd = -1;
xSemaphoreTake(s_mu, portMAX_DELAY);
l->up = false;
xSemaphoreGive(s_mu);
l->fails++;
int64_t backoff_s = 1LL << (l->fails < 5 ? l->fails : 5); // 2 s, 4 s, ... up to 30 s
l->retry_us = esp_timer_get_time() + (backoff_s > 30 ? 30 : backoff_s) * 1000000LL;
}
// One request and its reply on the driver's link: connect if needed, send, wait for the answer.
// Returns true with the reply in reply and the round trip in *rtt_ms (when not NULL).
static bool exchange(const char *id, const char *method, const char *path, const char *body,
char *reply, size_t cap, int *rtt_ms)
{
char host[80] = "";
store_lock();
const cJSON *dev = cJSON_GetObjectItem(store_coll("device"), id);
const cJSON *addr = dev ? cJSON_GetObjectItem(dev, "address") : NULL;
if (cJSON_IsString(addr)) {
snprintf(host, sizeof(host), "%s", addr->valuestring);
}
store_unlock();
if (!host[0]) { // the device was removed while the request waited
return false;
}
xSemaphoreTake(s_mu, portMAX_DELAY);
link_t *l = link_for(id);
char ip[16] = "";
if (l) {
snprintf(ip, sizeof(ip), "%s", l->ip);
}
xSemaphoreGive(s_mu);
if (!l) {
return false;
}
if (l->fd < 0) {
if (esp_timer_get_time() < l->retry_us) {
return false;
}
l->fd = ws_client_connect(ip[0] ? ip : host, "/ws");
if (l->fd < 0) {
mark_down(l);
return false;
}
ESP_LOGI(TAG, "connected to %s", id);
}
size_t need = strlen(body) + strlen(path) + strlen(method) + 64;
char *msg = malloc(need);
bool ok = false;
int64_t t0 = esp_timer_get_time();
if (msg) {
int n = snprintf(msg, need, "{\"method\":\"%s\",\"path\":\"%s\",\"body\":%s}", method, path, body);
ok = n > 0 && (size_t)n < need && ws_client_send_text(l->fd, msg, (size_t)n) == ESP_OK &&
ws_client_recv_text(l->fd, reply, cap) >= 0;
free(msg);
}
if (!ok) {
ESP_LOGW(TAG, "request to %s failed", id);
mark_down(l);
return false;
}
if (rtt_ms) {
*rtt_ms = (int)((esp_timer_get_time() - t0) / 1000);
}
xSemaphoreTake(s_mu, portMAX_DELAY);
l->up = true;
xSemaphoreGive(s_mu);
l->fails = 0;
return true;
}
static void run_job(job_t *j)
{
char reply[REPLY_MAX];
exchange(j->id, j->method, j->path, j->body, reply, sizeof(reply), NULL);
free(j->body);
}
// Ask every Wi-Fi driver for its status and record the round trip (-1 when it does not answer)
// The driver's MAC from its status reply (an envelope whose body is the status JSON). The MAC is the
// same in both modes, so it ties a board's Wi-Fi record to its ESP-NOW record.
static void learn_mac(const char *id, const char *reply)
{
cJSON *env = cJSON_Parse(reply);
const cJSON *b = env ? cJSON_GetObjectItem(env, "body") : NULL;
cJSON *st = cJSON_IsString(b) ? cJSON_Parse(b->valuestring) : NULL;
const cJSON *m = st ? cJSON_GetObjectItem(st, "mac") : NULL;
if (cJSON_IsString(m) && strlen(m->valuestring) == 12) {
engine_wifi_mac(id, m->valuestring);
}
cJSON_Delete(st);
cJSON_Delete(env);
}
static void run_ping(void)
{
char ids[PING_MAX][WIFI_DRV_ID_MAX + 1];
int n = 0;
store_lock();
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
const cJSON *tr = cJSON_GetObjectItem(d, "transport");
if (n < PING_MAX && cJSON_IsString(tr) && !strcmp(tr->valuestring, "wifi")) {
snprintf(ids[n], sizeof(ids[n]), "%s", d->string);
n++;
}
}
store_unlock();
for (int i = 0; i < n; i++) {
char reply[REPLY_MAX];
int rtt = -1;
bool ok = exchange(ids[i], "GET", "/api/status", "{}", reply, sizeof(reply), &rtt);
if (ok) {
learn_mac(ids[i], reply);
}
xSemaphoreTake(s_mu, portMAX_DELAY);
memcpy(s_ping.r[i].id, ids[i], sizeof(s_ping.r[i].id)); // both 13 bytes, NUL-terminated
s_ping.r[i].rtt_ms = ok ? rtt : -1;
s_ping.n = i + 1;
xSemaphoreGive(s_mu);
}
xSemaphoreTake(s_mu, portMAX_DELAY);
s_ping.busy = false;
xSemaphoreGive(s_mu);
xSemaphoreGive(s_ping_done);
}
static void sender_task(void *arg)
{
(void)arg;
job_t j;
for (;;) {
if (xQueueReceive(s_q, &j, portMAX_DELAY) == pdTRUE) {
if (j.ping) {
run_ping();
} else {
run_job(&j);
}
}
}
}
void wifi_drv_init(void)
{
if (s_q) {
return;
}
s_mu = xSemaphoreCreateMutex();
s_ping_done = xSemaphoreCreateBinary();
s_q = xQueueCreate(QUEUE_LEN, sizeof(job_t));
if (!s_mu || !s_ping_done || !s_q || xTaskCreate(sender_task, "wifi_drv", 6144, NULL, 4, NULL) != pdPASS) {
ESP_LOGE(TAG, "cannot start the sender");
}
}
void wifi_drv_post(const char *id, const char *path, cJSON *body)
{
wifi_drv_init();
job_t j = {};
snprintf(j.id, sizeof(j.id), "%s", id);
snprintf(j.method, sizeof(j.method), "POST");
snprintf(j.path, sizeof(j.path), "%s", path);
j.body = cJSON_PrintUnformatted(body);
cJSON_Delete(body);
if (!j.body) {
return;
}
if (strlen(j.body) > BODY_MAX || !s_q || xQueueSend(s_q, &j, 0) != pdTRUE) {
ESP_LOGW(TAG, "dropped a request to %s", id);
free(j.body);
}
}
static cJSON *rgb_json(const uint8_t rgb[3]);
#define IDENTIFY_MS 2000
static void identify_off_task(void *arg)
{
char *id = arg;
vTaskDelay(pdMS_TO_TICKS(IDENTIFY_MS));
cJSON *body = cJSON_CreateObject();
cJSON_AddStringToObject(body, "pattern", "off");
wifi_drv_post(id, "/api/pattern", body);
free(id);
vTaskDelete(NULL);
}
void wifi_drv_identify(const char *id)
{
static const uint8_t red[3] = { 255, 0, 0 };
cJSON *body = cJSON_CreateObject();
cJSON_AddStringToObject(body, "pattern", "blink");
cJSON *cols = cJSON_AddArrayToObject(body, "colors");
cJSON_AddItemToArray(cols, rgb_json(red));
cJSON_AddNumberToObject(body, "delay", 50);
cJSON_AddNumberToObject(body, "brightness", 128);
wifi_drv_post(id, "/api/pattern", body);
char *copy = strdup(id);
if (!copy || xTaskCreate(identify_off_task, "wifi_ident", 3072, copy, 3, NULL) != pdPASS) {
ESP_LOGW(TAG, "identify %s: no timer, the blink stays on", id);
free(copy);
}
}
int wifi_drv_ping_all(int timeout_ms, wifi_drv_ping_t out[], int max)
{
if (!s_q) {
return 0;
}
xSemaphoreTake(s_mu, portMAX_DELAY);
bool busy = s_ping.busy;
if (!busy) {
s_ping.busy = true;
s_ping.n = 0;
}
xSemaphoreGive(s_mu);
if (!busy) {
xSemaphoreTake(s_ping_done, 0); // drop a signal left by an earlier batch that timed out
job_t j = {};
j.ping = true;
if (xQueueSend(s_q, &j, 0) != pdTRUE) {
xSemaphoreTake(s_mu, portMAX_DELAY);
s_ping.busy = false;
xSemaphoreGive(s_mu);
return 0;
}
}
// Wait for the batch; if it runs past the timeout, report the replies that came in so far
xSemaphoreTake(s_ping_done, pdMS_TO_TICKS(timeout_ms));
xSemaphoreTake(s_mu, portMAX_DELAY);
int n = s_ping.n < max ? s_ping.n : max;
for (int i = 0; i < n; i++) {
out[i] = s_ping.r[i];
}
xSemaphoreGive(s_mu);
return n;
}
bool wifi_drv_connected(const char *id)
{
bool up = false;
if (!s_mu) {
return false;
}
xSemaphoreTake(s_mu, portMAX_DELAY);
for (int i = 0; i < LINKS_MAX; i++) {
if (s_links[i].id[0] && !strcmp(s_links[i].id, id)) {
up = s_links[i].up;
}
}
xSemaphoreGive(s_mu);
return up;
}
/* ------------------------------------------------------------ preset body */
static uint8_t clamp8(int v)
{
return (uint8_t)(v < 0 ? 0 : (v > 255 ? 255 : v));
}
// [r,g,b] or a "#RRGGBB" / "RRGGBB" string
static bool read_rgb(const cJSON *v, uint8_t rgb[3])
{
if (cJSON_IsArray(v)) {
if (cJSON_GetArraySize(v) != 3) {
return false;
}
for (int i = 0; i < 3; i++) {
const cJSON *c = cJSON_GetArrayItem(v, i);
if (!cJSON_IsNumber(c)) {
return false;
}
rgb[i] = clamp8((int)c->valuedouble);
}
return true;
}
if (!cJSON_IsString(v)) {
return false;
}
const char *s = v->valuestring;
if (*s == '#') {
s++;
}
if (strlen(s) != 6) {
return false;
}
for (int i = 0; i < 6; i++) {
if (!isxdigit((unsigned char)s[i])) {
return false;
}
}
unsigned x = (unsigned)strtoul(s, NULL, 16);
rgb[0] = (x >> 16) & 0xFF;
rgb[1] = (x >> 8) & 0xFF;
rgb[2] = x & 0xFF;
return true;
}
static cJSON *rgb_json(const uint8_t rgb[3])
{
cJSON *a = cJSON_CreateArray();
for (int i = 0; i < 3; i++) {
cJSON_AddItemToArray(a, cJSON_CreateNumber(rgb[i]));
}
return a;
}
static void copy_number(cJSON *o, const cJSON *src, const char *from, const char *to)
{
const cJSON *v = cJSON_GetObjectItem(src, from);
if (cJSON_IsNumber(v)) {
cJSON_AddNumberToObject(o, to, v->valuedouble);
}
}
cJSON *wifi_drv_preset_body(const cJSON *p)
{
if (!cJSON_IsObject(p)) {
return NULL;
}
cJSON *o = cJSON_CreateObject();
const cJSON *v = cJSON_GetObjectItem(p, "pattern");
if (cJSON_IsString(v)) {
cJSON_AddStringToObject(o, "pattern", v->valuestring);
}
v = cJSON_GetObjectItem(p, "colors");
if (cJSON_IsArray(v)) {
cJSON *cols = cJSON_AddArrayToObject(o, "colors");
const cJSON *c;
cJSON_ArrayForEach(c, v)
{
uint8_t rgb[3];
if (read_rgb(c, rgb)) {
cJSON_AddItemToArray(cols, rgb_json(rgb));
}
}
}
uint8_t bg[3];
v = cJSON_GetObjectItem(p, "background");
if (!v) {
v = cJSON_GetObjectItem(p, "bg");
}
if (v && read_rgb(v, bg)) {
cJSON_AddItemToObject(o, "background", rgb_json(bg));
}
copy_number(o, p, "delay", "delay");
copy_number(o, p, "brightness", "brightness");
// A selected preset is applied on top of the one the driver is running (POST /api/pattern), so fields it
// leaves out carry over: fade and beat timing are always sent, or "off" after "on" would fade for on's 10 s
const cJSON *fade = cJSON_GetObjectItem(p, "fade");
if (!cJSON_IsNumber(fade)) {
fade = cJSON_GetObjectItem(p, "f");
}
cJSON_AddNumberToObject(o, "fade", cJSON_IsNumber(fade) && fade->valuedouble > 0 ? fade->valuedouble : 0);
const cJSON *tb = cJSON_GetObjectItem(p, "beat_time");
if (!tb) {
tb = cJSON_GetObjectItem(p, "tb");
}
cJSON_AddBoolToObject(o, "beat_time", cJSON_IsTrue(tb) || (cJSON_IsNumber(tb) && tb->valuedouble != 0));
copy_number(o, p, "n1", "n1");
copy_number(o, p, "n2", "n2");
copy_number(o, p, "n3", "n3");
copy_number(o, p, "n4", "n4");
copy_number(o, p, "n6", "mode"); // the style mode travels as n6 on the controller
v = cJSON_GetObjectItem(p, "reverse");
if (cJSON_IsBool(v)) {
cJSON_AddBoolToObject(o, "reverse", cJSON_IsTrue(v));
}
return o;
}
/* ------------------------------------------------------------ discovery */
#if !defined(CONFIG_IDF_TARGET_LINUX) || defined(LED_DESKTOP_MDNS)
// A driver seen on mDNS: register it as a wifi device the first time, and remember its address
static void note_driver(const char *host, const char *ip)
{
bool added = false;
store_lock();
cJSON *all = store_coll("device");
if (!cJSON_GetObjectItem(all, host)) {
char addr[WIFI_DRV_ID_MAX + 8];
snprintf(addr, sizeof(addr), "%s.local", host);
cJSON *d = cJSON_CreateObject();
cJSON_AddStringToObject(d, "name", host);
cJSON_AddStringToObject(d, "type", "led");
cJSON_AddStringToObject(d, "transport", "wifi");
cJSON_AddStringToObject(d, "address", addr);
cJSON_AddItemToObject(d, "zones", cJSON_CreateArray());
cJSON_AddNullToObject(d, "default_pattern");
cJSON_AddStringToObject(d, "id", host);
cJSON_AddItemToObject(all, host, d);
store_save("device");
added = true;
}
store_unlock();
if (added) {
ESP_LOGI(TAG, "found Wi-Fi driver %s at %s", host, ip);
}
xSemaphoreTake(s_mu, portMAX_DELAY);
link_t *l = link_for(host);
if (l) {
snprintf(l->ip, sizeof(l->ip), "%s", ip);
}
xSemaphoreGive(s_mu);
}
static void discover_task(void *arg)
{
(void)arg;
for (;;) {
mdns_result_t *res = NULL;
if (mdns_query_ptr("_http", "_tcp", 1500, 30, &res) == ESP_OK && res) {
for (mdns_result_t *r = res; r; r = r->next) {
if (!r->hostname || strlen(r->hostname) > WIFI_DRV_ID_MAX) {
continue;
}
bool is_strip = false;
for (size_t i = 0; i < r->txt_count && r->txt; i++) {
if (r->txt[i].key && r->txt[i].value && !strcmp(r->txt[i].key, "app") &&
!strcmp(r->txt[i].value, "led-strip")) {
is_strip = true;
}
}
char ip[16] = "";
for (mdns_ip_addr_t *a = r->addr; is_strip && a && !ip[0]; a = a->next) {
if (a->addr.type == ESP_IPADDR_TYPE_V4) {
snprintf(ip, sizeof(ip), IPSTR, IP2STR(&a->addr.u_addr.ip4));
}
}
if (is_strip && ip[0]) {
char host[WIFI_DRV_ID_MAX + 1];
snprintf(host, sizeof(host), "%s", r->hostname);
note_driver(host, ip);
}
}
}
if (res) {
mdns_query_results_free(res);
}
// Ping the drivers too: a board that switched mode is merged by its MAC
wifi_drv_ping_t pr[WIFI_DRV_PING_MAX];
wifi_drv_ping_all(2000, pr, WIFI_DRV_PING_MAX);
vTaskDelay(pdMS_TO_TICKS(DISCOVER_MS));
}
}
void wifi_drv_start_discovery(void)
{
static bool started;
if (started) {
return;
}
started = true;
wifi_drv_init();
xTaskCreate(discover_task, "wifi_disc", 4096, NULL, 3, NULL);
}
#else
void wifi_drv_start_discovery(void)
{
}
#endif
+37
View File
@@ -0,0 +1,37 @@
// Wi-Fi LED drivers (the cpp led-driver): found by mDNS (_http._tcp, TXT app=led-strip) and driven
// through its JSON API over a WebSocket (/ws). A device's id is its hostname, 12 characters or fewer.
#pragma once
#include <stdbool.h>
#include "cJSON.h"
#define WIFI_DRV_ID_MAX 12
#define WIFI_DRV_PING_MAX 16 // most Wi-Fi drivers in one ping
// Start the send queue and sender task. Safe to call more than once.
void wifi_drv_init(void);
// Board only: browse mDNS every 30 s and add each new led-strip driver as a wifi device. Needs mdns up.
void wifi_drv_start_discovery(void);
// True while the driver's WebSocket is open and its last request was answered
bool wifi_drv_connected(const char *id);
// Queue POST path with body (a JSON object, freed here) to the driver id. Never blocks; drops when full.
void wifi_drv_post(const char *id, const char *path, cJSON *body);
// A driver preset body (/api/pattern fields) from a stored or pushed preset; NULL if not an object
cJSON *wifi_drv_preset_body(const cJSON *preset);
// Identify a Wi-Fi driver: red blink at 10 Hz (brightness 128) for 2 s, then off
void wifi_drv_identify(const char *id);
// One Wi-Fi driver's answer to a ping: its id and round trip in ms (-1 when it did not answer)
typedef struct {
char id[WIFI_DRV_ID_MAX + 1];
int rtt_ms;
} wifi_drv_ping_t;
// Ping every Wi-Fi driver (GET /api/status over its link) and wait up to timeout_ms for the answers.
// Copies up to max results into out and returns how many; returns 0 when there are no drivers.
int wifi_drv_ping_all(int timeout_ms, wifi_drv_ping_t out[], int max);
+171
View File
@@ -0,0 +1,171 @@
// SPDX-License-Identifier: Apache-2.0
// Minimal WebSocket client (RFC 6455, text frames only). Port of led-driver/main/ws_client.cpp.
#include "ws_client.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "esp_log.h"
#include "esp_random.h"
#include "lwip/netdb.h"
#include "lwip/sockets.h"
static const char *TAG = "ws_client";
#define WS_TIMEOUT_MS 2000
// Read until the buffer holds the end of the handshake reply. Returns the bytes read, or -1.
static int read_handshake(int fd, char *buf, size_t cap)
{
size_t got = 0;
while (got < cap - 1) {
int r = recv(fd, buf + got, cap - 1 - got, 0);
if (r <= 0) {
return -1;
}
got += r;
buf[got] = '\0';
if (strstr(buf, "\r\n\r\n")) {
return (int)got;
}
}
return -1;
}
int ws_client_connect(const char *host, const char *path)
{
struct addrinfo hints = {};
struct addrinfo *res = NULL;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(host, "80", &hints, &res) != 0 || !res) {
ESP_LOGW(TAG, "cannot resolve %s", host);
return -1;
}
int fd = socket(res->ai_family, res->ai_socktype, 0);
if (fd < 0) {
freeaddrinfo(res);
return -1;
}
struct timeval tv = { .tv_sec = WS_TIMEOUT_MS / 1000, .tv_usec = (WS_TIMEOUT_MS % 1000) * 1000 };
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
int one = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
if (connect(fd, res->ai_addr, res->ai_addrlen) != 0) {
freeaddrinfo(res);
close(fd);
return -1;
}
freeaddrinfo(res);
char req[256];
int n = snprintf(req, sizeof(req),
"GET %s HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n",
path, host);
if (n <= 0 || n >= (int)sizeof(req) || send(fd, req, n, 0) != n) {
close(fd);
return -1;
}
char reply[256];
if (read_handshake(fd, reply, sizeof(reply)) < 0 || strncmp(reply, "HTTP/1.1 101", 12) != 0) {
ESP_LOGW(TAG, "handshake with %s failed", host);
close(fd);
return -1;
}
return fd;
}
// Client frames are masked (RFC 6455). The mask only has to vary, not be secret.
esp_err_t ws_client_send_text(int fd, const char *data, size_t len)
{
if (len > 2048) {
return ESP_ERR_INVALID_SIZE;
}
size_t hdr = len < 126 ? 2 : 4;
size_t total = hdr + 4 + len;
uint8_t *frame = (uint8_t *)malloc(total);
if (!frame) {
return ESP_ERR_NO_MEM;
}
uint8_t mask[4];
esp_fill_random(mask, sizeof(mask));
frame[0] = 0x81; // FIN, text
if (len < 126) {
frame[1] = 0x80 | (uint8_t)len;
} else {
frame[1] = 0x80 | 126;
frame[2] = (uint8_t)(len >> 8);
frame[3] = (uint8_t)len;
}
memcpy(&frame[hdr], mask, 4);
for (size_t i = 0; i < len; i++) {
frame[hdr + 4 + i] = (uint8_t)data[i] ^ mask[i & 3];
}
esp_err_t err = send(fd, frame, total, 0) == (ssize_t)total ? ESP_OK : ESP_FAIL;
free(frame);
return err;
}
static bool read_n(int fd, uint8_t *dst, size_t n)
{
size_t got = 0;
while (got < n) {
int r = recv(fd, dst + got, n - got, 0);
if (r <= 0) {
return false;
}
got += r;
}
return true;
}
// Server frames are not masked. Only text frames are returned; other opcodes are skipped.
int ws_client_recv_text(int fd, char *buf, size_t cap)
{
for (;;) {
uint8_t h[2];
if (!read_n(fd, h, 2)) {
return -1;
}
size_t len = h[1] & 0x7F;
if (len == 126) {
uint8_t ext[2];
if (!read_n(fd, ext, 2)) {
return -1;
}
len = (ext[0] << 8) | ext[1];
} else if (len == 127) {
return -1;
}
bool masked = (h[1] & 0x80) != 0;
uint8_t mask[4] = {};
if (masked && !read_n(fd, mask, 4)) {
return -1;
}
if (len + 1 > cap) {
return -1;
}
if (!read_n(fd, (uint8_t *)buf, len)) {
return -1;
}
for (size_t i = 0; masked && i < len; i++) {
buf[i] ^= mask[i & 3];
}
if ((h[0] & 0x0F) == 0x1) {
buf[len] = '\0';
return (int)len;
}
if ((h[0] & 0x0F) == 0x8) {
return -1;
}
}
}
void ws_client_close(int fd)
{
if (fd >= 0) {
close(fd);
}
}
+18
View File
@@ -0,0 +1,18 @@
// Minimal WebSocket client for talking to a Wi-Fi LED driver (the cpp driver's /ws). One connection per
// driver is kept open by wifi_drv.c. Port of led-driver/main/ws_client.cpp.
#pragma once
#include <stddef.h>
#include "esp_err.h"
/** @brief Open a WebSocket to host:port/path (port 80). ip may be used instead of host when non-NULL. Returns the socket, or -1. */
int ws_client_connect(const char *host, const char *path);
/** @brief Send one masked text frame (up to 2048 bytes). */
esp_err_t ws_client_send_text(int fd, const char *data, size_t len);
/** @brief Receive one text frame into buf (NUL-terminated). Returns the length, or -1 on error or timeout. */
int ws_client_recv_text(int fd, char *buf, size_t cap);
/** @brief Close a socket from ws_client_connect. */
void ws_client_close(int fd);