diff --git a/docs/API.md b/docs/API.md index 9dfd0da..ea065dc 100644 --- a/docs/API.md +++ b/docs/API.md @@ -61,6 +61,8 @@ Keys with meaning on the controller (others are stored as they are): | Key | Checked | Meaning | |-----|---------|---------| +| `ap_enabled` | | Wi-Fi access point (open, SSID = hostname, `192.168.5.1`); default `true`; applies after a restart. Holding the D7 button at boot forces it on | +| `ap_password` | | AP password, 8-63 characters (WPA2); empty (default) is an open network; applies after a restart | | `hostname` | | mDNS name (`.local`, default `led-controller`); applies after a restart | | `static_ips` | | List of `{ip, netmask?, gw, dns?}` tried in order when the Ethernet link comes up; the first whose gateway answers ARP is used, else DHCP, else `192.168.4.1/24` for a direct PC cable. Applies after a restart | | `global_brightness` | integer 0–255 | Global factor of each driver's brightness (see Groups). Stored only: the UI pushes each driver its combined value | diff --git a/docs/help.md b/docs/help.md index 541fda9..5e73168 100644 --- a/docs/help.md +++ b/docs/help.md @@ -106,7 +106,7 @@ The preset editor: ## Settings -**Settings** (Edit mode) holds the controller's name, the ESP-NOW channel (for reference: the controller's channel is set at build time), its mDNS **hostname** and the **static IPs** it tries on the Ethernet link (DHCP when none answers). With no DHCP server, as on a cable straight to a PC, the controller is at `192.168.4.1`; give the PC a static IP such as `192.168.4.2`. Network changes apply after a restart. **Driver** in Settings sends a driver its name, LED count, colour order, startup mode, maximum brightness and direction over ESP-NOW, with no cable. **Update code** there sends a driver, or all of them, the led-driver code built into the controller. `led-cli` on a computer edits a driver's whole `settings.json` over USB. +**Settings** (Edit mode) holds the controller's name, the ESP-NOW channel (for reference: the controller's channel is set at build time), a **Wi-Fi access point** switch (on by default; network named after the hostname, with an optional WPA2 password, controller at `192.168.5.1`; holding the button on D7 at boot forces it on), its mDNS **hostname** and the **static IPs** it tries on the Ethernet link (DHCP when none answers). With no DHCP server, as on a cable straight to a PC, the controller is at `192.168.4.1`; give the PC a static IP such as `192.168.4.2`. Network changes apply after a restart. **Driver** in Settings sends a driver its name, LED count, colour order, startup mode, maximum brightness and direction over ESP-NOW, with no cable. **Update code** there sends a driver, or all of them, the led-driver code built into the controller. `led-cli` on a computer edits a driver's whole `settings.json` over USB. ![Schematic: narrow layout with Menu and the same header actions in a dropdown.](images/help/mobile-menu.svg) diff --git a/main/Kconfig.projbuild b/main/Kconfig.projbuild index f54958a..f431385 100644 --- a/main/Kconfig.projbuild +++ b/main/Kconfig.projbuild @@ -103,6 +103,23 @@ menu "Beat detection config" endmenu +menu "AP config" + + config AP_BUTTON_GPIO + int "AP button GPIO (XIAO D7), -1 for none" + default 44 + help + Push button to ground. Held while the controller boots, it turns + the Wi-Fi access point on even when the ap_enabled setting is off. + GPIO44 is also UART0 RX; the button only pulls it low at boot. + + config AP_HOLD_MS + int "Hold time at boot (ms)" + range 100 5000 + default 1000 + +endmenu + menu "ESP-NOW config" config ESPNOW_CHANNEL diff --git a/main/api.c b/main/api.c index 7c98496..beca453 100644 --- a/main/api.c +++ b/main/api.c @@ -348,6 +348,10 @@ void api_settings_defaults(void) api_set(st, "global_brightness", cJSON_CreateNumber(255)); changed = true; } + if (!cJSON_IsBool(cJSON_GetObjectItem(st, "ap_enabled"))) { + api_set(st, "ap_enabled", cJSON_CreateBool(true)); + changed = true; + } if (changed) { store_save("settings"); } @@ -382,6 +386,15 @@ static esp_err_t put_settings(httpd_req_t *req) bad = INTS[i].err; } } + const cJSON *ap = cJSON_GetObjectItem(body, "ap_enabled"); + if (ap && !cJSON_IsBool(ap)) { + bad = "ap_enabled must be true or false"; + } + const cJSON *pw = cJSON_GetObjectItem(body, "ap_password"); + if (!bad && pw && !cJSON_IsNull(pw) && + !(cJSON_IsString(pw) && (!pw->valuestring[0] || (strlen(pw->valuestring) >= 8 && strlen(pw->valuestring) <= 63)))) { + bad = "ap_password must be empty (open) or 8 to 63 characters"; + } 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")))) { diff --git a/main/espnow_tx.c b/main/espnow_tx.c index c91911a..6ec758b 100644 --- a/main/espnow_tx.c +++ b/main/espnow_tx.c @@ -210,12 +210,50 @@ void espnow_tx_stats(espnow_stats_t *out) *out = s_stats; } -esp_err_t espnow_tx_init(void) +// A link-local IPv6 address on the AP lets the mDNS responder answer the AAAA half of a browser's +// lookup; without it the browser waits about a second for an answer that never comes. +static esp_netif_t *s_ap_netif; +static void ap_event(void *arg, esp_event_base_t base, int32_t id, void *data) +{ + if (s_ap_netif) { + esp_netif_create_ip6_linklocal(s_ap_netif); + } +} + +esp_err_t espnow_tx_init(const char *ap_ssid, const char *ap_password) { wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); ESP_RETURN_ON_ERROR(esp_wifi_init(&cfg), TAG, "wifi init"); ESP_RETURN_ON_ERROR(esp_wifi_set_storage(WIFI_STORAGE_RAM), TAG, "storage"); - ESP_RETURN_ON_ERROR(esp_wifi_set_mode(WIFI_MODE_STA), TAG, "mode"); + if (ap_ssid) { + // Not the Ethernet fallback subnet (192.168.4.x) + esp_netif_t *ap = esp_netif_create_default_wifi_ap(); + ESP_RETURN_ON_FALSE(ap, ESP_FAIL, TAG, "ap netif"); + s_ap_netif = ap; + ESP_RETURN_ON_ERROR(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_AP_START, ap_event, NULL), TAG, "ap event"); + esp_netif_ip_info_t ip = { 0 }; + ip.ip.addr = ESP_IP4TOADDR(192, 168, 5, 1); + ip.gw.addr = ip.ip.addr; + ip.netmask.addr = ESP_IP4TOADDR(255, 255, 255, 0); + esp_netif_dhcps_stop(ap); + ESP_RETURN_ON_ERROR(esp_netif_set_ip_info(ap, &ip), TAG, "ap ip"); + esp_netif_dhcps_start(ap); + wifi_config_t ac = { 0 }; + strlcpy((char *)ac.ap.ssid, ap_ssid, sizeof(ac.ap.ssid)); + ac.ap.ssid_len = strlen((char *)ac.ap.ssid); + ac.ap.channel = CONFIG_ESPNOW_CHANNEL; + if (ap_password && strlen(ap_password) >= 8) { + strlcpy((char *)ac.ap.password, ap_password, sizeof(ac.ap.password)); + ac.ap.authmode = WIFI_AUTH_WPA2_PSK; + } else { + ac.ap.authmode = WIFI_AUTH_OPEN; + } + ac.ap.max_connection = 4; + ESP_RETURN_ON_ERROR(esp_wifi_set_mode(WIFI_MODE_APSTA), TAG, "mode"); + ESP_RETURN_ON_ERROR(esp_wifi_set_config(WIFI_IF_AP, &ac), TAG, "ap config"); + } else { + ESP_RETURN_ON_ERROR(esp_wifi_set_mode(WIFI_MODE_STA), TAG, "mode"); + } ESP_RETURN_ON_ERROR(esp_wifi_start(), TAG, "start"); ESP_RETURN_ON_ERROR(esp_wifi_set_ps(WIFI_PS_NONE), TAG, "ps"); ESP_RETURN_ON_ERROR(esp_wifi_set_max_tx_power(80), TAG, "tx power"); // 20 dBm diff --git a/main/espnow_tx.h b/main/espnow_tx.h index 4084712..7d0ecd4 100644 --- a/main/espnow_tx.h +++ b/main/espnow_tx.h @@ -30,8 +30,10 @@ typedef struct { uint32_t sim_dropped; // frames discarded by the lossy-link test mode } espnow_stats_t; -// Start Wi-Fi (no AP) on the configured channel and ESP-NOW; hooks beat_set_callback -esp_err_t espnow_tx_init(void); +// Start Wi-Fi on the configured channel and ESP-NOW; hooks beat_set_callback. +// ap_ssid non-NULL also runs an access point of that name (192.168.5.1): WPA2 with +// ap_password (8-63 chars), open when it is NULL or empty. +esp_err_t espnow_tx_init(const char *ap_ssid, const char *ap_password); // Queue a bulk frame (<= 240 bytes). mac NULL broadcasts. Unicast frames are // retried; they never go out within the hold-off window after a beat. diff --git a/main/main.c b/main/main.c index 794047b..43cd415 100644 --- a/main/main.c +++ b/main/main.c @@ -44,6 +44,7 @@ static const char *TAG = "eth"; static httpd_handle_t s_server = NULL; static esp_netif_t *s_eth_netif = NULL; +static bool s_ap_on = false; // Wi-Fi access point running static const char *reset_reason(void) { @@ -75,19 +76,21 @@ static esp_err_t status_get_handler(httpd_req_t *req) mic_get_level(&level); espnow_tx_stats(&es); rel_stats(&rs); - esp_netif_get_ip_info(s_eth_netif, &ip_info); - esp_netif_get_mac(s_eth_netif, mac); + if (s_eth_netif) { // NULL when the W5500 did not start + esp_netif_get_ip_info(s_eth_netif, &ip_info); + esp_netif_get_mac(s_eth_netif, mac); + } snprintf(ip, sizeof(ip), IPSTR, IP2STR(&ip_info.ip)); snprintf(macs, sizeof(macs), MACSTR, MAC2STR(mac)); snprintf(buf, sizeof(buf), - "{\"ip\":\"%s\",\"mac\":\"%s\",\"uptime_s\":%lld,\"reset_reason\":\"%s\",\"free_heap\":%lu,\"free_internal\":%lu," + "{\"ap\":%s,\"ip\":\"%s\",\"mac\":\"%s\",\"uptime_s\":%lld,\"reset_reason\":\"%s\",\"free_heap\":%lu,\"free_internal\":%lu," "\"mic_rms_dbfs\":%.1f,\"mic_peak_dbfs\":%.1f,\"mic_spl_db\":%.1f," "\"bpm\":%.1f,\"beat_confidence\":%.2f,\"beat_locked\":%s,\"beats\":%lu,\"onsets\":%lu," "\"meter\":%d,\"bar_beat\":%d,\"bar_sure\":%s,\"downbeats\":%lu," "\"espnow\":{\"beats_sent\":%lu,\"beat_send_fail\":%lu,\"bulk_sent\":%lu," "\"bulk_retries\":%lu,\"bulk_failed\":%lu,\"sim_dropped\":%lu}," "\"link\":{\"ver\":%u,\"acked\":%lu,\"ack_timeouts\":%lu,\"retransmits\":%lu,\"resyncs\":%lu,\"digests\":%lu}}", - ip, macs, (long long)(esp_timer_get_time() / 1000000), reset_reason(), (unsigned long)esp_get_free_heap_size(), + s_ap_on ? "true" : "false", ip, macs, (long long)(esp_timer_get_time() / 1000000), reset_reason(), (unsigned long)esp_get_free_heap_size(), (unsigned long)heap_caps_get_free_size(MALLOC_CAP_INTERNAL), level.rms_dbfs, level.peak_dbfs, level.spl_db, bi.bpm, bi.confidence, bi.locked ? "true" : "false", (unsigned long)bi.beat_count, (unsigned long)bi.onset_count, bi.meter, bi.bar_beat, bi.bar_sure ? "true" : "false", @@ -107,6 +110,34 @@ static esp_err_t status_get_handler(httpd_req_t *req) #define DEFAULT_NETMASK ESP_IP4TOADDR(255, 255, 255, 0) #define DHCP_WAIT_S 15 +// Boolean setting; def when missing or not a boolean +static bool settings_bool(const char *key, bool def) +{ + cJSON *v = cJSON_GetObjectItem(store_settings(), key); + return cJSON_IsBool(v) ? cJSON_IsTrue(v) : def; +} + +// AP button held (to ground) for AP_HOLD_MS from boot +static bool ap_button_held(void) +{ +#if CONFIG_AP_BUTTON_GPIO >= 0 + gpio_config_t io = { .pin_bit_mask = 1ULL << CONFIG_AP_BUTTON_GPIO, .mode = GPIO_MODE_INPUT, + .pull_up_en = GPIO_PULLUP_ENABLE }; + if (gpio_config(&io) != ESP_OK) { + return false; + } + for (int t = 0; t < CONFIG_AP_HOLD_MS; t += 10) { + if (gpio_get_level(CONFIG_AP_BUTTON_GPIO)) { + return false; + } + vTaskDelay(pdMS_TO_TICKS(10)); + } + return true; +#else + return false; +#endif +} + static const char *settings_str(const char *key) { cJSON *v = cJSON_GetObjectItem(store_settings(), key); @@ -257,6 +288,8 @@ static void start_webserver(void) config.max_uri_handlers = 80; config.stack_size = 8192; config.lru_purge_enable = true; + config.max_open_sockets = 12; // browsers open 6 connections at once + config.backlog_conn = 10; // the default 5 drops the 6th SYN, a 1 s retry if (httpd_start(&s_server, &config) != ESP_OK) { ESP_LOGE(TAG, "HTTP server start failed"); return; @@ -287,6 +320,7 @@ static void eth_event_handler(void *arg, esp_event_base_t event_base, esp_eth_ioctl(eth_handle, ETH_CMD_G_SPEED, &speed); esp_eth_ioctl(eth_handle, ETH_CMD_G_DUPLEX_MODE, &duplex); ESP_LOGI(TAG, "Ethernet Link Up, MAC " MACSTR, MAC2STR(mac)); + esp_netif_create_ip6_linklocal(s_eth_netif); // lets mDNS answer AAAA queries (see espnow_tx.c) xTaskCreate(link_up_task, "link_up", 4096, NULL, 5, NULL); ESP_LOGI(TAG, "%s Mbps %s Duplex", speed == ETH_SPEED_100M ? "100" : "10", @@ -407,21 +441,31 @@ void app_main(void) ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default()); - esp_eth_handle_t eth_handle = NULL; - ESP_ERROR_CHECK(w5500_init(ð_handle)); - - esp_netif_config_t netif_cfg = ESP_NETIF_DEFAULT_ETH(); - s_eth_netif = esp_netif_new(&netif_cfg); - ESP_ERROR_CHECK(esp_netif_attach(s_eth_netif, esp_eth_new_netif_glue(eth_handle))); - + // Wi-Fi (AP + ESP-NOW) comes up first so the AP is there even if Ethernet fails const char *host = settings_str("hostname"); - esp_netif_set_hostname(s_eth_netif, host ? host : DEFAULT_HOSTNAME); + 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)" : ""); + ESP_ERROR_CHECK(espnow_tx_init(s_ap_on ? (host ? host : DEFAULT_HOSTNAME) : NULL, settings_str("ap_password"))); - ESP_ERROR_CHECK(esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, ð_event_handler, NULL)); - ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &got_ip_event_handler, NULL)); + // Ethernet is optional: without it the web UI is still served over the AP + esp_eth_handle_t eth_handle = NULL; + if (w5500_init(ð_handle) == ESP_OK) { + esp_netif_config_t netif_cfg = ESP_NETIF_DEFAULT_ETH(); + s_eth_netif = esp_netif_new(&netif_cfg); + ESP_ERROR_CHECK(esp_netif_attach(s_eth_netif, esp_eth_new_netif_glue(eth_handle))); - ESP_ERROR_CHECK(esp_eth_start(eth_handle)); - ESP_ERROR_CHECK(espnow_tx_init()); + esp_netif_set_hostname(s_eth_netif, host ? host : DEFAULT_HOSTNAME); + + ESP_ERROR_CHECK(esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, ð_event_handler, NULL)); + ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &got_ip_event_handler, NULL)); + + ESP_ERROR_CHECK(esp_eth_start(eth_handle)); + } else { + ESP_LOGE(TAG, "Ethernet unavailable, continuing without it%s", s_ap_on ? " (web UI on the AP)" : ""); + start_webserver(); + start_mdns(); + } ESP_ERROR_CHECK(rel_init()); ESP_ERROR_CHECK(engine_init()); ESP_ERROR_CHECK(mic_start()); diff --git a/sdkconfig.defaults b/sdkconfig.defaults index 8fdf459..74d29f4 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -22,3 +22,12 @@ CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y CONFIG_HTTPD_WS_SUPPORT=y CONFIG_HTTPD_WS_POST_HANDSHAKE_CB_SUPPORT=y CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=8192 +CONFIG_LWIP_TCP_SND_BUF_DEFAULT=16384 +CONFIG_LWIP_TCP_WND_DEFAULT=16384 +CONFIG_LWIP_TCP_RECVMBOX_SIZE=12 +CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=16 +CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=64 +CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=64 +CONFIG_ESP_WIFI_TX_BA_WIN=16 +CONFIG_ESP_WIFI_RX_BA_WIN=16 +CONFIG_LWIP_MAX_SOCKETS=16 diff --git a/web/static/help.js b/web/static/help.js index c4d9491..fa2e684 100644 --- a/web/static/help.js +++ b/web/static/help.js @@ -98,6 +98,9 @@ document.addEventListener('DOMContentLoaded', () => { const hostInput = document.getElementById('hostname-input'); if (hostInput && staticIpsList && data && typeof data === 'object') { hostInput.value = data.hostname || ''; + setApToggle(data.ap_enabled !== false); + const apPw = document.getElementById('ap-password-input'); + if (apPw) apPw.value = data.ap_password || ''; staticIpsList.innerHTML = ''; (Array.isArray(data.static_ips) ? data.static_ips : []).forEach(addStaticIpRow); } @@ -106,6 +109,19 @@ document.addEventListener('DOMContentLoaded', () => { } } + const apToggle = document.getElementById('ap-enabled-toggle'); + function setApToggle(on) { + if (apToggle) { + apToggle.setAttribute('aria-pressed', on ? 'true' : 'false'); + apToggle.classList.toggle('is-on', on); + } + } + if (apToggle) { + apToggle.addEventListener('click', () => { + setApToggle(apToggle.getAttribute('aria-pressed') !== 'true'); + }); + } + const staticIpsList = document.getElementById('static-ips-list'); const STATIC_IP_FIELDS = [ ['ip', 'IP address', '192.168.1.50'], @@ -256,6 +272,11 @@ document.addEventListener('DOMContentLoaded', () => { showSettingsMessage('Hostname may only contain letters, digits and hyphens', 'error'); return; } + const apPassword = (document.getElementById('ap-password-input') || { value: '' }).value; + if (apPassword && (apPassword.length < 8 || apPassword.length > 63)) { + showSettingsMessage('Access point password must be 8 to 63 characters, or empty for open', 'error'); + return; + } let staticIps; try { staticIps = readStaticIps(); @@ -267,7 +288,12 @@ document.addEventListener('DOMContentLoaded', () => { const response = await fetch('/settings/settings', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ hostname, static_ips: staticIps }), + body: JSON.stringify({ + hostname, + static_ips: staticIps, + ap_password: apPassword, + ap_enabled: !apToggle || apToggle.getAttribute('aria-pressed') === 'true', + }), }); const result = await response.json(); if (response.ok) { diff --git a/web/static/style.css b/web/static/style.css index 6ecf21a..4dd60c6 100644 --- a/web/static/style.css +++ b/web/static/style.css @@ -1282,6 +1282,16 @@ html.simulated-bpm-mode .seq-switch-toggle-wrap { background-color: #e8e4ff; } +.nav-slide-toggle-switch.is-on { + background-color: #1b5e20; + border-color: #4caf50; +} + +.nav-slide-toggle-switch.is-on .nav-slide-toggle-thumb { + left: calc(100% - 1rem - 2px); + background-color: #e8f5e9; +} + .main-menu-dropdown .nav-slide-toggle-wrap--mobile { display: flex; justify-content: center; diff --git a/web/templates/index.html b/web/templates/index.html index daae417..4da7587 100644 --- a/web/templates/index.html +++ b/web/templates/index.html @@ -1182,6 +1182,20 @@ The controller answers at hostname.local. +
+ + + Named after the hostname; the controller is at 192.168.5.1 on it. Holding the button on D7 while the controller boots turns it on even when this is off. +
+
+ + + 8 to 63 characters (WPA2). Leave empty for an open network. +
Tried in order each time the Ethernet link comes up; the first whose gateway answers is used. If none does, or the list is empty, DHCP is used. With no DHCP server, as on a cable straight to a PC, the controller is at 192.168.4.1; give the PC a static IP such as 192.168.4.2.