feat: DDP frame sync over UDP broadcast, DDP acks, DDP enable setting

- Driver acks each completed DDP frame; the test waits for the acks before broadcasting the sync.
- Sync listener on UDP 4049: a frame is held until the next sync, then shown.
- DDP pixels are shown at full brightness, ignoring the device brightness settings.
- "DDP and sync receive on" setting (NVS, network API, web UI); off ignores DDP and sync packets.
- ddp_test.py: finds devices on the subnet, drives them in lockstep at a fixed rate, runs animations.
- /api/ddp reports sync counters for diagnosis.
- Includes in-progress WebSocket, multi-driver web UI and Wi-Fi work from the same tree.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Haiku 5.5 committed 2026-11-11 14:10:55 +13:00
1 parent 47f4eba0d6
commit 4cd3bc7973
294 files changed
+48954 -301

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
idf_component_register(SRCS "main.cpp" "ws2812.cpp" "net.cpp" "settings.cpp" "web.cpp" "patterns.cpp" "presets.cpp"
"effects_util.cpp" "effects_a.cpp" "effects_b.cpp" "effects_rig.cpp" "ota.c" "ddp.cpp"
"effects_util.cpp" "ws_client.cpp" "effects_a.cpp" "effects_b.cpp" "effects_rig.cpp" "ota.c" "ddp.cpp"
PRIV_REQUIRES esp_driver_rmt esp_driver_gpio esp_wifi esp_netif esp_event
esp_timer nvs_flash esp_http_server esp_http_client cjson mdns esp_hw_support app_update esp_app_format lwip
INCLUDE_DIRS "."
+62 -2
View File
@@ -9,9 +9,17 @@
#include "freertos/task.h"
#include "lwip/sockets.h"
#include "patterns.h"
#include "settings.h"
static const char *TAG = "ddp";
static volatile bool s_enabled = true;
void ddp_set_enabled(bool on)
{
s_enabled = on;
}
// Header: flags, sequence, data type, destination, data offset (4), data length (2); with the timecode
// flag, 4 more bytes follow. Version 1 is flags bits 6-7 = 01.
#define DDP_FLAG_VER1 0x40
@@ -52,7 +60,12 @@ static void ddp_task(void *arg)
uint8_t buf[1500];
while (true) {
int n = recv(sock, buf, sizeof(buf), 0);
struct sockaddr_in src = {};
socklen_t srclen = sizeof(src);
int n = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *)&src, &srclen);
if (!s_enabled) {
continue;
}
if (n < DDP_HEADER) {
continue;
}
@@ -73,12 +86,59 @@ static void ddp_task(void *arg)
if (len > (size_t)n - hdr) {
len = (size_t)n - hdr;
}
patterns_ddp_write(offset, buf + hdr, len, (flags & 0x01) != 0);
bool push = (flags & 0x01) != 0;
patterns_ddp_write(offset, buf + hdr, len, push);
if (push) {
// Ack the completed frame to its sender ("LAK1" + the DDP seq). The sender broadcasts the
// sync only after this, so the frame is already held when the sync arrives.
uint8_t ack[5] = { 'L', 'A', 'K', '1', buf[1] };
sendto(sock, ack, sizeof(ack), 0, (struct sockaddr *)&src, srclen);
}
}
}
// Sync broadcasts: a frame that arrived by DDP is shown when the next sync arrives (see patterns.cpp).
static void ddp_sync_task(void *arg)
{
(void)arg;
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock < 0) {
ESP_LOGE(TAG, "sync socket failed");
vTaskDelete(NULL);
return;
}
struct sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(DDP_SYNC_PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
ESP_LOGE(TAG, "bind to sync port %d failed", DDP_SYNC_PORT);
close(sock);
vTaskDelete(NULL);
return;
}
ESP_LOGI(TAG, "sync listening on UDP port %d", DDP_SYNC_PORT);
uint8_t buf[64];
while (true) {
int n = recv(sock, buf, sizeof(buf), 0);
if (!s_enabled || n < 8 || memcmp(buf, "LSY1", 4) != 0) {
continue;
}
patterns_ddp_sync(be32(buf + 4));
}
}
esp_err_t ddp_start(void)
{
net_cfg_t net;
if (settings_load_net(&net) == ESP_OK) {
s_enabled = net.ddp_enabled;
}
BaseType_t ok = xTaskCreate(ddp_task, "ddp", 4096, NULL, 4, NULL);
if (ok != pdPASS) {
return ESP_ERR_NO_MEM;
}
ok = xTaskCreate(ddp_sync_task, "ddp_sync", 3072, NULL, 4, NULL);
return ok == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
}
+5 -1
View File
@@ -9,6 +9,10 @@
#include "esp_err.h"
#define DDP_PORT 4048
#define DDP_SYNC_PORT 4049 // UDP broadcast sync: "LSY1" + seq (u32, big endian)
/** @brief Start listening for DDP packets. */
/** @brief Start listening for DDP packets and sync broadcasts. Off if the saved setting is off. */
esp_err_t ddp_start(void);
/** @brief Turn DDP pixels and sync reception on or off. Packets are ignored while off. */
void ddp_set_enabled(bool on);
+4 -2
View File
@@ -296,8 +296,10 @@ bool fx_chase(fx_t &f, st_t &s)
rgb color1 = ab(nc > 1 ? c[1] : c[0], b);
int n1 = nz(f.pr->n[1], 1);
int n2 = nz(f.pr->n[2], 1);
int n3 = sgn(f, f.pr->n[3]);
int n4 = sgn(f, f.pr->n[4]);
// Always move forward: a negative n3/n4 would otherwise make the dot bounce back.
// sgn() still applies the preset's reverse flag.
int n3 = sgn(f, abs(f.pr->n[3]));
int n4 = sgn(f, abs(f.pr->n[4]));
int seg = n1 + n2;
int max_pos = nled + seg;
auto position = [&](int sc) {
+105 -25
View File
@@ -26,6 +26,17 @@ static volatile bool s_sta_up;
static esp_ip4_addr_t s_sta_ip;
static int s_retries;
// The access point. It can be turned off in settings, as long as the client is connected. If the client
// then stays down for about a minute (AP_FALLBACK_RETRIES reconnect attempts), the access point comes back.
#define AP_FALLBACK_RETRIES 6
static volatile bool s_ap_on;
static bool s_ap_want; // the state ap_timer switches to
static esp_timer_handle_t s_ap_timer;
// A saved network change reconnects the client a moment later, so the reply to the request still gets out
static esp_timer_handle_t s_reconnect_timer;
static net_cfg_t s_pending_net;
// Set the STA config from credentials. Empty password means an open network.
static void apply_sta_config(const wifi_creds_t *c)
{
@@ -36,6 +47,58 @@ static void apply_sta_config(const wifi_creds_t *c)
esp_wifi_set_config(WIFI_IF_STA, &cfg);
}
// Turn the access point on (with its led-XXXXXX name, open) or off. The client keeps running either way.
static void apply_ap(bool on)
{
if (on) {
char ssid[16];
net_ap_ssid(ssid, sizeof(ssid));
wifi_config_t ap = {};
strncpy((char *)ap.ap.ssid, ssid, sizeof(ap.ap.ssid) - 1);
ap.ap.ssid_len = strlen(ssid);
ap.ap.channel = AP_CHANNEL;
ap.ap.max_connection = AP_MAX_CLIENTS;
ap.ap.authmode = WIFI_AUTH_OPEN;
esp_wifi_set_config(WIFI_IF_AP, &ap);
esp_wifi_set_mode(WIFI_MODE_APSTA);
ESP_LOGI(TAG, "Access point %s on", ssid);
} else {
esp_wifi_set_mode(WIFI_MODE_STA);
ESP_LOGI(TAG, "Access point off");
}
s_ap_on = on;
}
// Switch the access point later, from a timer task (not inside a Wi-Fi event)
static void ap_timer_cb(void *arg)
{
(void)arg;
if (s_ap_want != s_ap_on) {
apply_ap(s_ap_want);
}
}
static esp_err_t apply_client_ip(const net_cfg_t *c);
static void reconnect_cb(void *arg)
{
(void)arg;
esp_timer_stop(s_retry_timer);
esp_wifi_disconnect();
s_retries = 0;
if (apply_client_ip(&s_pending_net) != ESP_OK) {
ESP_LOGW(TAG, "Client address could not be applied");
}
esp_wifi_connect();
}
static void ap_switch_later(bool on, uint64_t delay_us)
{
s_ap_want = on;
esp_timer_stop(s_ap_timer); // not running is fine
esp_timer_start_once(s_ap_timer, delay_us);
}
// Client address: DHCP, or the static address from settings. Called before the client connects.
static esp_err_t apply_client_ip(const net_cfg_t *c)
{
@@ -99,6 +162,9 @@ static void on_wifi_event(void *arg, esp_event_base_t base, int32_t id, void *da
s_retries++;
esp_timer_stop(s_retry_timer);
esp_timer_start_once(s_retry_timer, (uint64_t)delay_ms * 1000);
if (!s_ap_on && s_retries >= AP_FALLBACK_RETRIES) {
ap_switch_later(true, 1000000); // the client keeps failing: bring the access point back
}
break;
}
default:
@@ -146,31 +212,39 @@ esp_err_t net_start(void)
};
ESP_ERROR_CHECK(esp_timer_create(&timer_args, &s_retry_timer));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA));
const esp_timer_create_args_t ap_args = {
.callback = ap_timer_cb,
.arg = NULL,
.dispatch_method = ESP_TIMER_TASK,
.name = "ap_switch",
.skip_unhandled_events = false,
};
ESP_ERROR_CHECK(esp_timer_create(&ap_args, &s_ap_timer));
// Open access point named led-XXXXXX
char ssid[16];
net_ap_ssid(ssid, sizeof(ssid));
wifi_config_t ap = {};
strncpy((char *)ap.ap.ssid, ssid, sizeof(ap.ap.ssid) - 1);
ap.ap.ssid_len = strlen(ssid);
ap.ap.channel = AP_CHANNEL;
ap.ap.max_connection = AP_MAX_CLIENTS;
ap.ap.authmode = WIFI_AUTH_OPEN;
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap));
const esp_timer_create_args_t reconnect_args = {
.callback = reconnect_cb,
.arg = NULL,
.dispatch_method = ESP_TIMER_TASK,
.name = "wifi_reconnect",
.skip_unhandled_events = false,
};
ESP_ERROR_CHECK(esp_timer_create(&reconnect_args, &s_reconnect_timer));
// Client credentials, if any were saved
// The access point is on unless turned off. With no client Wi-Fi saved it stays on, so the device
// can always be reached and set up.
net_cfg_t n;
settings_load_net(&n);
wifi_creds_t c;
if (settings_load_wifi(&c) == ESP_OK && c.ssid[0]) {
const bool has_creds = settings_load_wifi(&c) == ESP_OK && c.ssid[0];
apply_ap(n.ap_enabled || !has_creds);
if (has_creds) {
apply_sta_config(&c);
}
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(TAG, "AP %s started", ssid);
// mDNS: <hostname>.local, with an HTTP service on port 80
net_cfg_t n;
settings_load_net(&n);
ESP_ERROR_CHECK(mdns_init());
ESP_ERROR_CHECK(mdns_hostname_set(n.hostname));
ESP_ERROR_CHECK(mdns_instance_name_set("LED controller"));
@@ -208,6 +282,12 @@ esp_err_t net_sta_connect(const wifi_creds_t *c)
esp_err_t net_save_network(const net_cfg_t *c)
{
// Turning the access point off needs a connected client, or the device could not be reached again
net_cfg_t old;
settings_load_net(&old);
if (!c->ap_enabled && old.ap_enabled && !s_sta_up) {
return ESP_ERR_INVALID_STATE;
}
esp_err_t err = settings_save_net(c);
if (err != ESP_OK) {
return err;
@@ -216,19 +296,19 @@ esp_err_t net_save_network(const net_cfg_t *c)
if (err != ESP_OK) {
return err;
}
// Reconnect with the new address settings if a client is configured
if (c->ap_enabled != s_ap_on) {
// After the reply has gone out, so the page that asked still gets it
ap_switch_later(c->ap_enabled, c->ap_enabled ? 1000000 : 1500000);
}
// Reconnect with the new address settings if a client is configured (after the reply, see reconnect_cb)
wifi_creds_t w;
if (settings_load_wifi(&w) != ESP_OK || !w.ssid[0]) {
return ESP_OK;
}
esp_timer_stop(s_retry_timer);
esp_wifi_disconnect();
s_retries = 0;
err = apply_client_ip(c);
if (err != ESP_OK) {
return err;
}
return esp_wifi_connect();
s_pending_net = *c;
esp_timer_stop(s_reconnect_timer);
esp_timer_start_once(s_reconnect_timer, 1000000);
return ESP_OK;
}
esp_err_t net_scan(wifi_ap_record_t *recs, uint16_t *count)
+89 -16
View File
@@ -94,8 +94,18 @@ static uint32_t s_ddp_packets;
static uint32_t s_ddp_frames; // frames completed (PUSH seen)
static uint32_t s_ddp_sum; // checksum of the last completed frame
static uint32_t s_ddp_log_ms; // last serial summary
// Frame sync: while syncs keep arriving, a completed DDP frame waits for the next sync before it is shown
#define DDP_SYNC_TIMEOUT_MS 2000
static uint8_t s_ddp_show[FX_LEDS_MAX * 3]; // the frame the strip shows
static uint8_t s_ddp_held[FX_LEDS_MAX * 3]; // a completed frame waiting for a sync
static bool s_ddp_held_ok;
static uint32_t s_sync_last_ms; // 0: never
static uint32_t s_sync_seq; // seq of the last sync
static uint32_t s_sync_count;
static uint32_t s_ddp_shown; // frames shown
static uint8_t s_max_brightness = 255;
static uint8_t s_global = 255;
static uint8_t s_master = 255;
static uint32_t s_fade_t0;
static uint32_t s_fade_ms;
@@ -190,6 +200,21 @@ uint8_t patterns_get_global(void)
return v;
}
void patterns_set_master(uint8_t level)
{
xSemaphoreTake(s_lock, portMAX_DELAY);
s_master = level;
xSemaphoreGive(s_lock);
}
uint8_t patterns_get_master(void)
{
xSemaphoreTake(s_lock, portMAX_DELAY);
uint8_t v = s_master;
xSemaphoreGive(s_lock);
return v;
}
void patterns_get(preset_t *out)
{
xSemaphoreTake(s_lock, portMAX_DELAY);
@@ -203,9 +228,11 @@ static uint32_t now_ms(void)
}
// Show the shadow frame, crossfading from the previous frame while a fade runs
static void output(uint32_t now)
static void output(uint32_t now, bool full_brightness)
{
int s_scale = s_global * s_max_brightness / 255; // global brightness under the ceiling
// device brightness x master scale, under the max brightness ceiling. DDP frames are shown at
// full brightness: the sender sets the colours.
int s_scale = full_brightness ? 255 : s_global * s_master / 255 * s_max_brightness / 255;
int k = -1;
if (s_fading) {
uint32_t el = now - s_fade_t0;
@@ -342,14 +369,14 @@ static void patterns_task(void *arg)
s_fx.t = now - g_st.t0;
if (ddp_on) {
for (int i = 0; i < s_fx.n; i++) {
s_fx.px[i] = { s_ddp[3 * i], s_ddp[3 * i + 1], s_ddp[3 * i + 2] };
s_fx.px[i] = { s_ddp_show[3 * i], s_ddp_show[3 * i + 1], s_ddp_show[3 * i + 2] };
}
} else if (!g_st.done) {
if (kPatterns[s_run.pattern].fn(s_fx, g_st)) {
g_st.done = true;
}
}
output(now);
output(now, ddp_on);
xSemaphoreGive(s_lock);
vTaskDelay(pdMS_TO_TICKS(FRAME_MS));
}
@@ -378,6 +405,7 @@ void patterns_start(const hw_cfg_t &hw)
s_fx.n = n;
s_max_brightness = hw.max_brightness;
s_global = hw.global_brightness;
s_master = hw.master_brightness;
s_strip = new WS2812((gpio_num_t)hw.pin, n);
s_strip->setOrder(hw.order);
s_strip->setBrightness(255); // brightness is applied per colour by the patterns
@@ -411,6 +439,27 @@ esp_err_t patterns_set_hardware(const hw_cfg_t &hw)
// ---- DDP ---------------------------------------------------------------------------------------
// Make a completed frame the one the strip shows, and log it. Caller holds s_lock.
static void ddp_show(const uint8_t *frame, uint32_t now)
{
size_t cap = (size_t)s_fx.n * 3;
memcpy(s_ddp_show, frame, cap);
s_ddp_shown++;
uint32_t sum = 0;
for (size_t i = 0; i < cap; i++) {
sum += frame[i];
}
s_ddp_sum = sum;
// Summary on the serial log, at most twice a second, so the test can check what was shown
if (now - s_ddp_log_ms >= 500) {
s_ddp_log_ms = now;
ESP_LOGI(TAG, "DDP frames=%u packets=%u sum=%u led0=%u,%u,%u led_last=%u,%u,%u",
(unsigned)s_ddp_frames, (unsigned)s_ddp_packets, (unsigned)s_ddp_sum,
frame[0], frame[1], frame[2],
frame[cap - 3], frame[cap - 2], frame[cap - 1]);
}
}
void patterns_ddp_write(uint32_t offset, const uint8_t *data, size_t len, bool push)
{
xSemaphoreTake(s_lock, portMAX_DELAY);
@@ -426,23 +475,34 @@ void patterns_ddp_write(uint32_t offset, const uint8_t *data, size_t len, bool p
s_ddp_packets++;
if (push) {
s_ddp_frames++;
uint32_t sum = 0;
for (size_t i = 0; i < cap; i++) {
sum += s_ddp[i];
}
s_ddp_sum = sum;
// Summary on the serial log, at most twice a second, so the test can check what was shown
if (now - s_ddp_log_ms >= 500) {
s_ddp_log_ms = now;
ESP_LOGI(TAG, "DDP frames=%u packets=%u sum=%u led0=%u,%u,%u led_last=%u,%u,%u",
(unsigned)s_ddp_frames, (unsigned)s_ddp_packets, (unsigned)s_ddp_sum,
s_ddp[0], s_ddp[1], s_ddp[2],
s_ddp[cap - 3], s_ddp[cap - 2], s_ddp[cap - 1]);
bool syncing = s_sync_last_ms != 0 && now - s_sync_last_ms < DDP_SYNC_TIMEOUT_MS;
if (syncing) {
// Syncs are arriving: hold the frame until the next one. The sender acks each frame before it
// sends the sync, so the frame is always here when its sync arrives.
memcpy(s_ddp_held, s_ddp, cap);
s_ddp_held_ok = true;
} else {
s_ddp_held_ok = false;
ddp_show(s_ddp, now);
}
}
xSemaphoreGive(s_lock);
}
void patterns_ddp_sync(uint32_t seq)
{
xSemaphoreTake(s_lock, portMAX_DELAY);
uint32_t now = now_ms();
s_sync_last_ms = now | 1; // never 0
s_sync_seq = seq;
s_sync_count++;
if (s_ddp_held_ok) {
s_ddp_held_ok = false;
ddp_show(s_ddp_held, now);
}
xSemaphoreGive(s_lock);
}
void patterns_ddp_status(bool *active, uint32_t *packets)
{
xSemaphoreTake(s_lock, portMAX_DELAY);
@@ -451,6 +511,19 @@ void patterns_ddp_status(bool *active, uint32_t *packets)
xSemaphoreGive(s_lock);
}
void patterns_ddp_debug(patterns_ddp_debug_t *out)
{
xSemaphoreTake(s_lock, portMAX_DELAY);
uint32_t now = now_ms();
out->syncs = s_sync_count;
out->sync_seq = s_sync_seq;
out->sync_age_ms = s_sync_last_ms != 0 ? now - s_sync_last_ms : UINT32_MAX;
out->frames = s_ddp_frames;
out->shown = s_ddp_shown;
out->held = s_ddp_held_ok;
xSemaphoreGive(s_lock);
}
void patterns_shown_pixel(int i, uint8_t out[3])
{
xSemaphoreTake(s_lock, portMAX_DELAY);
+16
View File
@@ -41,10 +41,22 @@ void patterns_select(const preset_t &p);
/** @brief DDP pixel data for the strip: byte offset into the RGB buffer, data, length. Replaces the pattern. */
void patterns_ddp_write(uint32_t offset, const uint8_t *data, size_t len, bool push);
void patterns_ddp_sync(uint32_t seq);
/** @brief Whether DDP pixels are arriving, and how many packets have come in. */
void patterns_ddp_status(bool *active, uint32_t *packets);
/** @brief Frame sync counters, for diagnosing the sync test. */
typedef struct {
uint32_t syncs; // sync packets received
uint32_t sync_seq; // seq of the last sync
uint32_t sync_age_ms; // ms since the last sync (UINT32_MAX: never)
uint32_t frames; // DDP frames completed (PUSH)
uint32_t shown; // frames shown on the strip
bool held; // a frame is waiting for the next sync
} patterns_ddp_debug_t;
void patterns_ddp_debug(patterns_ddp_debug_t *out);
/** @brief The colour last shown on LED i, as RGB. */
void patterns_shown_pixel(int i, uint8_t out[3]);
@@ -52,6 +64,10 @@ void patterns_shown_pixel(int i, uint8_t out[3]);
void patterns_set_global(uint8_t level);
uint8_t patterns_get_global(void);
/** @brief Master scale for this device, 0-255: multiplies the device brightness (under the max brightness ceiling). */
void patterns_set_master(uint8_t level);
uint8_t patterns_get_master(void);
/** @brief Copy of the preset being shown. */
void patterns_get(preset_t *out);
+15
View File
@@ -50,6 +50,7 @@ esp_err_t settings_load_hw(hw_cfg_t *c)
c->num_leds = 119;
c->pin = 10;
c->global_brightness = 255;
c->master_brightness = 255;
nvs_handle_t h;
if (nvs_open(NS, NVS_READONLY, &h) != ESP_OK) {
return ESP_OK;
@@ -72,6 +73,9 @@ esp_err_t settings_load_hw(hw_cfg_t *c)
if (nvs_get_u8(h, "global_bright", &mb) == ESP_OK) {
c->global_brightness = mb;
}
if (nvs_get_u8(h, "master_bright", &mb) == ESP_OK) {
c->master_brightness = mb;
}
nvs_close(h);
return ESP_OK;
}
@@ -88,6 +92,7 @@ esp_err_t settings_save_hw(const hw_cfg_t *c)
if (err == ESP_OK) err = nvs_set_i32(h, "num_leds", c->num_leds);
if (err == ESP_OK) err = nvs_set_i32(h, "pin", c->pin);
if (err == ESP_OK) err = nvs_set_u8(h, "global_bright", c->global_brightness);
if (err == ESP_OK) err = nvs_set_u8(h, "master_bright", c->master_brightness);
if (err == ESP_OK) err = nvs_commit(h);
nvs_close(h);
return err;
@@ -106,6 +111,8 @@ static void get_str(nvs_handle_t h, const char *key, char *buf, size_t len, cons
esp_err_t settings_load_net(net_cfg_t *c)
{
memset(c, 0, sizeof(*c));
c->ap_enabled = true;
c->ddp_enabled = true;
nvs_handle_t h;
esp_err_t err = nvs_open(NS, NVS_READONLY, &h);
if (err == ESP_ERR_NVS_NOT_FOUND) {
@@ -124,6 +131,12 @@ esp_err_t settings_load_net(net_cfg_t *c)
get_str(h, "netmask", c->netmask, sizeof(c->netmask), "");
get_str(h, "gateway", c->gateway, sizeof(c->gateway), "");
get_str(h, "dns", c->dns, sizeof(c->dns), "");
char ap[8];
get_str(h, "ap", ap, sizeof(ap), "on");
c->ap_enabled = strcmp(ap, "off") != 0;
char ddp[8];
get_str(h, "ddp", ddp, sizeof(ddp), "on");
c->ddp_enabled = strcmp(ddp, "off") != 0;
nvs_close(h);
return ESP_OK;
}
@@ -141,6 +154,8 @@ esp_err_t settings_save_net(const net_cfg_t *c)
if (err == ESP_OK) err = nvs_set_str(h, "netmask", c->netmask);
if (err == ESP_OK) err = nvs_set_str(h, "gateway", c->gateway);
if (err == ESP_OK) err = nvs_set_str(h, "dns", c->dns);
if (err == ESP_OK) err = nvs_set_str(h, "ap", c->ap_enabled ? "on" : "off");
if (err == ESP_OK) err = nvs_set_str(h, "ddp", c->ddp_enabled ? "on" : "off");
if (err == ESP_OK) err = nvs_commit(h);
nvs_close(h);
return err;
+4 -1
View File
@@ -19,6 +19,8 @@ struct net_cfg_t {
char netmask[16];
char gateway[16];
char dns[16]; // optional; empty uses the gateway
bool ap_enabled; // the access point (led-XXXXXX) is on; default on
bool ddp_enabled; // DDP pixels and frame sync are received; default on
};
/** @brief Read saved Wi-Fi client credentials. ESP_ERR_NVS_NOT_FOUND if none are saved. */
@@ -32,7 +34,8 @@ struct hw_cfg_t {
uint8_t max_brightness; // ceiling for every output colour, 0-255
int num_leds; // 1-512
int pin; // GPIO for the data line
uint8_t global_brightness; // live brightness for all patterns, 0-255 (under max_brightness)
uint8_t global_brightness; // this device's own brightness, 0-255 (under max_brightness)
uint8_t master_brightness; // master scale for this device, 0-255, set from "All devices"
};
/** @brief Read the LED strip settings. Missing keys get their defaults (grb, 255, 119). */
+539 -129
View File
@@ -11,6 +11,9 @@
#include "esp_http_server.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_timer.h"
#include <netinet/tcp.h>
#include <sys/socket.h>
#include "esp_wifi.h"
#include "net.h"
#include "ota.h"
@@ -20,6 +23,7 @@
#include "presets.h"
#include "settings.h"
#include "web.h"
#include "ws_client.h"
static const char *TAG = "web";
@@ -122,38 +126,74 @@ void web_allow_lan_origin(httpd_req_t *req)
httpd_resp_set_hdr(req, "Vary", "Origin");
}
static esp_err_t send_json(httpd_req_t *req, cJSON *obj)
// One API call, from an HTTP request or from a WebSocket message. Handlers use only the helpers
// below, so the same handler serves both.
typedef struct {
httpd_req_t *http; // the HTTP request, or NULL for a WebSocket call
const char *body; // WebSocket call: the request body text
const char *query; // WebSocket call: the query string after '?', or ""
char *out; // WebSocket call: the reply text is written here
size_t out_cap;
int status; // WebSocket call: the reply's status code
} api_req_t;
typedef esp_err_t (*api_fn_t)(api_req_t *req);
// Send a JSON reply. status is a status line such as "200 OK".
static esp_err_t send_text(api_req_t *req, const char *status, const char *text)
{
if (req->http) {
web_allow_lan_origin(req->http);
httpd_resp_set_status(req->http, status);
httpd_resp_set_type(req->http, "application/json");
return httpd_resp_sendstr(req->http, text);
}
req->status = atoi(status);
snprintf(req->out, req->out_cap, "%s", text);
return ESP_OK;
}
static esp_err_t send_json(api_req_t *req, cJSON *obj)
{
char *s = cJSON_PrintUnformatted(obj);
cJSON_Delete(obj);
web_allow_lan_origin(req);
if (!s) {
return httpd_resp_send_500(req);
return send_text(req, "500 Internal Server Error", "{\"error\":\"out of memory\"}");
}
httpd_resp_set_type(req, "application/json");
esp_err_t err = httpd_resp_sendstr(req, s);
esp_err_t err = send_text(req, "200 OK", s);
cJSON_free(s);
return err;
}
static esp_err_t send_error(httpd_req_t *req, const char *status, const char *msg)
static esp_err_t send_error(api_req_t *req, const char *status, const char *msg)
{
httpd_resp_set_status(req, status);
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "error", msg);
return send_json(req, o);
char *s = cJSON_PrintUnformatted(o);
cJSON_Delete(o);
esp_err_t err = send_text(req, status, s ? s : "{}");
cJSON_free(s);
return err;
}
// Read the request body into buf (NUL-terminated). False if missing, too big or unreadable.
static bool read_body(httpd_req_t *req, char *buf, size_t cap)
static bool read_body(api_req_t *req, char *buf, size_t cap)
{
int len = req->content_len;
if (!req->http) {
size_t n = req->body ? strlen(req->body) : 0;
if (n == 0 || n >= cap) {
return false;
}
memcpy(buf, req->body, n + 1);
return true;
}
int len = req->http->content_len;
if (len <= 0 || (size_t)len >= cap) {
return false;
}
int got = 0;
while (got < len) {
int r = httpd_req_recv(req, buf + got, len - got);
int r = httpd_req_recv(req->http, buf + got, len - got);
if (r <= 0) {
return false;
}
@@ -164,7 +204,7 @@ static bool read_body(httpd_req_t *req, char *buf, size_t cap)
}
// Read a JSON body; NULL (no reply sent) if missing, too big or not JSON. Caller frees with cJSON_Delete.
static cJSON *read_json(httpd_req_t *req)
static cJSON *read_json(api_req_t *req)
{
char body[MAX_BODY];
if (!read_body(req, body, sizeof(body))) {
@@ -190,7 +230,7 @@ static esp_err_t style_css_get(httpd_req_t *req)
}
// GET /api/status : the running preset (same fields as a preset), plus device and network state
static esp_err_t status_get(httpd_req_t *req)
static esp_err_t status_get(api_req_t *req)
{
preset_t p;
patterns_get(&p);
@@ -207,6 +247,7 @@ static esp_err_t status_get(httpd_req_t *req)
cJSON_AddStringToObject(o, "sta_ip", ip);
cJSON_AddStringToObject(o, "selected", presets_selected());
cJSON_AddNumberToObject(o, "global_brightness", patterns_get_global());
cJSON_AddNumberToObject(o, "master_brightness", patterns_get_master());
cJSON *modes = cJSON_AddArrayToObject(o, "patterns");
for (int i = 0; i < patterns_count(); i++) {
cJSON_AddItemToArray(modes, cJSON_CreateString(patterns_name(i)));
@@ -215,7 +256,7 @@ static esp_err_t status_get(httpd_req_t *req)
}
// POST /api/pattern : change the running settings. Fields missing from the body keep their value.
static esp_err_t pattern_post(httpd_req_t *req)
static esp_err_t pattern_post(api_req_t *req)
{
cJSON *in = read_json(req);
if (!in) {
@@ -233,7 +274,7 @@ static esp_err_t pattern_post(httpd_req_t *req)
}
// GET /api/wifi : saved client SSID and connection state
static esp_err_t wifi_get(httpd_req_t *req)
static esp_err_t wifi_get(api_req_t *req)
{
wifi_creds_t c = {};
settings_load_wifi(&c);
@@ -247,7 +288,7 @@ static esp_err_t wifi_get(httpd_req_t *req)
}
// POST /api/wifi {"ssid","password"} : save and connect
static esp_err_t wifi_post(httpd_req_t *req)
static esp_err_t wifi_post(api_req_t *req)
{
char body[MAX_BODY];
if (!read_body(req, body, sizeof(body))) {
@@ -285,7 +326,7 @@ static esp_err_t wifi_post(httpd_req_t *req)
}
// GET /api/wifi/scan : visible networks
static esp_err_t wifi_scan_get(httpd_req_t *req)
static esp_err_t wifi_scan_get(api_req_t *req)
{
static wifi_ap_record_t recs[MAX_SCAN];
uint16_t count = MAX_SCAN;
@@ -330,7 +371,7 @@ static bool valid_ipv4(const char *s)
}
// GET /api/network : mDNS name and client address settings, with the current address
static esp_err_t network_get(httpd_req_t *req)
static esp_err_t network_get(api_req_t *req)
{
net_cfg_t n;
settings_load_net(&n);
@@ -345,12 +386,14 @@ static esp_err_t network_get(httpd_req_t *req)
cJSON_AddStringToObject(o, "dns", n.dns);
cJSON_AddBoolToObject(o, "connected", up);
cJSON_AddStringToObject(o, "current_ip", ip);
cJSON_AddBoolToObject(o, "ap_enabled", n.ap_enabled);
cJSON_AddBoolToObject(o, "ddp_enabled", n.ddp_enabled);
return send_json(req, o);
}
// POST /api/network {"hostname","mode":"dhcp"|"static","ip","netmask","gateway","dns"}
// Missing fields keep their current value. Saves, applies and reconnects the client.
static esp_err_t network_post(httpd_req_t *req)
static esp_err_t network_post(api_req_t *req)
{
cJSON *in = read_json(req);
if (!in) {
@@ -399,6 +442,15 @@ static esp_err_t network_post(httpd_req_t *req)
f.dst[f.len - 1] = '\0';
}
}
cJSON *ap = cJSON_GetObjectItem(in, "ap_enabled");
if (cJSON_IsBool(ap)) {
n.ap_enabled = cJSON_IsTrue(ap);
}
cJSON *ddp = cJSON_GetObjectItem(in, "ddp_enabled");
if (cJSON_IsBool(ddp)) {
n.ddp_enabled = cJSON_IsTrue(ddp);
ddp_set_enabled(n.ddp_enabled);
}
cJSON_Delete(in);
if (n.use_static) {
@@ -411,6 +463,9 @@ static esp_err_t network_post(httpd_req_t *req)
}
esp_err_t err = net_save_network(&n);
if (err == ESP_ERR_INVALID_STATE) {
return send_error(req, "400 Bad Request", "connect to a Wi-Fi network before turning the access point off");
}
if (err != ESP_OK) {
ESP_LOGW(TAG, "Network apply failed: %s", esp_err_to_name(err));
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
@@ -451,7 +506,7 @@ static bool valid_pin(int pin)
}
// GET /api/hardware : LED strip settings
static esp_err_t hardware_get(httpd_req_t *req)
static esp_err_t hardware_get(api_req_t *req)
{
hw_cfg_t hw;
settings_load_hw(&hw);
@@ -464,7 +519,7 @@ static esp_err_t hardware_get(httpd_req_t *req)
}
// POST /api/hardware {"rgb_order","max_brightness":0-255,"num_leds":1-512}. Missing fields keep their value.
static esp_err_t hardware_post(httpd_req_t *req)
static esp_err_t hardware_post(api_req_t *req)
{
cJSON *in = read_json(req);
if (!in) {
@@ -523,18 +578,21 @@ static esp_err_t hardware_post(httpd_req_t *req)
}
// GET /api/ddp[?led=N] : DDP receiver state, and the colour shown on LED N (for checks)
static esp_err_t ddp_get(httpd_req_t *req)
static esp_err_t ddp_get(api_req_t *req)
{
bool active;
uint32_t packets;
patterns_ddp_status(&active, &packets);
int led = 0;
char q[32];
if (httpd_req_get_url_query_str(req, q, sizeof(q)) == ESP_OK) {
char v[8];
if (httpd_query_key_value(q, "led", v, sizeof(v)) == ESP_OK) {
led = atoi(v);
}
char q[32] = "";
if (req->http) {
httpd_req_get_url_query_str(req->http, q, sizeof(q));
} else {
snprintf(q, sizeof(q), "%s", req->query);
}
char v[8];
if (httpd_query_key_value(q, "led", v, sizeof(v)) == ESP_OK) {
led = atoi(v);
}
uint8_t px[3];
patterns_shown_pixel(led, px);
@@ -542,6 +600,16 @@ static esp_err_t ddp_get(httpd_req_t *req)
cJSON_AddBoolToObject(o, "active", active);
cJSON_AddNumberToObject(o, "packets", packets);
cJSON_AddNumberToObject(o, "port", DDP_PORT);
patterns_ddp_debug_t dbg;
patterns_ddp_debug(&dbg);
cJSON *sy = cJSON_AddObjectToObject(o, "sync");
cJSON_AddNumberToObject(sy, "port", DDP_SYNC_PORT);
cJSON_AddNumberToObject(sy, "syncs", dbg.syncs);
cJSON_AddNumberToObject(sy, "seq", dbg.sync_seq);
cJSON_AddNumberToObject(sy, "age_ms", dbg.sync_age_ms == UINT32_MAX ? -1 : (double)dbg.sync_age_ms);
cJSON_AddNumberToObject(sy, "frames", dbg.frames);
cJSON_AddNumberToObject(sy, "shown", dbg.shown);
cJSON_AddBoolToObject(sy, "held", dbg.held);
cJSON_AddNumberToObject(o, "led", led);
cJSON *px_arr = cJSON_AddArrayToObject(o, "rgb");
for (int i = 0; i < 3; i++) {
@@ -551,7 +619,7 @@ static esp_err_t ddp_get(httpd_req_t *req)
}
// POST /api/presets/order {"names":[...]} : the presets' order on the front page
static esp_err_t presets_order_post(httpd_req_t *req)
static esp_err_t presets_order_post(api_req_t *req)
{
cJSON *in = read_json(req);
if (!in) {
@@ -578,7 +646,7 @@ static esp_err_t presets_order_post(httpd_req_t *req)
}
// POST /api/presets/defaults : add the default presets that are missing
static esp_err_t presets_defaults_post(httpd_req_t *req)
static esp_err_t presets_defaults_post(api_req_t *req)
{
cJSON *o = cJSON_CreateObject();
cJSON_AddNumberToObject(o, "added", presets_add_defaults());
@@ -586,7 +654,7 @@ static esp_err_t presets_defaults_post(httpd_req_t *req)
}
// GET /api/presets
static esp_err_t presets_get(httpd_req_t *req)
static esp_err_t presets_get(api_req_t *req)
{
cJSON *o = cJSON_CreateObject();
cJSON *arr = cJSON_AddArrayToObject(o, "presets");
@@ -599,32 +667,52 @@ static esp_err_t presets_get(httpd_req_t *req)
return send_json(req, o);
}
// POST /api/brightness {"brightness":0-255} : live brightness for every pattern, saved
static esp_err_t brightness_post(httpd_req_t *req)
// POST /api/brightness {"brightness":0-255} sets this device's level; {"master":0-255} sets its
// master scale (sent to every device by "All devices"). Either or both, saved.
// Returns NULL when applied, or the error message.
static const char *brightness_apply(const cJSON *in)
{
const cJSON *v = cJSON_GetObjectItem(in, "brightness");
const cJSON *m = cJSON_GetObjectItem(in, "master");
if (!v && !m) {
return "send brightness and/or master";
}
if ((v && (!cJSON_IsNumber(v) || v->valueint < 0 || v->valueint > 255)) ||
(m && (!cJSON_IsNumber(m) || m->valueint < 0 || m->valueint > 255))) {
return "brightness and master must be 0-255";
}
hw_cfg_t hw;
settings_load_hw(&hw);
if (v) {
hw.global_brightness = (uint8_t)v->valueint;
patterns_set_global(hw.global_brightness);
}
if (m) {
hw.master_brightness = (uint8_t)m->valueint;
patterns_set_master(hw.master_brightness);
}
settings_save_hw(&hw);
return NULL;
}
static esp_err_t brightness_post(api_req_t *req)
{
cJSON *in = read_json(req);
if (!in) {
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
}
cJSON *v = cJSON_GetObjectItem(in, "brightness");
if (!cJSON_IsNumber(v) || v->valueint < 0 || v->valueint > 255) {
cJSON_Delete(in);
return send_error(req, "400 Bad Request", "brightness must be 0-255");
}
uint8_t level = (uint8_t)v->valueint;
const char *err = brightness_apply(in);
cJSON_Delete(in);
patterns_set_global(level);
hw_cfg_t hw;
settings_load_hw(&hw);
hw.global_brightness = level;
settings_save_hw(&hw);
if (err) {
return send_error(req, "400 Bad Request", err);
}
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "message", "saved");
return send_json(req, o);
}
// POST /api/presets : create or update by name. Missing fields take the running settings.
static esp_err_t presets_post(httpd_req_t *req)
static esp_err_t presets_post(api_req_t *req)
{
cJSON *in = read_json(req);
if (!in) {
@@ -656,7 +744,7 @@ static esp_err_t presets_post(httpd_req_t *req)
}
// Shared body for select, delete and startup: {"name"}
static esp_err_t preset_name_action(httpd_req_t *req, esp_err_t (*action)(const char *), const char *ok_msg)
static esp_err_t preset_name_action(api_req_t *req, esp_err_t (*action)(const char *), const char *ok_msg)
{
cJSON *in = read_json(req);
if (!in) {
@@ -684,24 +772,25 @@ static esp_err_t preset_name_action(httpd_req_t *req, esp_err_t (*action)(const
return send_json(req, o);
}
static esp_err_t select_post(httpd_req_t *req)
static esp_err_t select_post(api_req_t *req)
{
return preset_name_action(req, presets_select, "selected");
}
static esp_err_t delete_post(httpd_req_t *req)
static esp_err_t delete_post(api_req_t *req)
{
return preset_name_action(req, presets_delete, "deleted");
}
static esp_err_t startup_post(httpd_req_t *req)
static esp_err_t startup_post(api_req_t *req)
{
return preset_name_action(req, presets_set_startup, "startup set");
}
static void add_uri(httpd_handle_t srv, const char *uri, httpd_method_t method, esp_err_t (*handler)(httpd_req_t *))
{
httpd_uri_t u = { .uri = uri, .method = method, .handler = handler, .user_ctx = NULL };
httpd_uri_t u = { .uri = uri, .method = method, .handler = handler, .user_ctx = NULL,
.is_websocket = false, .handle_ws_control_frames = false, .supported_subprotocol = NULL };
httpd_register_uri_handler(srv, &u);
}
@@ -734,90 +823,240 @@ static bool relay_path_ok(const char *p)
return strstr(p, "..") == NULL && strchr(p, ' ') == NULL && strchr(p, '\r') == NULL && strchr(p, '\n') == NULL;
}
// Relay connections are kept open per peer, so a relayed request does not pay for a new TCP connection.
// The HTTP server runs one task, so relay calls never overlap and the slots need no lock.
#define RELAY_SLOTS 4
#define RELAY_TIMEOUT_MS 4000
struct relay_slot_t {
char host[80];
esp_http_client_handle_t cl;
};
static relay_slot_t s_relay[RELAY_SLOTS];
// The kept-open client for this host, pointed at url. A new slot evicts the oldest one.
static esp_http_client_handle_t relay_client(const char *host, const char *url)
{
int slot = -1;
for (int i = 0; i < RELAY_SLOTS; i++) {
if (s_relay[i].cl && strcmp(s_relay[i].host, host) == 0) {
slot = i;
break;
}
}
if (slot < 0) {
slot = 0;
for (int i = 0; i < RELAY_SLOTS; i++) {
if (!s_relay[i].cl) {
slot = i;
break;
}
}
if (s_relay[slot].cl) {
esp_http_client_cleanup(s_relay[slot].cl);
}
esp_http_client_config_t cfg = {};
cfg.url = url;
cfg.timeout_ms = RELAY_TIMEOUT_MS;
cfg.keep_alive_enable = true;
s_relay[slot].cl = esp_http_client_init(&cfg);
snprintf(s_relay[slot].host, sizeof(s_relay[slot].host), "%s", host);
return s_relay[slot].cl;
}
esp_http_client_set_url(s_relay[slot].cl, url);
return s_relay[slot].cl;
}
// One request to a peer over its kept-open connection. A dead connection is dropped and retried once.
static esp_err_t relay_do(const char *host, const char *url, bool is_post, const char *body, int body_len,
int *status, char *out, int cap, int *got)
{
for (int attempt = 0; attempt < 2; attempt++) {
const int64_t t0 = esp_timer_get_time();
esp_http_client_handle_t cl = relay_client(host, url);
const int64_t t_client = esp_timer_get_time();
if (!cl) {
return ESP_ERR_NO_MEM;
}
esp_http_client_set_method(cl, is_post ? HTTP_METHOD_POST : HTTP_METHOD_GET);
esp_http_client_set_header(cl, "Content-Type", "text/plain");
esp_err_t err = esp_http_client_open(cl, is_post ? body_len : 0);
const int64_t t_open = esp_timer_get_time();
if (err == ESP_OK && is_post && body_len > 0 && esp_http_client_write(cl, body, body_len) != body_len) {
err = ESP_FAIL;
}
const int64_t t_write = esp_timer_get_time();
*got = 0;
bool full = false;
int fetch_rc = -1;
if (err == ESP_OK) {
fetch_rc = esp_http_client_fetch_headers(cl);
}
const int64_t t_headers = esp_timer_get_time();
ESP_LOGI(TAG, "relay %s attempt %d: client %lld us, open %lld us, write %lld us, headers %lld us (rc %d, err %d)",
host, attempt, (long long)(t_client - t0), (long long)(t_open - t_client),
(long long)(t_write - t_open), (long long)(t_headers - t_write), fetch_rc, (int)err);
if (err == ESP_OK && fetch_rc >= 0) {
*status = esp_http_client_get_status_code(cl);
int r;
while (*got < cap && (r = esp_http_client_read(cl, out + *got, cap - *got)) > 0) {
*got += r;
}
ESP_LOGI(TAG, "relay %s body %d bytes read in %lld us", host, *got,
(long long)(esp_timer_get_time() - t_headers));
full = *got >= cap; // more body than fits: keep what fits, and drop the connection
if (!full) {
return ESP_OK;
}
esp_http_client_close(cl);
return ESP_OK;
}
// Failed before the answer: drop this connection and try once more
esp_http_client_close(cl);
}
return ESP_FAIL;
}
// Calls to a peer go over a kept-open WebSocket (its /ws), not a new HTTP request each time.
#define WS_SLOTS 4
struct ws_slot_t {
char host[80]; // empty when the slot is free
int fd;
};
static ws_slot_t s_ws[WS_SLOTS];
static void ws_slot_drop(ws_slot_t *slot)
{
ws_client_close(slot->fd);
slot->fd = -1;
slot->host[0] = '\0';
}
// Send msg to host's /ws and read the reply into reply. Reconnects once if the connection is dead.
static bool ws_fast_call(const char *host, const char *msg, char *reply, size_t cap)
{
for (int attempt = 0; attempt < 2; attempt++) {
ws_slot_t *slot = NULL;
for (int i = 0; i < WS_SLOTS; i++) {
if (s_ws[i].host[0] && strcmp(s_ws[i].host, host) == 0) {
slot = &s_ws[i];
break;
}
}
if (!slot) {
for (int i = 0; i < WS_SLOTS && !slot; i++) {
if (!s_ws[i].host[0]) {
slot = &s_ws[i];
}
}
if (!slot) {
slot = &s_ws[0];
ws_slot_drop(slot);
}
slot->fd = ws_client_connect(host, "/ws");
if (slot->fd < 0) {
slot->host[0] = '\0';
return false;
}
snprintf(slot->host, sizeof(slot->host), "%s", host);
}
if (ws_client_send_text(slot->fd, msg, strlen(msg)) == ESP_OK && ws_client_recv_text(slot->fd, reply, cap) >= 0) {
return true;
}
ws_slot_drop(slot);
}
return false;
}
// The reply to a relayed or WebSocket call: {"status": n, "body": "..."}
static void envelope(char *out, size_t cap, int status, const char *body_text)
{
cJSON *env = cJSON_CreateObject();
cJSON_AddNumberToObject(env, "status", status);
cJSON_AddStringToObject(env, "body", body_text);
char *s = cJSON_PrintUnformatted(env);
snprintf(out, cap, "%s", s ? s : "{}");
cJSON_free(s);
cJSON_Delete(env);
}
// Call another driver's API. The peer's WebSocket is tried first (kept open, so it is fast); the HTTP
// call is the fallback. out gets the envelope {"status": n, "body": "..."}.
static void relay_forward(const char *host, const char *method, const char *path, const char *body,
char *out, size_t cap)
{
if (!relay_host_ok(host) || !relay_path_ok(path) || (strcmp(method, "GET") != 0 && strcmp(method, "POST") != 0)) {
envelope(out, cap, 400, "{\"error\":\"need host, method GET or POST, and a path under /api/\"}");
return;
}
const bool is_post = strcmp(method, "POST") == 0;
const char *b = is_post ? body : "";
cJSON *m = cJSON_CreateObject();
cJSON_AddStringToObject(m, "method", method);
cJSON_AddStringToObject(m, "path", path);
cJSON_AddStringToObject(m, "body", b);
char *msg = cJSON_PrintUnformatted(m);
cJSON_Delete(m);
bool ok = msg && ws_fast_call(host, msg, out, cap); // the peer's reply is already an envelope
cJSON_free(msg);
if (ok) {
return;
}
char *buf = (char *)malloc(4096);
if (!buf) {
envelope(out, cap, 503, "{\"error\":\"out of memory\"}");
return;
}
char url[200];
snprintf(url, sizeof(url), "http://%s%s", host, path);
int got = 0;
int status = 0;
if (relay_do(host, url, is_post, b, (int)strlen(b), &status, buf, 4095, &got) != ESP_OK) {
envelope(out, cap, 502, "{\"error\":\"could not reach that device\"}");
} else {
buf[got] = '\0';
envelope(out, cap, status, buf);
}
free(buf);
}
// POST /api/relay {"host": "10.1.1.50", "method": "GET" or "POST", "path": "/api/status", "body": "..."}
// Calls another driver from here and answers {"status": n, "body": "..."}. A page on this driver only
// talks to this driver, so the browser never has to reach the other device itself.
static esp_err_t relay_post(httpd_req_t *req)
// Kept for HTTP callers; the page itself sends relayed calls over the WebSocket.
static esp_err_t relay_post(api_req_t *req)
{
// Heap buffers: the HTTP server task has an 8 KB stack
char *in = (char *)malloc(2048);
char *out = (char *)malloc(4096);
char *out = (char *)malloc(8192);
if (!in || !out) {
free(in);
free(out);
return send_error(req, "503 Service Unavailable", "out of memory");
}
esp_err_t result = ESP_FAIL;
esp_err_t result;
if (!read_body(req, in, 2048)) {
result = send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
goto done;
} else {
cJSON *top = cJSON_Parse(in);
const cJSON *jh = top ? cJSON_GetObjectItem(top, "host") : NULL;
const cJSON *jm = top ? cJSON_GetObjectItem(top, "method") : NULL;
const cJSON *jp = top ? cJSON_GetObjectItem(top, "path") : NULL;
const cJSON *jb = top ? cJSON_GetObjectItem(top, "body") : NULL;
if (!cJSON_IsString(jh) || !cJSON_IsString(jm) || !cJSON_IsString(jp) || !relay_host_ok(jh->valuestring)
|| !relay_path_ok(jp->valuestring) || (strcmp(jm->valuestring, "GET") != 0 && strcmp(jm->valuestring, "POST") != 0)) {
if (!cJSON_IsString(jh) || !cJSON_IsString(jm) || !cJSON_IsString(jp)) {
cJSON_Delete(top);
result = send_error(req, "400 Bad Request", "need host, method GET or POST, and a path under /api/");
goto done;
}
const bool is_post = strcmp(jm->valuestring, "POST") == 0;
const char *body = (is_post && cJSON_IsString(jb)) ? jb->valuestring : "";
const int body_len = (int)strlen(body);
char url[200];
snprintf(url, sizeof(url), "http://%s%s", jh->valuestring, jp->valuestring);
esp_http_client_config_t ccfg = {};
ccfg.url = url;
ccfg.method = is_post ? HTTP_METHOD_POST : HTTP_METHOD_GET;
ccfg.timeout_ms = 4000;
esp_http_client_handle_t cl = esp_http_client_init(&ccfg);
if (!cl) {
cJSON_Delete(top);
result = send_error(req, "502 Bad Gateway", "could not start the request");
goto done;
}
esp_http_client_set_header(cl, "Content-Type", "text/plain");
esp_err_t err = esp_http_client_open(cl, is_post ? body_len : 0);
if (err == ESP_OK && is_post && body_len > 0) {
if (esp_http_client_write(cl, body, body_len) != body_len) {
err = ESP_FAIL;
}
}
int got = 0;
int status = 0;
if (err == ESP_OK && esp_http_client_fetch_headers(cl) >= 0) {
status = esp_http_client_get_status_code(cl);
int r;
while (got < 4095 && (r = esp_http_client_read(cl, out + got, 4095 - got)) > 0) {
got += r;
}
result = send_error(req, "400 Bad Request", "need host, method and path");
} else {
err = ESP_FAIL;
relay_forward(jh->valuestring, jm->valuestring, jp->valuestring,
cJSON_IsString(jb) ? jb->valuestring : "", out, 8192);
cJSON_Delete(top);
result = send_text(req, "200 OK", out);
}
esp_http_client_close(cl);
esp_http_client_cleanup(cl);
cJSON_Delete(top);
if (err != ESP_OK) {
result = send_error(req, "502 Bad Gateway", "could not reach that device");
goto done;
}
out[got] = '\0';
cJSON *o = cJSON_CreateObject();
cJSON_AddNumberToObject(o, "status", status);
cJSON_AddStringToObject(o, "body", out);
result = send_json(req, o);
}
done:
free(in);
free(out);
return result;
}
// GET /api/devices: the LED drivers on this network, found by mDNS (they advertise app=led-strip).
// Includes this driver; the page leaves it out, since "This device" is already in the list.
static esp_err_t devices_get(httpd_req_t *req)
static esp_err_t devices_get(api_req_t *req)
{
cJSON *arr = cJSON_CreateArray();
mdns_result_t *res = NULL;
@@ -873,6 +1112,184 @@ static esp_err_t devices_get(httpd_req_t *req)
return send_json(req, top);
}
// The server sends each response header as its own small write. With Nagle on, every write after the
// first waits for the client's delayed ACK (hundreds of ms), so turn Nagle off on each new connection.
static esp_err_t open_nodelay(httpd_handle_t hd, int sockfd)
{
(void)hd;
int one = 1;
setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
return ESP_OK;
}
// The JSON API. Each route answers an HTTP request and a WebSocket message alike.
typedef struct {
const char *path;
httpd_method_t method;
api_fn_t fn;
} api_route_t;
static const api_route_t s_api[] = {
{"/api/status", HTTP_GET, status_get},
{"/api/pattern", HTTP_POST, pattern_post},
{"/api/wifi", HTTP_GET, wifi_get},
{"/api/wifi", HTTP_POST, wifi_post},
{"/api/wifi/scan", HTTP_GET, wifi_scan_get},
{"/api/network", HTTP_GET, network_get},
{"/api/network", HTTP_POST, network_post},
{"/api/ddp", HTTP_GET, ddp_get},
{"/api/hardware", HTTP_GET, hardware_get},
{"/api/hardware", HTTP_POST, hardware_post},
{"/api/presets", HTTP_GET, presets_get},
{"/api/presets", HTTP_POST, presets_post},
{"/api/presets/select", HTTP_POST, select_post},
{"/api/presets/delete", HTTP_POST, delete_post},
{"/api/presets/startup", HTTP_POST, startup_post},
{"/api/presets/defaults", HTTP_POST, presets_defaults_post},
{"/api/presets/order", HTTP_POST, presets_order_post},
{"/api/brightness", HTTP_POST, brightness_post},
{"/api/devices", HTTP_GET, devices_get},
{"/api/relay", HTTP_POST, relay_post},
};
// An HTTP request for a route: the route's function is kept in the URI's user_ctx.
static esp_err_t api_http_entry(httpd_req_t *req)
{
api_req_t a = {};
a.http = req;
return reinterpret_cast<api_fn_t>(req->user_ctx)(&a);
}
#define WS_MSG_MAX 2048 // a request message
#define WS_REPLY_MAX 8192 // a reply envelope
// Run an API route on this driver: target is the path, optionally with a query string.
static void ws_local(const char *method, const char *target, const char *body, char *out, size_t cap)
{
char path[64];
const char *q = strchr(target, '?');
size_t n = q ? (size_t)(q - target) : strlen(target);
if (n >= sizeof(path)) {
envelope(out, cap, 404, "{\"error\":\"no such API path\"}");
return;
}
memcpy(path, target, n);
path[n] = '\0';
for (size_t i = 0; i < sizeof(s_api) / sizeof(s_api[0]); i++) {
const bool is_get = s_api[i].method == HTTP_GET;
if (strcmp(s_api[i].path, path) == 0 && strcmp(method, is_get ? "GET" : "POST") == 0) {
char *reply = (char *)malloc(WS_REPLY_MAX);
if (!reply) {
envelope(out, cap, 503, "{\"error\":\"out of memory\"}");
return;
}
reply[0] = '\0';
api_req_t a = {};
a.body = body;
a.query = q ? q + 1 : "";
a.out = reply;
a.out_cap = WS_REPLY_MAX;
a.status = 200;
s_api[i].fn(&a);
if (reply[0] == '\0') {
snprintf(reply, WS_REPLY_MAX, "{}");
}
envelope(out, cap, a.status, reply);
free(reply);
return;
}
}
envelope(out, cap, 404, "{\"error\":\"no such API path\"}");
}
// A WebSocket request: {"method": "GET" or "POST", "path": "/api/...", "body": "<JSON text>"}, plus
// "host" to have this driver relay it to that driver. The reply is the envelope {"status": n, "body": "..."}.
static void ws_dispatch(const char *msg, char *out, size_t cap)
{
cJSON *top = cJSON_Parse(msg);
const cJSON *jm = top ? cJSON_GetObjectItem(top, "method") : NULL;
const cJSON *jp = top ? cJSON_GetObjectItem(top, "path") : NULL;
const cJSON *jb = top ? cJSON_GetObjectItem(top, "body") : NULL;
const cJSON *jh = top ? cJSON_GetObjectItem(top, "host") : NULL;
if (!cJSON_IsString(jp)) {
envelope(out, cap, 400, "{\"error\":\"need a path\"}");
cJSON_Delete(top);
return;
}
const char *method = cJSON_IsString(jm) ? jm->valuestring : "GET";
char *owned = NULL; // body printed from a JSON object (a string is used as it is)
const char *body = "";
if (cJSON_IsString(jb)) {
body = jb->valuestring;
} else if (jb) {
owned = cJSON_PrintUnformatted(jb);
body = owned ? owned : "";
}
if (cJSON_IsString(jh) && jh->valuestring[0] != '\0') {
relay_forward(jh->valuestring, method, jp->valuestring, body, out, cap);
} else {
ws_local(method, jp->valuestring, body, out, cap);
}
cJSON_free(owned);
cJSON_Delete(top);
}
// WebSocket handler: one text frame in, one text frame out
// Another site's page must not drive this driver. A browser sends its Origin with the WebSocket
// handshake, and only a page from the LAN (or this device) may open the socket. ESP-IDF has no hook
// before the handshake reply, so the check runs right after it: a refused socket is closed before any
// frame is read, so its messages are never dispatched.
static esp_err_t ws_origin_check(httpd_req_t *req)
{
size_t origin_len = httpd_req_get_hdr_value_len(req, "Origin");
if (origin_len == 0) {
return ESP_OK; // not a browser (no Origin): the device's own client, or a tool
}
char origin[128];
if (origin_len >= sizeof(origin) || httpd_req_get_hdr_value_str(req, "Origin", origin, sizeof(origin)) != ESP_OK
|| !origin_is_lan(origin)) {
return ESP_FAIL;
}
return ESP_OK;
}
static esp_err_t ws_handler(httpd_req_t *req)
{
if (req->method == HTTP_GET) {
return ws_origin_check(req); // the handshake is done
}
httpd_ws_frame_t frame = {};
frame.type = HTTPD_WS_TYPE_TEXT;
esp_err_t err = httpd_ws_recv_frame(req, &frame, 0);
if (err != ESP_OK) {
return err;
}
if (frame.len == 0 || frame.len > WS_MSG_MAX) {
return ESP_FAIL;
}
uint8_t *buf = (uint8_t *)malloc(frame.len + 1);
char *reply = (char *)malloc(WS_REPLY_MAX);
if (!buf || !reply) {
free(buf);
free(reply);
return ESP_ERR_NO_MEM;
}
frame.payload = buf;
err = httpd_ws_recv_frame(req, &frame, frame.len);
if (err == ESP_OK) {
buf[frame.len] = '\0';
ws_dispatch((const char *)buf, reply, WS_REPLY_MAX);
httpd_ws_frame_t out = {};
out.type = HTTPD_WS_TYPE_TEXT;
out.payload = (uint8_t *)reply;
out.len = strlen(reply);
err = httpd_ws_send_frame(req, &out);
}
free(buf);
free(reply);
return err;
}
esp_err_t web_start(void)
{
httpd_config_t cfg = HTTPD_DEFAULT_CONFIG();
@@ -881,6 +1298,7 @@ esp_err_t web_start(void)
cfg.lru_purge_enable = true;
cfg.max_open_sockets = 7;
cfg.backlog_conn = 10;
cfg.open_fn = open_nodelay;
esp_err_t err = httpd_start(&s_server, &cfg);
if (err != ESP_OK) {
ESP_LOGE(TAG, "HTTP server start failed: %s", esp_err_to_name(err));
@@ -889,26 +1307,18 @@ esp_err_t web_start(void)
add_uri(s_server, "/", HTTP_GET, index_get);
add_uri(s_server, "/app.js", HTTP_GET, app_js_get);
add_uri(s_server, "/style.css", HTTP_GET, style_css_get);
add_uri(s_server, "/api/status", HTTP_GET, status_get);
add_uri(s_server, "/api/pattern", HTTP_POST, pattern_post);
add_uri(s_server, "/api/wifi", HTTP_GET, wifi_get);
add_uri(s_server, "/api/wifi", HTTP_POST, wifi_post);
add_uri(s_server, "/api/wifi/scan", HTTP_GET, wifi_scan_get);
add_uri(s_server, "/api/network", HTTP_GET, network_get);
add_uri(s_server, "/api/network", HTTP_POST, network_post);
add_uri(s_server, "/api/ddp", HTTP_GET, ddp_get);
add_uri(s_server, "/api/hardware", HTTP_GET, hardware_get);
add_uri(s_server, "/api/hardware", HTTP_POST, hardware_post);
add_uri(s_server, "/api/presets", HTTP_GET, presets_get);
add_uri(s_server, "/api/presets", HTTP_POST, presets_post);
add_uri(s_server, "/api/presets/select", HTTP_POST, select_post);
add_uri(s_server, "/api/presets/delete", HTTP_POST, delete_post);
add_uri(s_server, "/api/presets/startup", HTTP_POST, startup_post);
add_uri(s_server, "/api/presets/defaults", HTTP_POST, presets_defaults_post);
add_uri(s_server, "/api/presets/order", HTTP_POST, presets_order_post);
add_uri(s_server, "/api/brightness", HTTP_POST, brightness_post);
add_uri(s_server, "/api/relay", HTTP_POST, relay_post);
add_uri(s_server, "/api/devices", HTTP_GET, devices_get);
for (size_t i = 0; i < sizeof(s_api) / sizeof(s_api[0]); i++) {
httpd_uri_t u = {};
u.uri = s_api[i].path;
u.method = s_api[i].method;
u.handler = api_http_entry;
u.user_ctx = reinterpret_cast<void *>(s_api[i].fn);
httpd_register_uri_handler(s_server, &u);
}
static const httpd_uri_t ws_uri = { .uri = "/ws", .method = HTTP_GET, .handler = ws_handler,
.user_ctx = NULL, .is_websocket = true, .handle_ws_control_frames = false,
.supported_subprotocol = NULL };
httpd_register_uri_handler(s_server, &ws_uri);
ota_register(s_server);
ESP_LOGI(TAG, "Web UI on port 80");
return ESP_OK;
+173
View File
@@ -0,0 +1,173 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include "ws_client.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#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)); // one frame, one segment
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 || 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; // 2-byte or 16-bit length
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;
}
// Read exactly n bytes
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; // larger than this client accepts
}
bool masked = (h[1] & 0x80) != 0;
uint8_t mask[4] = {};
if (masked && !read_n(fd, mask, 4)) {
return -1;
}
if (len >= 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) { // text
buf[len] = '\0';
return (int)len;
}
if ((h[0] & 0x0F) == 0x8) { // close
return -1;
}
}
}
void ws_client_close(int fd)
{
if (fd >= 0) {
close(fd);
}
}
+22
View File
@@ -0,0 +1,22 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* Minimal WebSocket client for talking to another driver. One connection is kept open per peer.
*/
#pragma once
#include <cstddef>
#include "esp_err.h"
/** @brief Open (or reuse) a WebSocket to host:/ws. Returns the socket, or -1. */
int ws_client_connect(const char *host, const char *path);
/** @brief Send one text frame. */
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. */
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);