Skip to content

Commit 8dfa0b5

Browse files
DTTerastarclaude
andcommitted
Rescue portal fixes from testing on a C3 dev board
- Close the rescue AP before joining the entered network. With a phone on the AP the WPA handshake kept timing out (reason 15); with the AP closed it joined in 2 s. The AP reopens after a minute if it fails. - Save WiFi config to NVS until the erase starts (then RAM only), so a network entered before the copy to ota_1 survives that reboot. - Captive portal: DHCP hands out 192.168.4.1 as DNS, every A query answers 192.168.4.1, every GET serves the page, so phones pop it up. - Raise the HTTP header limit to 2048: phones got 431 at 512. - Name the AP espreswitch-<suffix> with the same suffix ESPresense uses (last three base-MAC bytes, reversed). - Log the STA disconnect reason and the received password length; join PMF-capable. Tested: no WiFi -> AP at 60 s -> form posted -> joined -> copied to ota_1 -> rejoined from NVS without the portal -> ESPresense at 380 s. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018ddLgHVXMofL5Z725JL3uM
1 parent 3235239 commit 8dfa0b5

6 files changed

Lines changed: 115 additions & 25 deletions

File tree

‎AGENTS.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ own bootloader and partition table instead of Tasmota's.
1818
offset 0. It MD5-checks both the download and a read-back of flash, and retries until both match.
1919
With no saved WiFi it joins `espreswitch`/`espreswitch` (`config.h`; was `switchbota` before v0.4.1).
2020
If WiFi is down for a minute, the stage also opens an AP `espreswitch-xxxxxx` with a page at
21-
192.168.4.1 to enter a new network (kept in RAM only: NVS at `0x9000` is inside the erased region).
21+
192.168.4.1 to enter a new network. WiFi config is saved to NVS until the erase starts, then RAM only
22+
(`wifi_stop_persisting()`): NVS (`0x9000` or `0xE000`) is inside the erased region.
2223
The LEDs (GPIO7/8, active low) show the state, one pattern per stuck state (`espressif/main/led.c`).
2324
Once erased, only the two erased patterns show. The README "What the LEDs mean" table must
2425
match `led.c`; update both together.
@@ -65,7 +66,7 @@ reads the partition table at runtime, so it tolerates either of the last two lay
6566

6667
## Status (2026-10-11)
6768

