Files
led-driver/main/net.cpp
T
jimmyandClaude Haiku 5.5 4cd3bc7973 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>
2026-11-11 14:10:55 +13:00

325 lines
10 KiB
C++

/*
* SPDX-License-Identifier: Apache-2.0
*/
#include <cstdio>
#include <cstring>
#include "esp_event.h"
#include "esp_log.h"
#include "esp_mac.h"
#include "esp_netif.h"
#include "esp_timer.h"
#include "esp_wifi.h"
#include "mdns.h"
#include "net.h"
static const char *TAG = "net";
#define AP_CHANNEL 1
#define AP_MAX_CLIENTS 4
#define RETRY_MAX_MS 30000
static esp_netif_t *s_ap_netif;
static esp_netif_t *s_sta_netif;
static esp_timer_handle_t s_retry_timer;
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)
{
wifi_config_t cfg = {};
strncpy((char *)cfg.sta.ssid, c->ssid, sizeof(cfg.sta.ssid) - 1);
strncpy((char *)cfg.sta.password, c->pass, sizeof(cfg.sta.password) - 1);
cfg.sta.threshold.authmode = c->pass[0] ? WIFI_AUTH_WPA2_PSK : WIFI_AUTH_OPEN;
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)
{
if (!c->use_static) {
esp_err_t err = esp_netif_dhcpc_start(s_sta_netif);
// Already running is fine
return (err == ESP_OK || err == ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED) ? ESP_OK : err;
}
esp_netif_ip_info_t info = {};
if (esp_netif_str_to_ip4(c->ip, &info.ip) != ESP_OK ||
esp_netif_str_to_ip4(c->netmask, &info.netmask) != ESP_OK ||
esp_netif_str_to_ip4(c->gateway, &info.gw) != ESP_OK) {
return ESP_ERR_INVALID_ARG;
}
esp_netif_dhcpc_stop(s_sta_netif); // ignore "not started"
esp_err_t err = esp_netif_set_ip_info(s_sta_netif, &info);
if (err != ESP_OK) {
return err;
}
esp_netif_dns_info_t dns = {};
const char *dns_str = c->dns[0] ? c->dns : c->gateway;
if (esp_netif_str_to_ip4(dns_str, &dns.ip.u_addr.ip4) == ESP_OK) {
dns.ip.type = ESP_IPADDR_TYPE_V4;
esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_MAIN, &dns);
}
ESP_LOGI(TAG, "Client static IP %s/%s gw %s", c->ip, c->netmask, c->gateway);
return ESP_OK;
}
static void retry_cb(void *arg)
{
(void)arg;
esp_wifi_connect();
}
static void on_wifi_event(void *arg, esp_event_base_t base, int32_t id, void *data)
{
(void)arg;
(void)base;
(void)data;
switch (id) {
case WIFI_EVENT_STA_START: {
wifi_creds_t c;
if (settings_load_wifi(&c) == ESP_OK && c.ssid[0]) {
net_cfg_t n;
settings_load_net(&n);
if (apply_client_ip(&n) != ESP_OK) {
ESP_LOGW(TAG, "Static IP settings are invalid; using DHCP");
n.use_static = false;
apply_client_ip(&n);
}
esp_wifi_connect();
}
break;
}
case WIFI_EVENT_STA_DISCONNECTED: {
// Back off 1 s, 2 s, 4 s ... up to RETRY_MAX_MS
s_sta_up = false;
uint32_t delay_ms = 1000u << (s_retries < 5 ? s_retries : 5);
if (delay_ms > RETRY_MAX_MS) delay_ms = RETRY_MAX_MS;
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:
break;
}
}
static void on_ip_event(void *arg, esp_event_base_t base, int32_t id, void *data)
{
(void)arg;
(void)base;
(void)id;
ip_event_got_ip_t *e = (ip_event_got_ip_t *)data;
s_sta_ip = e->ip_info.ip;
s_sta_up = true;
s_retries = 0;
ESP_LOGI(TAG, "Client IP " IPSTR, IP2STR(&e->ip_info.ip));
}
void net_ap_ssid(char *buf, size_t len)
{
uint8_t mac[6];
esp_read_mac(mac, ESP_MAC_WIFI_SOFTAP);
snprintf(buf, len, "led-%02X%02X%02X", mac[3], mac[4], mac[5]);
}
esp_err_t net_start(void)
{
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
s_ap_netif = esp_netif_create_default_wifi_ap();
s_sta_netif = esp_netif_create_default_wifi_sta();
wifi_init_config_t init_cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&init_cfg));
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, on_wifi_event, NULL, NULL));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, on_ip_event, NULL, NULL));
const esp_timer_create_args_t timer_args = {
.callback = retry_cb,
.arg = NULL,
.dispatch_method = ESP_TIMER_TASK,
.name = "wifi_retry",
.skip_unhandled_events = false,
};
ESP_ERROR_CHECK(esp_timer_create(&timer_args, &s_retry_timer));
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));
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));
// 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;
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());
// mDNS: <hostname>.local, with an HTTP service on port 80
ESP_ERROR_CHECK(mdns_init());
ESP_ERROR_CHECK(mdns_hostname_set(n.hostname));
ESP_ERROR_CHECK(mdns_instance_name_set("LED controller"));
// app=led-strip lets other drivers' discovery (GET /api/devices) pick out LED drivers from other HTTP devices
static mdns_txt_item_t txt[] = { { "app", "led-strip" } };
ESP_ERROR_CHECK(mdns_service_add(NULL, "_http", "_tcp", 80, txt, 1));
ESP_LOGI(TAG, "mDNS: %s.local", n.hostname);
return ESP_OK;
}
bool net_sta_status(char *ip, size_t ip_len)
{
if (ip_len) {
ip[0] = '\0';
}
if (!s_sta_up) {
return false;
}
snprintf(ip, ip_len, IPSTR, IP2STR(&s_sta_ip));
return true;
}
esp_err_t net_sta_connect(const wifi_creds_t *c)
{
esp_err_t err = settings_save_wifi(c);
if (err != ESP_OK) {
return err;
}
esp_timer_stop(s_retry_timer);
esp_wifi_disconnect();
s_retries = 0;
apply_sta_config(c);
return esp_wifi_connect();
}
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;
}
err = mdns_hostname_set(c->hostname);
if (err != ESP_OK) {
return err;
}
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;
}
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)
{
esp_err_t err = esp_wifi_scan_start(NULL, true);
if (err != ESP_OK) {
return err;
}
uint16_t max = *count;
err = esp_wifi_scan_get_ap_records(&max, recs);
*count = max;
return err;
}