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:
Vendored
+1
-1
@@ -11,5 +11,5 @@
|
|||||||
"--compile-commands-dir=d:\\ViraTak\\Projects\\Hodor_Firmeware\\esp32-camera-master\\examples\\camera_example\\build"
|
"--compile-commands-dir=d:\\ViraTak\\Projects\\Hodor_Firmeware\\esp32-camera-master\\examples\\camera_example\\build"
|
||||||
],
|
],
|
||||||
"idf.flashType": "UART",
|
"idf.flashType": "UART",
|
||||||
"idf.portWin": "COM8"
|
"idf.port": "COM4"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
# ESP32-S3-CAM Door Intercom
|
||||||
|
|
||||||
|
A door-opener / intercom device used mainly from Home Assistant, as close to real time as possible.
|
||||||
|
Video (MJPEG) and two-way audio over HTTP and RTSP, with a captive-portal setup page.
|
||||||
|
|
||||||
|
## Project briefing
|
||||||
|
|
||||||
|
### Hardware
|
||||||
|
|
||||||
|
- Waveshare ESP32-S3-CAM
|
||||||
|
- Camera: GC2145 (YUV422 -> `frame2jpg()` -> JPEG -> MJPEG)
|
||||||
|
- Speaker codec: ES8311 (I2C 0x18)
|
||||||
|
- Mic ADC: ES7210 (I2C 0x40)
|
||||||
|
- CH32V003 IO expander on the same I2C bus (SDA 8, SCL 7)
|
||||||
|
- Speaker amp enable: `PA_CTRL` = EXIO_4 (bit 3 vs bit 4 not yet confirmed)
|
||||||
|
- I2S: MCLK 10, BCLK 11, WS 12, DOUT 14, DIN 13, 16 kHz / 16-bit
|
||||||
|
- BOOT button: GPIO0 (not used by anything else on the board, checked on the schematic)
|
||||||
|
|
||||||
|
### Software
|
||||||
|
|
||||||
|
- ESP-IDF 5.x (built with v5.5.3), `esp_codec_dev` 1.6.2 (local component)
|
||||||
|
- Project: `D:\ViraTak\Projects\Hodor_Firmeware\Hodor` (`main/main.c`)
|
||||||
|
|
||||||
|
### Source files
|
||||||
|
|
||||||
|
| File | Role |
|
||||||
|
|---|---|
|
||||||
|
| `main.c` | Camera, `audio_init()` (full-duplex I2S), `play_task` fed by `s_play_sb`, `mic_task` feeding HTTP `/mic` and RTSP. HTTP servers: `:80` `/pic` `/stream` `/setup` (POST), `:81` `/mic` (WAV stream), `:82` `/spk` (POST) `/vol`. No WebSocket. |
|
||||||
|
| `wifi.c` | Station mode + captive portal (AP `ESP32_Setup`, DNS hijack, setup page with a Wi-Fi card and a "change login" card). Opens the portal after 30 failed reconnects or on request. |
|
||||||
|
| `button.c` | BOOT long-press handler, opens the portal in "physical presence" mode (see below). |
|
||||||
|
| `cam_stream.c/.h` | One shared JPEG producer for `/pic`, `/stream` and RTSP. RTSP server on `:554`, TCP-interleaved only, max 2 sessions. `track0` = MJPEG (RTP/JPEG), `track1` = mic audio (G.711 PCMA by default; `RTSP_AUDIO_FORMAT` also allows PCMU or L16 16 kHz), `track2` = ONVIF-style back channel (offered only if the client sends `Require: www.onvif.org/ver20/backchannel`; G.711 from the client plays on the speaker through `rtsp_set_speaker_sink()`). |
|
||||||
|
| `cam_auth.c/.h` | RTSP Digest (own MD5, no qop) and HTTP Basic or `?key=<password>`. Login stored in NVS as user + MD5 hash. Defaults come from `CAM_USER`/`CAM_PASS`. |
|
||||||
|
| `video.html` / `audio.html` | Pass the password as `?key=`. |
|
||||||
|
|
||||||
|
### Decisions
|
||||||
|
|
||||||
|
- IP-address filtering was dropped.
|
||||||
|
- Muting the mic while the speaker plays was rejected.
|
||||||
|
- Home Assistant route: its ONVIF integration needs H.264 and its stream pipeline does not take MJPEG/G.711, so use go2rtc
|
||||||
|
(`rtsp://user:pass@IP:554/mjpeg/1` plus an `ffmpeg:...#video=h264` source) with the WebRTC Camera card
|
||||||
|
(`media: video,audio,microphone`; HTTPS needed for the mic).
|
||||||
|
|
||||||
|
## Setup portal and the BOOT button
|
||||||
|
|
||||||
|
### Opening the portal
|
||||||
|
|
||||||
|
| How | Wi-Fi card | Login card |
|
||||||
|
|---|---|---|
|
||||||
|
| Hold BOOT for 3 s while running | open, no login asked | open, no current login asked |
|
||||||
|
| 30 failed reconnects, or `wifi_request_portal()` | needs current login | needs current login |
|
||||||
|
|
||||||
|
Join the open AP `ESP32_Setup` and open `http://192.168.4.1/` (most phones pop it up automatically).
|
||||||
|
|
||||||
|
### How it works
|
||||||
|
|
||||||
|
- A long press stores a one-shot flag in NVS (namespace `portal`) and restarts. NVS is used because an RTC-memory flag was lost across the reset on this board.
|
||||||
|
- At boot the flag is read and erased, and `s_physical` is set for that portal session only. A power cycle is a normal boot.
|
||||||
|
- With physical presence the page hides the "current login" fields and shows a green banner.
|
||||||
|
- 5 wrong logins lock `/save` and `/auth` until restart (not applied in the physical case). Failed attempts are delayed 1 s.
|
||||||
|
- Portal timeouts: 180 s when opened by the button, 300 s otherwise. The device then restarts.
|
||||||
|
- GPIO0 is a strapping pin. A press held from boot is ignored by the task, so download-mode entry is unaffected.
|
||||||
|
|
||||||
|
### Requirements
|
||||||
|
|
||||||
|
- `cam_auth_load()` must run **before** `wifi_start_provisioning_if_needed()`. Otherwise `cam_auth_verify()` treats auth as disabled and accepts any login.
|
||||||
|
- `audio_init()` must be enabled in `app_main`. With it commented out, mic and speaker are silent.
|
||||||
|
- `button_start()` is called right after `wifi_start_provisioning_if_needed()`, only when not provisioning, so the button also works while the device keeps retrying an unreachable network.
|
||||||
|
|
||||||
|
### app_main order
|
||||||
|
|
||||||
|
```c
|
||||||
|
bsp_i2c_init();
|
||||||
|
bsp_io_expander_init();
|
||||||
|
init_camera();
|
||||||
|
audio_init(bsp_i2c_get_handle());
|
||||||
|
cam_auth_load(CAM_USER, CAM_PASS);
|
||||||
|
cam_feed_start();
|
||||||
|
wifi_start_provisioning_if_needed();
|
||||||
|
if (!wifi_is_provisioning()) button_start();
|
||||||
|
while (!wifi_wait_connected(5000)) { /* portal mode never leaves this loop */ }
|
||||||
|
start_camera_server(); // :80
|
||||||
|
xTaskCreate(mic_task, ...);
|
||||||
|
start_audio_server(); // :81, :82
|
||||||
|
rtsp_set_speaker_sink(rtsp_speaker_sink);
|
||||||
|
rtsp_server_start();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
**Working on the board**
|
||||||
|
- Compiles and runs on ESP-IDF 5.5.3; camera, Wi-Fi station, RTSP server start.
|
||||||
|
- Mic over RTSP.
|
||||||
|
- Mic and speaker once `audio_init()` is enabled.
|
||||||
|
- BOOT long press reboots into the `ESP32_Setup` portal instead of reconnecting to the stored network.
|
||||||
|
|
||||||
|
**Not yet tested on the board**
|
||||||
|
- The back channel with go2rtc (`a=sendonly` direction is unverified).
|
||||||
|
- Wi-Fi card login gating, lockout, 180 s timeout, portal page rendering on a phone.
|
||||||
|
- Digest/Basic auth against real clients (verified on a PC only: G.711 conversions, MD5/Digest, auth logic).
|
||||||
|
|
||||||
|
**Known behaviour**
|
||||||
|
- About 1 s delay in audio and video in the Home Assistant path, attributed to go2rtc's ffmpeg MJPEG-to-H.264 transcode (about 0.5 to 1 s with default x264 settings).
|
||||||
|
- Earlier KMPlayer playback showed about 2 s, probably player buffering. KMPlayer cannot send audio, so the speaker only works via `audio.html` (`/spk`) or the go2rtc back channel.
|
||||||
|
|
||||||
|
## Latency notes
|
||||||
|
|
||||||
|
Compare in this order to find the slow stage:
|
||||||
|
1. Browser: `/stream` and `audio.html` directly (almost no client buffering).
|
||||||
|
2. `ffplay -fflags nobuffer -flags low_delay -probesize 32 -analyzeduration 0 -rtsp_transport tcp rtsp://USER:PASS@IP:554/mjpeg/1`
|
||||||
|
3. go2rtc / Home Assistant.
|
||||||
|
|
||||||
|
If the device itself is slow, check: camera `fb_count = 2` with `CAMERA_GRAB_LATEST`, JPEG encode time at 640x480, I2S DMA size (aim for ~20 ms chunks), mic packet size (20 ms), `TCP_NODELAY` on RTSP/HTTP sockets, and the speaker stream-buffer trigger level.
|
||||||
|
For go2rtc: use a low-latency x264 setup (`ultrafast` preset, `-tune zerolatency`), or hardware encoding if available.
|
||||||
|
|
||||||
|
## Open ideas
|
||||||
|
|
||||||
|
- Confirm the `PA_CTRL` bit (EXIO_4 bit 3 vs 4)
|
||||||
|
- Raise the default speaker volume (~85)
|
||||||
|
- Test go2rtc two-way audio
|
||||||
|
- Beep through the speaker at the 3 s mark of the BOOT hold
|
||||||
|
- Echo cancellation (esp-sr)
|
||||||
|
- HTTPS
|
||||||
|
- `RTSP_MAX_SESSIONS` 3 and `CONFIG_LWIP_MAX_SOCKETS` 16
|
||||||
|
|
||||||
|
Done: lock the portal's Wi-Fi card behind the login; hardware reset button for a forgotten login (BOOT hold).
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
Never commit passwords. `CAM_USER`/`CAM_PASS` are only the built-in defaults; change the login on the setup page.
|
||||||
File diff suppressed because one or more lines are too long
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"version": "1.2",
|
"version": "1.2",
|
||||||
"project_name": "camera_example",
|
"project_name": "camera_example",
|
||||||
"project_version": "58715ec-dirty",
|
"project_version": "72a2d71-dirty",
|
||||||
"project_path": "D:/ViraTak/Projects/Hodor_Firmeware/Hodor",
|
"project_path": "D:/ViraTak/Projects/Hodor_Firmeware/Hodor",
|
||||||
"idf_path": "C:/Espressif/frameworks/esp-idf-v5.5.3",
|
"idf_path": "C:/Espressif/frameworks/esp-idf-v5.5.3",
|
||||||
"build_dir": "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/build",
|
"build_dir": "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/build",
|
||||||
@@ -1310,12 +1310,12 @@
|
|||||||
"dir": "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main",
|
"dir": "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main",
|
||||||
"type": "LIBRARY",
|
"type": "LIBRARY",
|
||||||
"lib": "__idf_main",
|
"lib": "__idf_main",
|
||||||
"reqs": [ "nvs_flash", "esp32-camera", "esp_io_expander", "custom_io_expander_ch32v003", "esp_jpeg" ],
|
"reqs": [ "nvs_flash", "esp32-camera", "esp_io_expander", "custom_io_expander_ch32v003", "esp_jpeg", "esp_http_server", "esp_timer", "lwip" ],
|
||||||
"priv_reqs": [ "espressif__esp_codec_dev" ],
|
"priv_reqs": [ "espressif__esp_codec_dev" ],
|
||||||
"managed_reqs": [],
|
"managed_reqs": [],
|
||||||
"managed_priv_reqs": [ "espressif__esp_codec_dev" ],
|
"managed_priv_reqs": [ "espressif__esp_codec_dev" ],
|
||||||
"file": "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/build/esp-idf/main/libmain.a",
|
"file": "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/build/esp-idf/main/libmain.a",
|
||||||
"sources": [ "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main/main.c", "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main/esp32_s3_cam_ovxxxx.c", "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main/camera.c", "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main/audio.c", "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main/wifi.c" ],
|
"sources": [ "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main/main.c", "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main/esp32_s3_cam_ovxxxx.c", "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main/camera.c", "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main/audio.c", "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main/wifi.c", "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main/cam_stream.c", "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main/cam_auth.c", "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main/button.c" ],
|
||||||
"include_dirs": []
|
"include_dirs": []
|
||||||
},
|
},
|
||||||
"mbedtls": {
|
"mbedtls": {
|
||||||
@@ -3024,7 +3024,7 @@
|
|||||||
"prefix": "idf",
|
"prefix": "idf",
|
||||||
"dir": "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main",
|
"dir": "D:/ViraTak/Projects/Hodor_Firmeware/Hodor/main",
|
||||||
"lib": "__idf_main",
|
"lib": "__idf_main",
|
||||||
"reqs": [ "nvs_flash", "esp32-camera", "esp_io_expander", "custom_io_expander_ch32v003", "esp_jpeg" ],
|
"reqs": [ "nvs_flash", "esp32-camera", "esp_io_expander", "custom_io_expander_ch32v003", "esp_jpeg", "esp_http_server", "esp_timer", "lwip" ],
|
||||||
"priv_reqs": [ "espressif__esp_codec_dev" ],
|
"priv_reqs": [ "espressif__esp_codec_dev" ],
|
||||||
"managed_reqs": [],
|
"managed_reqs": [],
|
||||||
"managed_priv_reqs": [ "espressif__esp_codec_dev" ],
|
"managed_priv_reqs": [ "espressif__esp_codec_dev" ],
|
||||||
|
|||||||
+1
-1
@@ -1,3 +1,3 @@
|
|||||||
idf_component_register(SRCS "main.c" "esp32_s3_cam_ovxxxx.c" "camera.c" "audio.c" "wifi.c" "cam_stream.c" "cam_auth.c"
|
idf_component_register(SRCS "main.c" "esp32_s3_cam_ovxxxx.c" "camera.c" "audio.c" "wifi.c" "cam_stream.c" "cam_auth.c" "button.c"
|
||||||
PRIV_INCLUDE_DIRS .
|
PRIV_INCLUDE_DIRS .
|
||||||
REQUIRES nvs_flash esp32-camera esp_io_expander custom_io_expander_ch32v003 esp_jpeg esp_http_server esp_timer lwip)
|
REQUIRES nvs_flash esp32-camera esp_io_expander custom_io_expander_ch32v003 esp_jpeg esp_http_server esp_timer lwip)
|
||||||
@@ -27,5 +27,8 @@ void start_wifi_and_server(void);
|
|||||||
void start_audio_server(void);
|
void start_audio_server(void);
|
||||||
void start_camera_server(void);
|
void start_camera_server(void);
|
||||||
void wifi_start_provisioning_if_needed(void);
|
void wifi_start_provisioning_if_needed(void);
|
||||||
|
bool wifi_is_provisioning(void);
|
||||||
bool wifi_wait_connected(uint32_t timeout_ms);
|
bool wifi_wait_connected(uint32_t timeout_ms);
|
||||||
void rtsp_speaker_sink(const int16_t *pcm, size_t samples);
|
void rtsp_speaker_sink(const int16_t *pcm, size_t samples);
|
||||||
|
void wifi_request_portal_physical(void);
|
||||||
|
void button_start(void);
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
#include "driver/gpio.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "board.h"
|
||||||
|
|
||||||
|
#define BTN_GPIO GPIO_NUM_0
|
||||||
|
#define BTN_HOLD_MS 10000
|
||||||
|
|
||||||
|
extern void wifi_request_portal_physical(void);
|
||||||
|
|
||||||
|
static void button_task(void *arg)
|
||||||
|
{
|
||||||
|
gpio_config_t io = {
|
||||||
|
.pin_bit_mask = 1ULL << BTN_GPIO,
|
||||||
|
.mode = GPIO_MODE_INPUT,
|
||||||
|
.pull_up_en = GPIO_PULLUP_ENABLE,
|
||||||
|
};
|
||||||
|
|
||||||
|
gpio_config(&io);
|
||||||
|
|
||||||
|
/* ignore a button still held from boot */
|
||||||
|
while (gpio_get_level(BTN_GPIO) == 0) vTaskDelay(pdMS_TO_TICKS(50));
|
||||||
|
|
||||||
|
int held = 0;
|
||||||
|
for (;;) {
|
||||||
|
if (gpio_get_level(BTN_GPIO) == 0) {
|
||||||
|
held += 50;
|
||||||
|
if (held >= BTN_HOLD_MS) {
|
||||||
|
ESP_LOGW("button", "long press -> portal");
|
||||||
|
wifi_request_portal_physical(); /* does not return */
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
held = 0;
|
||||||
|
}
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(50));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void button_start(void)
|
||||||
|
{
|
||||||
|
xTaskCreate(button_task, "btn", 3072, NULL, 3, NULL);
|
||||||
|
}
|
||||||
+130
-11
@@ -3,6 +3,17 @@
|
|||||||
* - tiny self-contained MD5 (no mbedTLS dependency, works on every ESP-IDF version)
|
* - tiny self-contained MD5 (no mbedTLS dependency, works on every ESP-IDF version)
|
||||||
* - RTSP Digest authentication (RFC 2069 style, no qop: what ffmpeg, VLC and go2rtc speak)
|
* - RTSP Digest authentication (RFC 2069 style, no qop: what ffmpeg, VLC and go2rtc speak)
|
||||||
* - HTTP check: "Authorization: Basic" header or "?key=" query parameter
|
* - HTTP check: "Authorization: Basic" header or "?key=" query parameter
|
||||||
|
* - login stored in NVS as user name + MD5 hash (no plain password in flash),
|
||||||
|
* changeable at runtime:
|
||||||
|
* cam_auth_change() after verifying the current login
|
||||||
|
* cam_auth_set() WITHOUT verifying it (only for the BOOT-button portal, where
|
||||||
|
* physical access to the device is the proof)
|
||||||
|
*
|
||||||
|
* cam_auth.h must declare (add the last one):
|
||||||
|
* bool cam_auth_verify(const char *user, const char *pass);
|
||||||
|
* cam_auth_result_t cam_auth_change(const char *old_user, const char *old_pass,
|
||||||
|
* const char *new_user, const char *new_pass);
|
||||||
|
* cam_auth_result_t cam_auth_set(const char *new_user, const char *new_pass);
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
@@ -13,14 +24,17 @@
|
|||||||
#include "freertos/task.h"
|
#include "freertos/task.h"
|
||||||
#include "esp_log.h"
|
#include "esp_log.h"
|
||||||
#include "esp_random.h"
|
#include "esp_random.h"
|
||||||
|
#include "nvs_flash.h"
|
||||||
|
#include "nvs.h"
|
||||||
#include "cam_auth.h"
|
#include "cam_auth.h"
|
||||||
|
|
||||||
static const char *TAG = "AUTH";
|
static const char *TAG = "AUTH";
|
||||||
|
|
||||||
static bool s_enabled = false;
|
static bool s_enabled = false;
|
||||||
static char s_user[48];
|
static char s_user[48];
|
||||||
static char s_pass[64];
|
static char s_ha1[33]; /* md5(user:realm:pass); the password itself is never kept */
|
||||||
static char s_ha1[33]; /* md5(user:realm:pass), computed once */
|
|
||||||
|
#define AUTH_NS "cam_auth" /* NVS namespace: keys "user" and "ha1" */
|
||||||
|
|
||||||
/* ================================================================== */
|
/* ================================================================== */
|
||||||
/* MD5 (RFC 1321) */
|
/* MD5 (RFC 1321) */
|
||||||
@@ -177,6 +191,13 @@ static size_t b64_decode(const char *in, uint8_t *out, size_t outmax)
|
|||||||
/* ================================================================== */
|
/* ================================================================== */
|
||||||
/* Public API */
|
/* Public API */
|
||||||
/* ================================================================== */
|
/* ================================================================== */
|
||||||
|
static void make_ha1(const char *user, const char *pass, char out[33])
|
||||||
|
{
|
||||||
|
char tmp[200];
|
||||||
|
snprintf(tmp, sizeof(tmp), "%s:%s:%s", user, CAM_AUTH_REALM, pass);
|
||||||
|
md5_hex(tmp, out);
|
||||||
|
}
|
||||||
|
|
||||||
void cam_auth_init(const char *user, const char *pass)
|
void cam_auth_init(const char *user, const char *pass)
|
||||||
{
|
{
|
||||||
s_enabled = (user && *user);
|
s_enabled = (user && *user);
|
||||||
@@ -185,11 +206,7 @@ void cam_auth_init(const char *user, const char *pass)
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
snprintf(s_user, sizeof(s_user), "%s", user);
|
snprintf(s_user, sizeof(s_user), "%s", user);
|
||||||
snprintf(s_pass, sizeof(s_pass), "%s", pass ? pass : "");
|
make_ha1(s_user, pass ? pass : "", s_ha1);
|
||||||
|
|
||||||
char tmp[160];
|
|
||||||
snprintf(tmp, sizeof(tmp), "%s:%s:%s", s_user, CAM_AUTH_REALM, s_pass);
|
|
||||||
md5_hex(tmp, s_ha1);
|
|
||||||
ESP_LOGI(TAG, "Authentication enabled for user \"%s\"", s_user);
|
ESP_LOGI(TAG, "Authentication enabled for user \"%s\"", s_user);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,6 +215,106 @@ bool cam_auth_enabled(void)
|
|||||||
return s_enabled;
|
return s_enabled;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool cam_auth_verify(const char *user, const char *pass)
|
||||||
|
{
|
||||||
|
if (!s_enabled) return true;
|
||||||
|
if (!user || !pass) return false;
|
||||||
|
char ha1[33];
|
||||||
|
make_ha1(user, pass, ha1);
|
||||||
|
bool u_ok = ct_eq(user, s_user); /* evaluate both: no early exit */
|
||||||
|
bool p_ok = ct_eq(ha1, s_ha1);
|
||||||
|
return u_ok && p_ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- Stored login (NVS) ---------------- */
|
||||||
|
static bool valid_user(const char *u) /* 3-31 chars: letters, digits . _ - */
|
||||||
|
{
|
||||||
|
size_t n = strlen(u);
|
||||||
|
if (n < 3 || n > 31) return false;
|
||||||
|
for (size_t i = 0; i < n; i++) {
|
||||||
|
char c = u[i];
|
||||||
|
bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||||
|
c == '.' || c == '_' || c == '-';
|
||||||
|
if (!ok) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool valid_pass(const char *p) /* 8-32 chars: letters and digits */
|
||||||
|
{
|
||||||
|
size_t n = strlen(p);
|
||||||
|
if (n < 8 || n > 32) return false;
|
||||||
|
for (size_t i = 0; i < n; i++) {
|
||||||
|
char c = p[i];
|
||||||
|
bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
|
||||||
|
if (!ok) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool store_save(const char *user, const char *ha1)
|
||||||
|
{
|
||||||
|
nvs_handle_t h;
|
||||||
|
if (nvs_open(AUTH_NS, NVS_READWRITE, &h) != ESP_OK) return false;
|
||||||
|
bool ok = nvs_set_str(h, "user", user) == ESP_OK &&
|
||||||
|
nvs_set_str(h, "ha1", ha1) == ESP_OK &&
|
||||||
|
nvs_commit(h) == ESP_OK;
|
||||||
|
nvs_close(h);
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
void cam_auth_load(const char *default_user, const char *default_pass)
|
||||||
|
{
|
||||||
|
esp_err_t e = nvs_flash_init(); /* harmless if already initialised */
|
||||||
|
if (e == ESP_ERR_NVS_NO_FREE_PAGES || e == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||||
|
nvs_flash_erase();
|
||||||
|
nvs_flash_init();
|
||||||
|
}
|
||||||
|
|
||||||
|
nvs_handle_t h;
|
||||||
|
if (nvs_open(AUTH_NS, NVS_READONLY, &h) == ESP_OK) {
|
||||||
|
char u[48] = {0}, ha[33] = {0};
|
||||||
|
size_t ul = sizeof(u), hl = sizeof(ha);
|
||||||
|
bool ok = nvs_get_str(h, "user", u, &ul) == ESP_OK &&
|
||||||
|
nvs_get_str(h, "ha1", ha, &hl) == ESP_OK &&
|
||||||
|
u[0] != 0 && strlen(ha) == 32;
|
||||||
|
nvs_close(h);
|
||||||
|
if (ok) {
|
||||||
|
s_enabled = true;
|
||||||
|
snprintf(s_user, sizeof(s_user), "%s", u);
|
||||||
|
memcpy(s_ha1, ha, sizeof(s_ha1));
|
||||||
|
ESP_LOGI(TAG, "Loaded stored login for user \"%s\"", s_user);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cam_auth_init(default_user, default_pass);
|
||||||
|
ESP_LOGW(TAG, "Using the built-in default login: change it on the setup page");
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Validates the new login, stores it and makes it active. No check of the current login. */
|
||||||
|
cam_auth_result_t cam_auth_set(const char *new_user, const char *new_pass)
|
||||||
|
{
|
||||||
|
if (!new_user || !new_pass || !valid_user(new_user) || !valid_pass(new_pass))
|
||||||
|
return CAM_AUTH_BAD_NEW;
|
||||||
|
|
||||||
|
char ha1[33];
|
||||||
|
make_ha1(new_user, new_pass, ha1);
|
||||||
|
if (!store_save(new_user, ha1)) return CAM_AUTH_STORE_FAILED;
|
||||||
|
|
||||||
|
s_enabled = true;
|
||||||
|
snprintf(s_user, sizeof(s_user), "%s", new_user);
|
||||||
|
memcpy(s_ha1, ha1, sizeof(s_ha1));
|
||||||
|
ESP_LOGI(TAG, "Login changed, new user \"%s\"", s_user);
|
||||||
|
return CAM_AUTH_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
cam_auth_result_t cam_auth_change(const char *old_user, const char *old_pass,
|
||||||
|
const char *new_user, const char *new_pass)
|
||||||
|
{
|
||||||
|
if (!cam_auth_verify(old_user, old_pass)) return CAM_AUTH_BAD_CURRENT;
|
||||||
|
return cam_auth_set(new_user, new_pass);
|
||||||
|
}
|
||||||
|
|
||||||
/* ---------------- HTTP ---------------- */
|
/* ---------------- HTTP ---------------- */
|
||||||
bool cam_http_check(httpd_req_t *req)
|
bool cam_http_check(httpd_req_t *req)
|
||||||
{
|
{
|
||||||
@@ -215,9 +332,11 @@ bool cam_http_check(httpd_req_t *req)
|
|||||||
size_t dl = b64_decode(h + 6, dec, sizeof(dec) - 1);
|
size_t dl = b64_decode(h + 6, dec, sizeof(dec) - 1);
|
||||||
if (dl > 0) {
|
if (dl > 0) {
|
||||||
dec[dl] = 0;
|
dec[dl] = 0;
|
||||||
char want[120];
|
char *colon = strchr((char *)dec, ':');
|
||||||
snprintf(want, sizeof(want), "%s:%s", s_user, s_pass);
|
if (colon) {
|
||||||
ok = ct_eq((const char *)dec, want);
|
*colon = 0;
|
||||||
|
ok = cam_auth_verify((const char *)dec, colon + 1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -227,7 +346,7 @@ bool cam_http_check(httpd_req_t *req)
|
|||||||
char q[160], v[80];
|
char q[160], v[80];
|
||||||
if (httpd_req_get_url_query_str(req, q, sizeof(q)) == ESP_OK &&
|
if (httpd_req_get_url_query_str(req, q, sizeof(q)) == ESP_OK &&
|
||||||
httpd_query_key_value(q, "key", v, sizeof(v)) == ESP_OK) {
|
httpd_query_key_value(q, "key", v, sizeof(v)) == ESP_OK) {
|
||||||
ok = ct_eq(v, s_pass);
|
ok = cam_auth_verify(s_user, v);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,27 @@
|
|||||||
|
|
||||||
#define CAM_AUTH_REALM "ESP32-Cam"
|
#define CAM_AUTH_REALM "ESP32-Cam"
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
CAM_AUTH_OK = 0,
|
||||||
|
CAM_AUTH_BAD_CURRENT, /* current user name / password is wrong */
|
||||||
|
CAM_AUTH_BAD_NEW, /* new user name / password breaks the rules */
|
||||||
|
CAM_AUTH_STORE_FAILED /* could not write to flash */
|
||||||
|
} cam_auth_result_t;
|
||||||
|
|
||||||
|
cam_auth_result_t cam_auth_set(const char *new_user, const char *new_pass);
|
||||||
|
|
||||||
|
/* Call once at boot, before Wi-Fi/portal and servers: loads the login stored in flash,
|
||||||
|
* or uses the given defaults when nothing was stored yet. */
|
||||||
|
void cam_auth_load(const char *default_user, const char *default_pass);
|
||||||
|
|
||||||
|
/* True when user + password match the current login. */
|
||||||
|
bool cam_auth_verify(const char *user, const char *pass);
|
||||||
|
|
||||||
|
/* Changes the login after checking the current one, and stores it in flash.
|
||||||
|
* New user: 3-31 chars (letters, digits . _ -). New password: 8-32 letters/digits. */
|
||||||
|
cam_auth_result_t cam_auth_change(const char *old_user, const char *old_pass,
|
||||||
|
const char *new_user, const char *new_pass);
|
||||||
|
|
||||||
/* Set the single account used by every service (RTSP, /pic, /stream, /mic, /spk, /vol).
|
/* Set the single account used by every service (RTSP, /pic, /stream, /mic, /spk, /vol).
|
||||||
* user NULL or "" disables authentication completely.
|
* user NULL or "" disables authentication completely.
|
||||||
* Use letters and digits only in the password, it also travels inside URLs. */
|
* Use letters and digits only in the password, it also travels inside URLs. */
|
||||||
|
|||||||
@@ -65,10 +65,23 @@ esp_err_t init_camera(void)
|
|||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
esp_err_t setup_handler(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
if (!cam_http_check(req)) return ESP_OK;
|
||||||
|
httpd_resp_set_type(req, "text/plain; charset=utf-8");
|
||||||
|
httpd_resp_send(req, "Rebooting into setup mode. Join the Wi-Fi network ESP32_Setup and open http://192.168.4.1/",
|
||||||
|
HTTPD_RESP_USE_STRLEN);
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(800));
|
||||||
|
wifi_request_portal_physical();
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
void start_camera_server(void)
|
void start_camera_server(void)
|
||||||
{
|
{
|
||||||
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
|
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
|
||||||
httpd_handle_t server = NULL;
|
httpd_handle_t server = NULL;
|
||||||
|
httpd_uri_t uri_setup = { .uri = "/setup", .method = HTTP_POST, .handler = setup_handler };
|
||||||
|
httpd_register_uri_handler(server, &uri_setup);
|
||||||
if (httpd_start(&server, &config) == ESP_OK) {
|
if (httpd_start(&server, &config) == ESP_OK) {
|
||||||
httpd_uri_t uri_capture = { .uri = "/pic", .method = HTTP_GET, .handler = capture_handler };
|
httpd_uri_t uri_capture = { .uri = "/pic", .method = HTTP_GET, .handler = capture_handler };
|
||||||
httpd_uri_t uri_stream = { .uri = "/stream", .method = HTTP_GET, .handler = stream_handler };
|
httpd_uri_t uri_stream = { .uri = "/stream", .method = HTTP_GET, .handler = stream_handler };
|
||||||
|
|||||||
+6
-3
@@ -19,14 +19,17 @@ void app_main(void)
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
ESP_ERROR_CHECK(audio_init(bsp_i2c_get_handle()));
|
ESP_ERROR_CHECK(audio_init(bsp_i2c_get_handle()));
|
||||||
ESP_ERROR_CHECK(cam_feed_start());
|
cam_auth_load(CAM_USER, CAM_PASS);
|
||||||
|
ESP_ERROR_CHECK(cam_feed_start());
|
||||||
wifi_start_provisioning_if_needed(); // station mode, or the captive portal if no credentials
|
wifi_start_provisioning_if_needed(); // station mode, or the captive portal if no credentials
|
||||||
|
|
||||||
|
if (!wifi_is_provisioning()) /* no point in portal mode; the portal has its own timeout */
|
||||||
|
button_start();
|
||||||
|
|
||||||
while (!wifi_wait_connected(5000)) {
|
while (!wifi_wait_connected(5000)) {
|
||||||
ESP_LOGI("Main", "Waiting for Wi-Fi (or setup portal)...");
|
ESP_LOGI("Main", "Waiting for Wi-Fi (or setup portal)...");
|
||||||
}
|
}
|
||||||
|
// cam_auth_init(CAM_USER, CAM_PASS);
|
||||||
cam_auth_init(CAM_USER, CAM_PASS);
|
|
||||||
start_camera_server(); // port 80: /pic, /stream
|
start_camera_server(); // port 80: /pic, /stream
|
||||||
xTaskCreate(mic_task, "mic", 6144, NULL, 5, NULL);
|
xTaskCreate(mic_task, "mic", 6144, NULL, 5, NULL);
|
||||||
start_audio_server(); // ports 81 and 82: /mic, /spk, /vol
|
start_audio_server(); // ports 81 and 82: /mic, /spk, /vol
|
||||||
|
|||||||
+281
-52
@@ -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 <string.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
@@ -15,6 +48,7 @@
|
|||||||
#include "esp_http_server.h"
|
#include "esp_http_server.h"
|
||||||
#include "lwip/sockets.h"
|
#include "lwip/sockets.h"
|
||||||
#include "board.h"
|
#include "board.h"
|
||||||
|
#include "cam_auth.h"
|
||||||
|
|
||||||
/* ---- Fallbacks, used only if board.h does not define them ---- */
|
/* ---- Fallbacks, used only if board.h does not define them ---- */
|
||||||
#ifndef WIFI_NS
|
#ifndef WIFI_NS
|
||||||
@@ -30,12 +64,16 @@
|
|||||||
#define WIFI_CONNECTED_BIT BIT0
|
#define WIFI_CONNECTED_BIT BIT0
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#define PROV_TIMEOUT_SEC 300 /* portal closes and board restarts after this */
|
#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 PROV_TIMEOUT_PHYS_SEC 180 /* shorter window when no login is needed (BOOT button) */
|
||||||
#define AP_SSID "ESP32_Setup"
|
#define MAX_RECONNECT_TRIES 30 /* then the board reboots into the portal */
|
||||||
#define AP_CHANNEL 6
|
#define MAX_AUTH_FAILS 5
|
||||||
#define AP_IP_STR "192.168.4.1"
|
#define AP_SSID "ESP32_Setup"
|
||||||
#define HOSTNAME "hodor-cam"
|
#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";
|
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_sta_netif = NULL;
|
||||||
static esp_netif_t *s_ap_netif = NULL;
|
static esp_netif_t *s_ap_netif = NULL;
|
||||||
static bool s_provisioning = false;
|
static bool s_provisioning = false;
|
||||||
|
static bool s_physical = false; /* portal opened by the BOOT button */
|
||||||
static int s_retry = 0;
|
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 */
|
/* 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;
|
RTC_DATA_ATTR static uint8_t rtc_hint_channel = 0;
|
||||||
|
|
||||||
/* ------------------------------------------------------------------ */
|
/* ------------------------------------------------------------------ */
|
||||||
/* Portal web page */
|
/* Portal web page */
|
||||||
/* ------------------------------------------------------------------ */
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* The page contains exactly one "<script>"; the root handler injects "var PHYS=0/1;" there. */
|
||||||
static const char *html_settings =
|
static const char *html_settings =
|
||||||
"<!DOCTYPE html>"
|
"<!DOCTYPE html>"
|
||||||
"<html lang='fa' dir='rtl'>"
|
"<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'>"
|
"<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
|
||||||
"<title>تنظیمات وایفای</title>"
|
"<title>تنظیمات وایفای</title>"
|
||||||
"<style>"
|
"<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}"
|
".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}"
|
"h1{color:#333;text-align:center;margin-bottom:25px;font-size:22px}"
|
||||||
"label{display:block;margin-bottom:8px;color:#555;font-weight:bold}"
|
"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}"
|
"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}"
|
"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}"
|
".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>"
|
"</style>"
|
||||||
"</head>"
|
"</head>"
|
||||||
"<body>"
|
"<body>"
|
||||||
|
"<div id='phys'>باز شده با کلید روی دستگاه — نیازی به نام کاربری و رمز فعلی نیست.</div>"
|
||||||
"<div class='container'>"
|
"<div class='container'>"
|
||||||
"<h1>⚙️ تنظیمات وایفای</h1>"
|
"<h1>⚙️ تنظیمات وایفای</h1>"
|
||||||
"<form id='wifiForm'>"
|
"<form id='wifiForm'>"
|
||||||
@@ -82,11 +124,39 @@ static const char *html_settings =
|
|||||||
"<input type='text' id='ssid' maxlength='32' required>"
|
"<input type='text' id='ssid' maxlength='32' required>"
|
||||||
"<label>رمز عبور:</label>"
|
"<label>رمز عبور:</label>"
|
||||||
"<input type='password' id='pass' maxlength='63'>"
|
"<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>"
|
"<button type='submit'>ذخیره و اتصال</button>"
|
||||||
"</form>"
|
"</form>"
|
||||||
"<div id='status' class='status'></div>"
|
"<div id='status' class='status'></div>"
|
||||||
"</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>"
|
"<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)=>{"
|
"document.getElementById('wifiForm').addEventListener('submit',async(e)=>{"
|
||||||
"e.preventDefault();"
|
"e.preventDefault();"
|
||||||
"const st=document.getElementById('status');"
|
"const st=document.getElementById('status');"
|
||||||
@@ -94,12 +164,32 @@ static const char *html_settings =
|
|||||||
"const fd=new URLSearchParams();"
|
"const fd=new URLSearchParams();"
|
||||||
"fd.append('ssid',document.getElementById('ssid').value);"
|
"fd.append('ssid',document.getElementById('ssid').value);"
|
||||||
"fd.append('pass',document.getElementById('pass').value);"
|
"fd.append('pass',document.getElementById('pass').value);"
|
||||||
|
"fd.append('wu',document.getElementById('wu').value);"
|
||||||
|
"fd.append('wp',document.getElementById('wp').value);"
|
||||||
"try{"
|
"try{"
|
||||||
"const r=await fetch('/save',{method:'POST',body:fd});"
|
"const r=await fetch('/save',{method:'POST',body:fd});"
|
||||||
"if(r.ok){st.innerHTML='✅ ذخیره شد. دستگاه ریاستارت میشود؛ به وایفای اصلی خود وصل شوید.';}"
|
"if(r.ok){st.innerHTML='✅ ذخیره شد. دستگاه ریاستارت میشود؛ به وایفای اصلی خود وصل شوید.';}"
|
||||||
"else{st.innerHTML='❌ مقادیر نامعتبر است (رمز باید ۸ تا ۶۳ حرف باشد).';}"
|
"else{st.innerHTML='❌ '+await r.text();}"
|
||||||
"}catch(err){st.innerHTML='✅ ذخیره شد. دستگاه ریاستارت میشود.';}"
|
"}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>"
|
"</script>"
|
||||||
"</body>"
|
"</body>"
|
||||||
"</html>";
|
"</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 */
|
/* 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_type(req, "text/html; charset=utf-8");
|
||||||
httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
|
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)
|
static esp_err_t save_post_handler(httpd_req_t *req)
|
||||||
{
|
{
|
||||||
char body[512];
|
if (!s_physical && s_auth_fail >= MAX_AUTH_FAILS)
|
||||||
size_t total = req->content_len;
|
return send_text(req, "429 Too Many Requests", MSG_LOCKED);
|
||||||
if (total == 0 || total >= sizeof(body)) {
|
|
||||||
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "bad length");
|
char body[768];
|
||||||
return ESP_FAIL;
|
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);
|
size_t sl = strlen(ssid), pl = strlen(pass);
|
||||||
if (sl == 0 || sl > 32 || (pl != 0 && (pl < 8 || pl > 63))) {
|
if (sl == 0 || sl > 32 || (pl != 0 && (pl < 8 || pl > 63)))
|
||||||
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "invalid credentials");
|
return send_text(req, "400 Bad Request",
|
||||||
return ESP_FAIL;
|
"نام شبکه یا رمز عبور نامعتبر است (رمز ۸ تا ۶۳ حرف).");
|
||||||
}
|
|
||||||
|
|
||||||
ESP_LOGI(TAG, "Saving SSID: %s", ssid);
|
ESP_LOGI(TAG, "Saving SSID: %s", ssid);
|
||||||
|
|
||||||
nvs_handle_t h;
|
nvs_handle_t h;
|
||||||
if (nvs_open(WIFI_NS, NVS_READWRITE, &h) != ESP_OK) {
|
if (nvs_open(WIFI_NS, NVS_READWRITE, &h) != ESP_OK)
|
||||||
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "nvs error");
|
return send_text(req, "500 Internal Server Error", MSG_STORE_ERR);
|
||||||
return ESP_FAIL;
|
|
||||||
}
|
|
||||||
nvs_set_str(h, WIFI_SSID_KEY, ssid);
|
nvs_set_str(h, WIFI_SSID_KEY, ssid);
|
||||||
nvs_set_str(h, WIFI_PASS_KEY, pass);
|
nvs_set_str(h, WIFI_PASS_KEY, pass);
|
||||||
nvs_commit(h);
|
nvs_commit(h);
|
||||||
nvs_close(h);
|
nvs_close(h);
|
||||||
|
|
||||||
rtc_hint_valid = false;
|
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));
|
vTaskDelay(pdMS_TO_TICKS(800));
|
||||||
esp_restart();
|
esp_restart();
|
||||||
return ESP_OK;
|
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
|
/* Every unknown URL (Android generate_204, Apple hotspot-detect, Windows
|
||||||
* connecttest, ...) is redirected to the setup page. This is what makes the
|
* connecttest, ...) is redirected to the setup page. This is what makes the
|
||||||
* phone/PC pop up the "sign in to network" screen. */
|
* 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();
|
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
|
||||||
config.server_port = 80;
|
config.server_port = 80;
|
||||||
config.stack_size = 8192;
|
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) {
|
if (httpd_start(&s_portal_server, &config) != ESP_OK) {
|
||||||
ESP_LOGE(TAG, "Portal HTTP server failed to start");
|
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 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 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, &root);
|
||||||
httpd_register_uri_handler(s_portal_server, &save);
|
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);
|
httpd_register_err_handler(s_portal_server, HTTPD_404_NOT_FOUND, redirect_404_handler);
|
||||||
|
|
||||||
ESP_LOGI(TAG, "Portal HTTP server started on port 80");
|
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);
|
xTaskCreate(dns_server_task, "dns_server", 4096, NULL, 3, NULL);
|
||||||
start_portal_webserver();
|
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);
|
pdFALSE, NULL, prov_timeout_callback);
|
||||||
if (s_prov_timer) xTimerStart(s_prov_timer, 0);
|
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 */
|
/* 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)
|
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) {
|
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++;
|
s_retry++;
|
||||||
ESP_LOGW(TAG, "Disconnected, try %d/%d", s_retry, MAX_RECONNECT_TRIES);
|
ESP_LOGW(TAG, "Disconnected, try %d/%d", s_retry, MAX_RECONNECT_TRIES);
|
||||||
if (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. */
|
/* The media servers own port 80 by now, so reboot straight into the portal.
|
||||||
rtc_force_portal = true;
|
* Not a physical request: the portal will ask for the current login. */
|
||||||
|
portal_flag_set(1);
|
||||||
esp_restart();
|
esp_restart();
|
||||||
} else {
|
} else {
|
||||||
esp_wifi_connect();
|
esp_wifi_connect();
|
||||||
@@ -448,6 +650,29 @@ bool wifi_is_provisioning(void)
|
|||||||
return s_provisioning;
|
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)
|
void wifi_start_provisioning_if_needed(void)
|
||||||
{
|
{
|
||||||
/* NVS must be ready before the Wi-Fi driver starts */
|
/* 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(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));
|
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 */
|
/* A portal was requested (failed reconnects, HA, or the BOOT button) */
|
||||||
if (rtc_force_portal) {
|
ESP_LOGI(TAG, "Reset reason: %d", (int)esp_reset_reason());
|
||||||
rtc_force_portal = false;
|
|
||||||
ESP_LOGW(TAG, "Previous boot failed to connect, opening portal");
|
uint8_t pm = portal_flag_take();
|
||||||
|
if (pm) {
|
||||||
|
s_physical = (pm == 2);
|
||||||
|
ESP_LOGW(TAG, "Opening portal (physical=%d)", s_physical);
|
||||||
start_provisioning_mode();
|
start_provisioning_mode();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -505,3 +733,4 @@ void wifi_start_provisioning_if_needed(void)
|
|||||||
|
|
||||||
start_station_mode(ssid, pass);
|
start_station_mode(ssid, pass);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user