68-
- `v0.4.0` released (stage `app.bin` + `.md5`): payload info from the server, re-checked on every retry; WiFi rescue portal; LED status. CI is green.
69+
- `v0.4.2` released (stage `app.bin` + `.md5`): payload info from the server, re-checked on every retry; WiFi rescue portal (captive, AP closes before joining, network kept until the erase); LED status. CI is green.
6970
- `payload.json` pins `esp32c3.factory.bin` from the **ESPresense v5.0.0b1 pre-release** (release asset,
7071
so it doesn't expire). Writing it ends at `0x174000`, below both `0x220000` (stock) and `0x1E0000` (Tasmota v11 layout).
7172
- **Tested end-to-end on 2026-10-11** with v0.4.0:
@@ -75,7 +76,10 @@ reads the partition table at runtime, so it tolerates either of the last two lay
7576
`/version/wocaotech/firmware/WoPlugUS/WoPlugUS_V12.bin`; nothing more until `57 0F 0B`, which installs
7677
and reboots. The stage was already in `ota_1` (no `/app.bin` copy), wrote the payload first try,
7778
and the plug came up as ESPresense.
78-
- Not exercised yet: the rescue portal, the plug's LED patterns, the Tasmota v11 layout.
79+
- Rescue portal (v0.4.2, C3 dev board, an ESP32-S3 posting the form): AP opened at 60 s; after the
80+
save the stage closes the AP, then joins (with the AP open, the WPA handshake timed out: reason 15);
81+
the network survived the reboot into `ota_1` (saved to NVS until the erase); converted at 380 s.
82+
- Not exercised yet: the plug's LED patterns, the Tasmota v11 layout.
7983

8084
### Background: plugs converted via Tasmota
8185

‎README.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -158,15 +158,15 @@ Two different networks are involved, so keep them apart:
158158
| Network | Created by | What it's for |
159159
|---|---|---|
160160
| `espreswitch` (password `espreswitch`) | **You**, on your router or a phone hotspot | A network the plug **joins** if it has no saved WiFi. It must resolve `wohand.com` to the ESPreSwitch server |
161-
| `espreswitch-xxxxxx` (open; `xxxxxx` is the end of its MAC address) | **The plug** | A rescue network the plug **opens** after a minute without WiFi, so you can give it one |
161+
| `espreswitch-xxxxxx` (open; `xxxxxx` matches the `espresense-xxxxxx` network it opens once converted) | **The plug** | A rescue network the plug **opens** after a minute without WiFi, so you can give it one |
162162

163163
The stage joins the WiFi network saved in the plug (the one you set in the SwitchBot app). Only if the plug has no saved WiFi at all does it join `espreswitch` instead. If it still has no WiFi after a minute, it opens `espreswitch-xxxxxx`:
164164

165-
1. Join `espreswitch-xxxxxx` from a phone or laptop and browse to http://192.168.4.1.
165+
1. Join `espreswitch-xxxxxx` from a phone or laptop. The page should pop up by itself; if not, browse to http://192.168.4.1.
166166
2. Enter a WiFi network the plug can use. That network has to resolve `wohand.com` to the ESPreSwitch server: your normal LAN with the DNS override, or any network whose DHCP hands out the server's IP as DNS.
167-
3. The `espreswitch-xxxxxx` network disappears once the plug connects, and the flash carries on.
167+
3. The `espreswitch-xxxxxx` network closes as soon as you save, while the plug joins your network (one radio can't do both reliably). If the plug can't join, `espreswitch-xxxxxx` comes back in about a minute: reconnect and check the name and password.
168168

169-
This works even after the flash is erased, as long as the plug stays powered. The new network is kept in RAM only, so a power cut loses it, but a power cut after the erase means opening the plug anyway.
169+
This works even after the flash is erased, as long as the plug stays powered. A network entered before the erase is saved, so it survives the plug's own reboot into its second app slot and you only enter it once. A network entered after the erase is kept in RAM only (the saved-settings area is part of what gets erased), but a power cut after the erase means opening the plug anyway.
170170

171171
## Updating the payload
172172
1. Pick an ESPresense build that publishes `esp32c3.factory.bin` (release asset or CI artifact).

‎espressif/main/include/wifi.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,4 @@
1717

1818
void wifi_init();
1919
int wifi_is_connected();
20+
void wifi_stop_persisting(); // call before erasing: NVS is inside the erased region

‎espressif/main/ota.c‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434

3535
#include "ota.h"
3636
#include "led.h"
37+
#include "wifi.h"
3738

3839
static const char *TAG = "ota";
3940

@@ -241,6 +242,7 @@ void ota_inject() {
241242
return;
242243
}
243244

245+
wifi_stop_persisting();
244246
ESP_LOGI(TAG, "erasing bootloader! don't lose power now!");
245247
led_set(LED_WRITING);
246248
ESP_ERROR_CHECK( esp_flash_erase_region(NULL, 0, write_size) );

‎espressif/main/wifi.c‎

Lines changed: 100 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@
3131

3232
#include "lwip/err.h"
3333
#include "lwip/sys.h"
34+
#include "lwip/sockets.h"
35+
#include "dhcpserver/dhcpserver.h"
36+
#include "tcpip_adapter.h"
3437

3538
#include "wifi.h"
3639
#include "config.h"
@@ -42,6 +45,7 @@ static EventGroupHandle_t s_wifi_event_group;
4245

4346
#define WIFI_CONNECTED_BIT BIT0
4447
#define WIFI_FAIL_BIT BIT1
48+
#define WIFI_NEW_CONFIG_BIT BIT2 // portal saved a network: close the AP, then join it
4549

4650
static void wifi_task(void *pvParameters);
4751

@@ -52,6 +56,7 @@ static void wifi_task(void *pvParameters);
5256
#define PORTAL_RETRY_MS 30000
5357
static volatile bool portal_active = false;
5458
static httpd_handle_t portal_server = NULL;
59+
static void portal_dhcp_dns(void);
5560

5661
static void wifi_set_connected(uint8_t c) {
5762
if (c) {
@@ -79,7 +84,7 @@ esp_err_t event_handler(void *ctx, system_event_t *event)
7984
break;
8085

8186
case SYSTEM_EVENT_STA_DISCONNECTED:
82-
ESP_LOGI(TAG, "event_handler: SYSTEM_EVENT_STA_DISCONNECTED");
87+
ESP_LOGI(TAG, "event_handler: SYSTEM_EVENT_STA_DISCONNECTED, reason %d", event->event_info.disconnected.reason);
8388
// try to re-connect; with the portal up, wifi_task retries less often, because each
8489
// attempt scans every channel and knocks phones off the AP
8590
if (!portal_active) esp_wifi_connect();
@@ -89,6 +94,7 @@ esp_err_t event_handler(void *ctx, system_event_t *event)
8994

9095
case SYSTEM_EVENT_AP_START:
9196
ESP_LOGI(TAG, "event_handler: SYSTEM_EVENT_AP_START");
97+
if (portal_active) portal_dhcp_dns();
9298
break;
9399

94100
case SYSTEM_EVENT_AP_STOP:
@@ -112,6 +118,14 @@ esp_err_t event_handler(void *ctx, system_event_t *event)
112118
}
113119
return ESP_OK;
114120
}
121+
// WiFi config is saved to NVS (so a network entered in the portal survives the reboot into ota_1)
122+
// until the erase starts. NVS (0x9000 or 0xE000) is inside the erased region, so from then on it
123+
// must only live in RAM.
124+
void wifi_stop_persisting()
125+
{
126+
esp_wifi_set_storage(WIFI_STORAGE_RAM);
127+
}
128+
115129
int wifi_is_connected()
116130
{
117131
return xEventGroupGetBits(s_wifi_event_group) & WIFI_CONNECTED_BIT;
@@ -123,8 +137,6 @@ void wifi_connect()
123137
// get default config ...
124138
wifi_config_t existing_config = { 0 };
125139
esp_wifi_get_config(WIFI_IF_STA, &existing_config);
126-
// Never write WiFi config to NVS: 0x9000 is inside the region being erased and rewritten.
127-
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
128140
ESP_LOGI(TAG, "%s", existing_config.sta.ssid);
129141
if(strlen((char *)existing_config.sta.ssid) == 0 || strcmp((char *)existing_config.sta.ssid, "wocao_factory_test") == 0) {
130142
ESP_LOGI(TAG, "defaulting to fallback network ...");
@@ -202,54 +214,125 @@ static esp_err_t portal_save(httpd_req_t *req)
202214
strlcpy((char *)config.sta.password, value, sizeof(config.sta.password));
203215
}
204216

205-
ESP_LOGI(TAG, "portal: switching to network %s", (char *)config.sta.ssid);
206-
esp_wifi_disconnect();
217+
config.sta.pmf_cfg.capable = true; // join PMF-optional (WPA2/WPA3 transition) networks with PMF
218+
ESP_LOGI(TAG, "portal: switching to network %s (password %d chars)", (char *)config.sta.ssid,
219+
(int)strlen((char *)config.sta.password));
207220
esp_wifi_set_config(WIFI_IF_STA, &config);
208-
esp_wifi_connect();
209221
httpd_resp_set_type(req, "text/html");
210-
return httpd_resp_send(req, "<p>Connecting. If it works, this network disappears and the flash carries on.",
211-
HTTPD_RESP_USE_STRLEN);
222+
esp_err_t err = httpd_resp_send(req,
223+
"<p>Saved. This network closes now while the plug joins yours. If it can't join, this network "
224+
"comes back in about a minute: reconnect and check the name and password.", HTTPD_RESP_USE_STRLEN);
225+
// Join from wifi_task with the AP closed: with a phone on the AP, the radio splits its time
226+
// between channels and the WPA handshake times out (reason 15).
227+
xEventGroupSetBits(s_wifi_event_group, WIFI_NEW_CONFIG_BIT);
228+
return err;
229+
}
230+
231+
// Captive portal: phones on the rescue AP get 192.168.4.1 as their DNS server, and every A query is
232+
// answered with 192.168.4.1, so their connectivity check lands on our page and they pop it up.
233+
// The plug's own lookups (wohand.com on the real WiFi) don't go through this.
234+
static void portal_dhcp_dns(void)
235+
{
236+
tcpip_adapter_ip_info_t ip;
237+
tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip);
238+
tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP);
239+
dhcps_offer_t offer = OFFER_DNS;
240+
tcpip_adapter_dhcps_option(TCPIP_ADAPTER_OP_SET, TCPIP_ADAPTER_DOMAIN_NAME_SERVER, &offer, sizeof(offer));
241+
tcpip_adapter_dns_info_t dns = { 0 };
242+
dns.ip.type = IPADDR_TYPE_V4;
243+
dns.ip.u_addr.ip4.addr = ip.ip.addr;
244+
tcpip_adapter_set_dns_info(TCPIP_ADAPTER_IF_AP, ESP_NETIF_DNS_MAIN, &dns);
245+
tcpip_adapter_dhcps_start(TCPIP_ADAPTER_IF_AP);
246+
}
247+
248+
static void portal_dns_task(void *pvParameters)
249+
{
250+
int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
251+
struct sockaddr_in addr = { .sin_family = AF_INET, .sin_port = htons(53), .sin_addr.s_addr = htonl(INADDR_ANY) };
252+
struct timeval tv = { .tv_sec = 1 };
253+
if (s < 0 || bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
254+
ESP_LOGE(TAG, "portal: DNS server failed to start");
255+
if (s >= 0) close(s);
256+
vTaskDelete(NULL);
257+
return;
258+
}
259+
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
260+
uint8_t buf[512];
261+
while (portal_active) {
262+
struct sockaddr_in from;
263+
socklen_t fromlen = sizeof(from);
264+
int n = recvfrom(s, buf, sizeof(buf) - 16, 0, (struct sockaddr *)&from, &fromlen);
265+
if (n < 12) continue;
266+
int i = 12; // skip the question name
267+
while (i < n && buf[i]) i += buf[i] + 1;
268+
if (i + 5 > n) continue;
269+
bool a = buf[i + 1] == 0 && buf[i + 2] == 1;
270+
n = i + 5; // header + one question; drop anything after it
271+
buf[2] = 0x81; buf[3] = 0x80; // response, no error
272+
buf[4] = 0; buf[5] = 1; // one question
273+
buf[6] = 0; buf[7] = a ? 1 : 0; // one answer for A, none otherwise
274+
buf[8] = buf[9] = buf[10] = buf[11] = 0;
275+
if (a) {
276+
uint8_t ans[] = { 0xC0, 0x0C, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 192, 168, 4, 1 };
277+
memcpy(buf + n, ans, sizeof(ans));
278+
n += sizeof(ans);
279+
}
280+
sendto(s, buf, n, 0, (struct sockaddr *)&from, fromlen);
281+
}
282+
close(s);
283+
vTaskDelete(NULL);
212284
}
213285

