Add BOOT-button entry to the setup portal and gate the Wi-Fi card behind login

Hold BOOT (GPIO0) for 10s while running to reboot into the captive
portal without needing the current media login (physical access is the
proof). This also covers the "forgotten login" case.

button.c (new)
- button_task polls GPIO0 (pull-up, 50 ms), ignores a press held since
  boot so download-mode entry is unaffected, and calls
  wifi_request_portal_physical() after 10s.
- Started from app_main() right after wifi_start_provisioning_if_needed(),
  only when not provisioning, so it also works while the station is
  retrying an unreachable network.

wifi.c
- wifi_request_portal_physical(): stores a one-shot "portal requested by
  button" flag in NVS (namespace "portal") and restarts. NVS is used
  instead of RTC_DATA_ATTR because the flag was lost across the reset
  on this board.
- wifi_start_provisioning_if_needed(): reads and erases the flag at boot
  (portal_flag_take) and sets s_physical for that portal session only.
  Logs the reset reason.
- Portal without the button (30 failed reconnects, wifi_request_portal())
  stays non-physical and asks for the current login.
- /save (Wi-Fi card) now requires cam_auth_verify() unless s_physical.
- /auth uses cam_auth_set() when s_physical, else cam_auth_change().
- Shared lockout: 5 wrong logins block /save and /auth until restart
  (not applied when s_physical). Failed attempts are delayed by 1 s.
- Physical portal times out after 180 s (normal portal: 300 s).
- Root page gets "var PHYS=0/1" injected before its script via chunked
  send; with PHYS=1 the "current login" fields are hidden and a banner
  is shown.
- html: added current-login fields (wu/wp) to the Wi-Fi form, wrapped
  current-login fields in .cur, /save errors are shown to the user.
- read_body()/send_text() moved above the handlers.

cam_auth.c
- New cam_auth_set(): validates and stores a new login with no check of
  the current one. cam_auth_change() now = cam_auth_verify() +
  cam_auth_set().

Requirements
- cam_auth_load() must run before wifi_start_provisioning_if_needed(),
  otherwise cam_auth_verify() treats auth as disabled and accepts any
  login.
- cam_auth.h: declare cam_auth_set(); declare
  wifi_request_portal_physical() where button.c can see it.