214286
static void portal_start(void)
215287
{
288+
// Same suffix as ESPresense's own AP (espresense-xxxxxx): last three bytes of the base MAC,
289+
// reversed, so both networks name the plug the same way.
216290
uint8_t mac[6];
217-
esp_wifi_get_mac(WIFI_IF_AP, mac);
291+
esp_efuse_mac_get_default(mac);
218292
wifi_config_t ap = { .ap = { .max_connection = 2, .authmode = WIFI_AUTH_OPEN } };
219-
ap.ap.ssid_len = snprintf((char *)ap.ap.ssid, sizeof(ap.ap.ssid), "espreswitch-%02x%02x%02x", mac[3], mac[4], mac[5]);
293+
ap.ap.ssid_len = snprintf((char *)ap.ap.ssid, sizeof(ap.ap.ssid), "espreswitch-%02x%02x%02x", mac[5], mac[4], mac[3]);
220294
portal_active = true;
221295
led_set(LED_PORTAL);
222296
esp_wifi_set_mode(WIFI_MODE_APSTA);
223297
esp_wifi_set_config(WIFI_IF_AP, &ap);
224298

225299
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
300+
config.uri_match_fn = httpd_uri_match_wildcard; // every GET gets the page, incl. phones' connectivity checks
226301
if (httpd_start(&portal_server, &config) == ESP_OK) {
227-
httpd_uri_t get = { .uri = "/", .method = HTTP_GET, .handler = portal_get };
228302
httpd_uri_t save = { .uri = "/save", .method = HTTP_POST, .handler = portal_save };
229-
httpd_register_uri_handler(portal_server, &get);
303+
httpd_uri_t get = { .uri = "/*", .method = HTTP_GET, .handler = portal_get };
230304
httpd_register_uri_handler(portal_server, &save);
305+
httpd_register_uri_handler(portal_server, &get);
231306
}
307+
xTaskCreate(&portal_dns_task, "portalDns", 3072, NULL, 4, NULL);
232308
ESP_LOGI(TAG, "portal: no WiFi, opened AP %s at http://192.168.4.1", (char *)ap.ap.ssid);
233309
}
234310

235-
static void portal_stop(void)
311+
static void portal_stop(const char *why)
236312
{
237313
if (portal_server) httpd_stop(portal_server);
238314
portal_server = NULL;
239315
esp_wifi_set_mode(WIFI_MODE_STA);
240316
portal_active = false;
241317
led_set(wifi_is_connected() ? LED_READY : LED_WIFI);
242-
ESP_LOGI(TAG, "portal: WiFi back, closed AP");
318+
ESP_LOGI(TAG, "portal: closed AP (%s)", why);
243319
}
244320

245321
void wifi_task(void *pvParameters)
246322
{
247323
while (1) {
248324
TickType_t wait = (portal_active ? PORTAL_RETRY_MS : PORTAL_DELAY_MS) / portTICK_PERIOD_MS;
249-
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT, false, true, wait);
250-
if (bits & WIFI_CONNECTED_BIT) {
325+
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT | WIFI_NEW_CONFIG_BIT,
326+
false, false, wait);
327+
if (bits & WIFI_NEW_CONFIG_BIT) {
328+
xEventGroupClearBits(s_wifi_event_group, WIFI_NEW_CONFIG_BIT);
329+
vTaskDelay(1000 / portTICK_PERIOD_MS); // let the "Saved" page reach the phone
330+
if (portal_active) portal_stop("joining the new network");
331+
esp_wifi_disconnect();
332+
esp_wifi_connect(); // portal reopens after PORTAL_DELAY_MS if this fails
333+
} else if (bits & WIFI_CONNECTED_BIT) {
251334
ESP_LOGI(TAG, "networkTask: connected to access point");
252-
if (portal_active) portal_stop();
335+
if (portal_active) portal_stop("WiFi back");
253336
while (wifi_is_connected()) { vTaskDelay(1000 / portTICK_PERIOD_MS); }
254337
} else if (!portal_active) {
255338
portal_start();

‎espressif/sdkconfig‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,7 @@ CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH=y
339339
#
340340
# HTTP Server
341341
#
342-
CONFIG_HTTPD_MAX_REQ_HDR_LEN=512
342+
CONFIG_HTTPD_MAX_REQ_HDR_LEN=2048
343343
CONFIG_HTTPD_MAX_URI_LEN=512
344344
CONFIG_HTTPD_ERR_RESP_NO_DELAY=y
345345
CONFIG_HTTPD_PURGE_BUF_LEN=32

0 commit comments

Comments
 (0)