Tested on board: long press reboots into the AP "ESP32_Setup" instead of
reconnecting to the stored network. Not yet tested: Wi-Fi card login
gating, lockout, 180 s timeout, portal page rendering on a phone.
This commit is contained in:
2026-10-11 15:26:53 +03:30
parent 72a2d714ab
commit 194671d387
12 changed files with 653 additions and 75 deletions
+282 -53
View File
@@ -1,3 +1,36 @@
/*
* wifi.c - Wi-Fi station + captive-portal provisioning
*
* Public API (declare in board.h or the camera file):
* void wifi_start_provisioning_if_needed(void);
* bool wifi_wait_connected(uint32_t timeout_ms);
* bool wifi_is_provisioning(void);
* void wifi_erase_credentials(void);
* void wifi_request_portal(void); reboot into the portal; login REQUIRED there
* void wifi_request_portal_physical(void); reboot into the portal opened by the BOOT button;
* no current login needed there
* bool wifi_portal_is_physical(void);
*
* Flow:
* - Boot: read SSID/password from NVS.
* - No credentials (or too many failed reconnects, or a portal request) -> open AP
* "ESP32_Setup" with DNS hijack + web page at http://192.168.4.1/
* - Credentials found -> station mode, WIFI_CONNECTED_BIT is set on got-IP.
*
* Portal security:
* - Normal portal: BOTH cards (Wi-Fi and login) need the current media login.
* - Portal opened by holding BOOT: physical access is the proof, so no login is asked.
* The flag lives in RTC memory: one-shot, survives esp_restart(), lost on power cycle.
* - 5 wrong logins lock the portal until restart (not applied in the physical case).
*
* IMPORTANT: cam_auth_load() must run BEFORE wifi_start_provisioning_if_needed(),
* otherwise cam_auth_verify() sees "auth disabled" and accepts everything.
*
* The media servers (camera on :80, audio on :81/:82) must be started by the
* caller only AFTER wifi_wait_connected() returns true, so they never collide
* with the portal's HTTP server on port 80.
*/
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
@@ -15,6 +48,7 @@
#include "esp_http_server.h"
#include "lwip/sockets.h"
#include "board.h"
#include "cam_auth.h"
/* ---- Fallbacks, used only if board.h does not define them ---- */
#ifndef WIFI_NS
@@ -30,12 +64,16 @@
#define WIFI_CONNECTED_BIT BIT0
#endif
#define PROV_TIMEOUT_SEC 300 /* portal closes and board restarts after this */
#define MAX_RECONNECT_TRIES 30 /* then the board reboots into the portal */
#define AP_SSID "ESP32_Setup"
#define AP_CHANNEL 6
#define AP_IP_STR "192.168.4.1"
#define HOSTNAME "hodor-cam"
#define PROV_TIMEOUT_SEC 300 /* portal closes and board restarts after this */
#define PROV_TIMEOUT_PHYS_SEC 180 /* shorter window when no login is needed (BOOT button) */
#define MAX_RECONNECT_TRIES 30 /* then the board reboots into the portal */
#define MAX_AUTH_FAILS 5
#define AP_SSID "ESP32_Setup"
#define AP_CHANNEL 6
#define AP_IP_STR "192.168.4.1"
#define HOSTNAME "hodor-cam"
#define PORTAL_NS "portal"
static const char *TAG = "WIFI";
@@ -47,16 +85,18 @@ static TimerHandle_t s_prov_timer = NULL;
static esp_netif_t *s_sta_netif = NULL;
static esp_netif_t *s_ap_netif = NULL;
static bool s_provisioning = false;
static bool s_physical = false; /* portal opened by the BOOT button */
static int s_retry = 0;
static int s_auth_fail = 0; /* wrong logins since the portal started */
/* Survive esp_restart() (software reset), lost on power cycle */
RTC_DATA_ATTR static bool rtc_force_portal = false; /* set after too many failed reconnects */
RTC_DATA_ATTR static bool rtc_hint_valid = false; /* fast-connect channel hint */
RTC_DATA_ATTR static bool rtc_hint_valid = false; /* fast-connect channel hint */
RTC_DATA_ATTR static uint8_t rtc_hint_channel = 0;
/* ------------------------------------------------------------------ */
/* Portal web page */
/* ------------------------------------------------------------------ */
/* The page contains exactly one "<script>"; the root handler injects "var PHYS=0/1;" there. */
static const char *html_settings =
"<!DOCTYPE html>"
"<html lang='fa' dir='rtl'>"
@@ -65,16 +105,18 @@ static const char *html_settings =
"<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
"<title>تنظیمات وای‌فای</title>"
"<style>"
"body{font-family:Tahoma,Arial,sans-serif;background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);min-height:100vh;display:flex;align-items:center;justify-content:center;margin:0}"
"body{font-family:Tahoma,Arial,sans-serif;background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:20px;padding:20px 0;box-sizing:border-box;margin:0}"
".container{background:#fff;padding:30px;border-radius:15px;box-shadow:0 10px 40px rgba(0,0,0,.2);width:90%;max-width:400px}"
"h1{color:#333;text-align:center;margin-bottom:25px;font-size:22px}"
"label{display:block;margin-bottom:8px;color:#555;font-weight:bold}"
"input{width:100%;padding:12px;margin-bottom:20px;border:2px solid #ddd;border-radius:8px;box-sizing:border-box;font-size:16px}"
"button{width:100%;padding:15px;background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);color:#fff;border:none;border-radius:8px;font-size:18px;cursor:pointer}"
".status{padding:15px;margin-top:20px;border-radius:8px;text-align:center;display:none;background:#eef}"
"#phys{display:none;background:#e6ffed;color:#14532d;padding:12px;border-radius:8px;width:90%;max-width:400px;text-align:center;box-sizing:border-box}"
"</style>"
"</head>"
"<body>"
"<div id='phys'>باز شده با کلید روی دستگاه — نیازی به نام کاربری و رمز فعلی نیست.</div>"
"<div class='container'>"
"<h1>⚙️ تنظیمات وای‌فای</h1>"
"<form id='wifiForm'>"
@@ -82,11 +124,39 @@ static const char *html_settings =
"<input type='text' id='ssid' maxlength='32' required>"
"<label>رمز عبور:</label>"
"<input type='password' id='pass' maxlength='63'>"
"<div class='cur'>"
"<label>نام کاربری فعلی دوربین:</label>"
"<input type='text' id='wu' maxlength='47' autocomplete='off' required>"
"<label>رمز عبور فعلی دوربین:</label>"
"<input type='password' id='wp' maxlength='63' autocomplete='off' required>"
"</div>"
"<button type='submit'>ذخیره و اتصال</button>"
"</form>"
"<div id='status' class='status'></div>"
"</div>"
"<div class='container'>"
"<h1>🔐 تغییر نام کاربری و رمز عبور</h1>"
"<form id='authForm'>"
"<div class='cur'>"
"<label>نام کاربری فعلی:</label>"
"<input type='text' id='ou' maxlength='47' autocomplete='off' required>"
"<label>رمز عبور فعلی:</label>"
"<input type='password' id='op' maxlength='63' autocomplete='off' required>"
"</div>"
"<label>نام کاربری جدید:</label>"
"<input type='text' id='nu' maxlength='31' autocomplete='off' required>"
"<label>رمز عبور جدید (۸ تا ۳۲ حرف انگلیسی یا عدد):</label>"
"<input type='password' id='np' maxlength='32' autocomplete='off' required>"
"<label>تکرار رمز عبور جدید:</label>"
"<input type='password' id='np2' maxlength='32' autocomplete='off' required>"
"<button type='submit'>ذخیره</button>"
"</form>"
"<div id='astatus' class='status'></div>"
"</div>"
"<script>"
"if(PHYS){document.querySelectorAll('.cur input').forEach(i=>i.required=false);"
"document.querySelectorAll('.cur').forEach(d=>d.style.display='none');"
"document.getElementById('phys').style.display='block';}"
"document.getElementById('wifiForm').addEventListener('submit',async(e)=>{"
"e.preventDefault();"
"const st=document.getElementById('status');"
@@ -94,12 +164,32 @@ static const char *html_settings =
"const fd=new URLSearchParams();"
"fd.append('ssid',document.getElementById('ssid').value);"
"fd.append('pass',document.getElementById('pass').value);"
"fd.append('wu',document.getElementById('wu').value);"
"fd.append('wp',document.getElementById('wp').value);"
"try{"
"const r=await fetch('/save',{method:'POST',body:fd});"
"if(r.ok){st.innerHTML='✅ ذخیره شد. دستگاه ری‌استارت می‌شود؛ به وای‌فای اصلی خود وصل شوید.';}"
"else{st.innerHTML='❌ مقادیر نامعتبر است (رمز باید ۸ تا ۶۳ حرف باشد).';}"
"else{st.innerHTML='❌ '+await r.text();}"
"}catch(err){st.innerHTML='✅ ذخیره شد. دستگاه ری‌استارت می‌شود.';}"
"});"
"document.getElementById('authForm').addEventListener('submit',async(e)=>{"
"e.preventDefault();"
"const st=document.getElementById('astatus');"
"st.style.display='block';"
"const np=document.getElementById('np').value;"
"if(np!==document.getElementById('np2').value){st.innerHTML='❌ رمز جدید و تکرار آن یکسان نیست.';return;}"
"st.innerHTML='⏳ در حال بررسی...';"
"const fd=new URLSearchParams();"
"fd.append('ou',document.getElementById('ou').value);"
"fd.append('op',document.getElementById('op').value);"
"fd.append('nu',document.getElementById('nu').value);"
"fd.append('np',np);"
"try{"
"const r=await fetch('/auth',{method:'POST',body:fd});"
"if(r.ok){st.innerHTML='✅ ذخیره شد. دستگاه ری‌استارت می‌شود.';}"
"else{st.innerHTML='❌ '+await r.text();}"
"}catch(err){st.innerHTML='ارتباط قطع شد؛ اگر دستگاه ری‌استارت شده، تغییر ذخیره شده است.';}"
"});"
"</script>"
"</body>"
"</html>";
@@ -142,6 +232,33 @@ void wifi_erase_credentials(void)
}
}
static bool read_body(httpd_req_t *req, char *body, size_t size)
{
size_t total = req->content_len;
if (total == 0 || total >= size) return false;
size_t got = 0;
while (got < total) {
int r = httpd_req_recv(req, body + got, total - got);
if (r == HTTPD_SOCK_ERR_TIMEOUT) continue;
if (r <= 0) return false;
got += r;
}
body[got] = '\0';
return true;
}
static esp_err_t send_text(httpd_req_t *req, const char *status, const char *msg)
{
httpd_resp_set_status(req, status);
httpd_resp_set_type(req, "text/plain; charset=utf-8");
return httpd_resp_send(req, msg, HTTPD_RESP_USE_STRLEN);
}
#define MSG_LOCKED "تعداد تلاش‌های ناموفق زیاد است. دستگاه را ری‌استارت کنید."
#define MSG_BAD_REQ "درخواست نامعتبر است."
#define MSG_BAD_LOGIN "نام کاربری یا رمز عبور فعلی اشتباه است."
#define MSG_STORE_ERR "خطا در ذخیره‌سازی."
/* ------------------------------------------------------------------ */
/* Portal HTTP server */
/* ------------------------------------------------------------------ */
@@ -149,62 +266,114 @@ static esp_err_t root_get_handler(httpd_req_t *req)
{
httpd_resp_set_type(req, "text/html; charset=utf-8");
httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
return httpd_resp_send(req, html_settings, HTTPD_RESP_USE_STRLEN);
/* inject the physical-presence flag in front of the page script */
const char *sp = strstr(html_settings, "<script>");
if (!sp) return httpd_resp_send(req, html_settings, HTTPD_RESP_USE_STRLEN);
httpd_resp_send_chunk(req, html_settings, sp - html_settings);
httpd_resp_send_chunk(req, s_physical ? "<script>var PHYS=1;" : "<script>var PHYS=0;",
HTTPD_RESP_USE_STRLEN);
httpd_resp_send_chunk(req, sp + strlen("<script>"), HTTPD_RESP_USE_STRLEN);
return httpd_resp_send_chunk(req, NULL, 0);
}
static esp_err_t save_post_handler(httpd_req_t *req)
{
char body[512];
size_t total = req->content_len;
if (total == 0 || total >= sizeof(body)) {
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "bad length");
return ESP_FAIL;
if (!s_physical && s_auth_fail >= MAX_AUTH_FAILS)
return send_text(req, "429 Too Many Requests", MSG_LOCKED);
char body[768];
if (!read_body(req, body, sizeof(body)))
return send_text(req, "400 Bad Request", MSG_BAD_REQ);
/* decoded text is never longer than its encoded form, so the buffers have equal sizes */
char e_ssid[128] = {0}, e_pass[256] = {0}, e_wu[128] = {0}, e_wp[192] = {0};
char ssid[128], pass[256], wu[128], wp[192];
httpd_query_key_value(body, "ssid", e_ssid, sizeof(e_ssid));
httpd_query_key_value(body, "pass", e_pass, sizeof(e_pass));
httpd_query_key_value(body, "wu", e_wu, sizeof(e_wu));
httpd_query_key_value(body, "wp", e_wp, sizeof(e_wp));
url_decode(ssid, e_ssid);
url_decode(pass, e_pass);
url_decode(wu, e_wu);
url_decode(wp, e_wp);
/* The Wi-Fi card is open only with physical presence or a valid login */
if (!s_physical && !cam_auth_verify(wu, wp)) {
s_auth_fail++;
ESP_LOGW(TAG, "Wrong login on Wi-Fi save (%d/%d)", s_auth_fail, MAX_AUTH_FAILS);
vTaskDelay(pdMS_TO_TICKS(1000)); /* slows down guessing */
return send_text(req, "403 Forbidden", MSG_BAD_LOGIN);
}
size_t got = 0;
while (got < total) {
int r = httpd_req_recv(req, body + got, total - got);
if (r == HTTPD_SOCK_ERR_TIMEOUT) continue;
if (r <= 0) return ESP_FAIL;
got += r;
}
body[got] = '\0';
char ssid_enc[128] = {0}, pass_enc[256] = {0};
char ssid[33] = {0}, pass[65] = {0};
httpd_query_key_value(body, "ssid", ssid_enc, sizeof(ssid_enc));
httpd_query_key_value(body, "pass", pass_enc, sizeof(pass_enc));
url_decode(ssid, ssid_enc);
url_decode(pass, pass_enc);
size_t sl = strlen(ssid), pl = strlen(pass);
if (sl == 0 || sl > 32 || (pl != 0 && (pl < 8 || pl > 63))) {
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "invalid credentials");
return ESP_FAIL;
}
if (sl == 0 || sl > 32 || (pl != 0 && (pl < 8 || pl > 63)))
return send_text(req, "400 Bad Request",
"نام شبکه یا رمز عبور نامعتبر است (رمز ۸ تا ۶۳ حرف).");
ESP_LOGI(TAG, "Saving SSID: %s", ssid);
nvs_handle_t h;
if (nvs_open(WIFI_NS, NVS_READWRITE, &h) != ESP_OK) {
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "nvs error");
return ESP_FAIL;
}
if (nvs_open(WIFI_NS, NVS_READWRITE, &h) != ESP_OK)
return send_text(req, "500 Internal Server Error", MSG_STORE_ERR);
nvs_set_str(h, WIFI_SSID_KEY, ssid);
nvs_set_str(h, WIFI_PASS_KEY, pass);
nvs_commit(h);
nvs_close(h);
rtc_hint_valid = false;
rtc_force_portal = false;
httpd_resp_send(req, "OK", HTTPD_RESP_USE_STRLEN);
send_text(req, "200 OK", "OK");
vTaskDelay(pdMS_TO_TICKS(800));
esp_restart();
return ESP_OK;
}
static esp_err_t auth_post_handler(httpd_req_t *req)
{
if (!s_physical && s_auth_fail >= MAX_AUTH_FAILS)
return send_text(req, "429 Too Many Requests", MSG_LOCKED);
char body[768];
if (!read_body(req, body, sizeof(body)))
return send_text(req, "400 Bad Request", MSG_BAD_REQ);
char e_ou[128] = {0}, e_op[192] = {0}, e_nu[128] = {0}, e_np[192] = {0};
char ou[128], op[192], nu[128], np[192];
httpd_query_key_value(body, "ou", e_ou, sizeof(e_ou));
httpd_query_key_value(body, "op", e_op, sizeof(e_op));
httpd_query_key_value(body, "nu", e_nu, sizeof(e_nu));
httpd_query_key_value(body, "np", e_np, sizeof(e_np));
url_decode(ou, e_ou);
url_decode(op, e_op);
url_decode(nu, e_nu);
url_decode(np, e_np);
/* BOOT-button portal: no current login needed */
cam_auth_result_t res = s_physical ? cam_auth_set(nu, np)
: cam_auth_change(ou, op, nu, np);
switch (res) {
case CAM_AUTH_OK:
send_text(req, "200 OK", "OK");
vTaskDelay(pdMS_TO_TICKS(800));
esp_restart();
return ESP_OK;
case CAM_AUTH_BAD_CURRENT:
s_auth_fail++;
ESP_LOGW(TAG, "Wrong current login in change request (%d/%d)", s_auth_fail, MAX_AUTH_FAILS);
vTaskDelay(pdMS_TO_TICKS(1000)); /* slows down guessing */
return send_text(req, "403 Forbidden", MSG_BAD_LOGIN);
case CAM_AUTH_BAD_NEW:
return send_text(req, "400 Bad Request",
"نام کاربری جدید (۳ تا ۳۱ حرف انگلیسی، عدد یا . _ -) یا رمز جدید "
"(۸ تا ۳۲ حرف انگلیسی و عدد) معتبر نیست.");
default:
return send_text(req, "500 Internal Server Error", MSG_STORE_ERR);
}
}
/* Every unknown URL (Android generate_204, Apple hotspot-detect, Windows
* connecttest, ...) is redirected to the setup page. This is what makes the
* phone/PC pop up the "sign in to network" screen. */
@@ -222,7 +391,7 @@ static void start_portal_webserver(void)
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.server_port = 80;
config.stack_size = 8192;
config.lru_purge_enable = true;
config.lru_purge_enable = true; /* phones open many short connections */
if (httpd_start(&s_portal_server, &config) != ESP_OK) {
ESP_LOGE(TAG, "Portal HTTP server failed to start");
@@ -232,8 +401,10 @@ static void start_portal_webserver(void)
httpd_uri_t root = { .uri = "/", .method = HTTP_GET, .handler = root_get_handler };
httpd_uri_t save = { .uri = "/save", .method = HTTP_POST, .handler = save_post_handler };
httpd_uri_t auth = { .uri = "/auth", .method = HTTP_POST, .handler = auth_post_handler };
httpd_register_uri_handler(s_portal_server, &root);
httpd_register_uri_handler(s_portal_server, &save);
httpd_register_uri_handler(s_portal_server, &auth);
httpd_register_err_handler(s_portal_server, HTTPD_404_NOT_FOUND, redirect_404_handler);
ESP_LOGI(TAG, "Portal HTTP server started on port 80");
@@ -356,11 +527,13 @@ static void start_provisioning_mode(void)
xTaskCreate(dns_server_task, "dns_server", 4096, NULL, 3, NULL);
start_portal_webserver();
s_prov_timer = xTimerCreate("prov_timeout", pdMS_TO_TICKS(PROV_TIMEOUT_SEC * 1000),
uint32_t secs = s_physical ? PROV_TIMEOUT_PHYS_SEC : PROV_TIMEOUT_SEC;
s_prov_timer = xTimerCreate("prov_timeout", pdMS_TO_TICKS(secs * 1000),
pdFALSE, NULL, prov_timeout_callback);
if (s_prov_timer) xTimerStart(s_prov_timer, 0);
ESP_LOGI(TAG, "Portal ready: join \"%s\" and open http://%s/", AP_SSID, AP_IP_STR);
ESP_LOGI(TAG, "Portal ready (physical=%d, %u s): join \"%s\" and open http://%s/",
s_physical, (unsigned)secs, AP_SSID, AP_IP_STR);
}
/* ------------------------------------------------------------------ */
@@ -391,6 +564,34 @@ static void start_station_mode(const char *ssid, const char *pass)
/* ------------------------------------------------------------------ */
/* Events */
/* ------------------------------------------------------------------ */
#define PORTAL_NS "portal"
#define PORTAL_KEY "mode" /* 1 = portal, login required; 2 = portal opened by BOOT */
static void portal_flag_set(uint8_t mode)
{
nvs_handle_t h;
if (nvs_open(PORTAL_NS, NVS_READWRITE, &h) == ESP_OK) {
nvs_set_u8(h, PORTAL_KEY, mode);
nvs_commit(h);
nvs_close(h);
}
}
static uint8_t portal_flag_take(void) /* read and erase: one-shot */
{
nvs_handle_t h;
uint8_t v = 0;
if (nvs_open(PORTAL_NS, NVS_READWRITE, &h) != ESP_OK) return 0;
if (nvs_get_u8(h, PORTAL_KEY, &v) == ESP_OK && v) {
nvs_erase_key(h, PORTAL_KEY);
nvs_commit(h);
} else {
v = 0;
}
nvs_close(h);
return v;
}
static void wifi_event_handler(void *arg, esp_event_base_t base, int32_t id, void *data)
{
if (base == WIFI_EVENT && id == WIFI_EVENT_STA_START) {
@@ -416,8 +617,9 @@ static void wifi_event_handler(void *arg, esp_event_base_t base, int32_t id, voi
s_retry++;
ESP_LOGW(TAG, "Disconnected, try %d/%d", s_retry, MAX_RECONNECT_TRIES);
if (s_retry > MAX_RECONNECT_TRIES) {
/* The media servers own port 80 by now, so reboot straight into the portal. */
rtc_force_portal = true;
/* The media servers own port 80 by now, so reboot straight into the portal.
* Not a physical request: the portal will ask for the current login. */
portal_flag_set(1);
esp_restart();
} else {
esp_wifi_connect();
@@ -448,6 +650,29 @@ bool wifi_is_provisioning(void)
return s_provisioning;
}
bool wifi_portal_is_physical(void)
{
return s_physical;
}
/* Reboots into the setup portal WITHOUT asking for the current login.
* Call only from the BOOT-button handler (physical access). */
void wifi_request_portal(void)
{
ESP_LOGW(TAG, "Portal requested (login required)");
portal_flag_set(1);
vTaskDelay(pdMS_TO_TICKS(100));
esp_restart();
}
void wifi_request_portal_physical(void)
{
ESP_LOGW(TAG, "Portal requested by BOOT button");
portal_flag_set(2);
vTaskDelay(pdMS_TO_TICKS(100));
esp_restart();
}
void wifi_start_provisioning_if_needed(void)
{
/* NVS must be ready before the Wi-Fi driver starts */
@@ -473,10 +698,13 @@ void wifi_start_provisioning_if_needed(void)
ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL));
/* Previous run gave up reconnecting: show the portal so credentials can be fixed */
if (rtc_force_portal) {
rtc_force_portal = false;
ESP_LOGW(TAG, "Previous boot failed to connect, opening portal");
/* A portal was requested (failed reconnects, HA, or the BOOT button) */
ESP_LOGI(TAG, "Reset reason: %d", (int)esp_reset_reason());
uint8_t pm = portal_flag_take();
if (pm) {
s_physical = (pm == 2);
ESP_LOGW(TAG, "Opening portal (physical=%d)", s_physical);
start_provisioning_mode();
return;
}
@@ -504,4 +732,5 @@ void wifi_start_provisioning_if_needed(void)
nvs_close(h);
start_station_mode(ssid, pass);
}
}