4. Embedded Installer Portal, Wi-Fi AP/STA Self-Healing & Local HTTP REST API
Repository:
Converters (planovi-converter)• Rule Prefix:BR-UI• Documented Rules: 8 • Open[TEAM_WHY_NEEDED]Questions: 2
1. Business Purpose & Actors
Allows an on-site electrical installer to commission, configure, diagnose, and service an Edge Converter locally over Wi-Fi without Internet connectivity or external CDNs. Exposes a captive-portal WPA2 Access Point (10.10.10.254) with DHCP/DNS interception, an authenticated local HTTP/1.1 REST API (27 routes), a gzipped single-page Zone 1 Planovi web UI (src/ux/index.html -> src/ux/ux_page.h), and autonomous Wi-Fi STA/AP self-healing with 60-second remote credential rollback.
- Actors: On-site Electrical Installer / Commissioning Technician (browser connected to
Planovi-<serial>AP or site LAN STA IP), Cloud Operator triggering remote Wi-Fi commands (reconnect_wifi,update_wifi_credentials,reset_wifi_ap).
2. All Features & End-to-End Flows
- Boot Wi-Fi Mode Selection & Captive Portal (
src/net/wifi_manager.c,dhcp_server.c,dns_server.c):- Trigger:
wifi_manager_start()during boot. - Flow: If NVS
wifi.is_configured == true, attempts STA (CYW43_AUTH_WPA2_AES_PSK, 15 s; fallbackCYW43_AUTH_WPA2_MIXED_PSK,max(timeout/2, 2000)ms; DHCP wait 10 s). If unconfigured or STA fails, starts WPA2-AES AP (Planovi-<serial>, OTP setup password, IP10.10.10.254/24), DHCPv4 server (UDP 67, pool10.10.10.16..31, 24 h lease, RFC 8910 Opt 114"http://10.10.10.254/"), and wildcard DNS server (UDP 53, allIN/A->10.10.10.254, TTL 30 s). Any unmatched HTTPGETin AP mode returns302 Found->http://10.10.10.254/.
- Trigger:
- AP Background STA Recovery & Multi-Tier Wi-Fi Self-Healing:
- While in AP mode with saved STA creds, transiently enables STA every
30 s-> exponential backoff up to300 s(15 sattempt timeout). On DHCP IP acquisition, tears down AP/DHCP/DNS and promotes toWIFI_MODE_STA. - In STA mode: auto-reconnects every
10 son link drop (promoting RAM-only fallback SSID if primary fails). OnCLOUD_FAILURE_TRANSIENTstreaks: Tier 2 at3and6failures resets STA interface; Tier 3 at10failures runscyw43_arch_deinit()+cyw43_arch_init()+wifi_manager_start()without rebooting RP2350 (Modbus continues uninterrupted). - Remote
update_wifi_credentials: connects to new SSID (8 s), persists to NVS, and arms60 srollback deadline disarmed only by successful cloud HTTPS response; timeout restores prior credentials ("wifi_60s_rollback_restored").
- While in AP mode with saved STA creds, transiently enables STA every
- Async PBKDF2 Login, Forced First-Login Password Change & Per-IP Lockout (
src/web/auth.c,api_endpoints.c):- Trigger:
POST /api/login(or/api/auth/login) -> returns202+ 32-hexoperation_token(poll_after_ms: 250). - Processing:
"AuthWorker"task computes 100,000-iteration PBKDF2-HMAC-SHA-256 (HW SHA-256, yielding every 256 iterations) so raw-lwIPtcpip_threadnever blocks. Client pollsPOST /api/auth/login-status(IP-bound, 30 s TTL) until200with 64-hex Bearer token +password_change_required. - First-Login Gate: While
password_change_required == true, all authenticated routes except/api/change-password,/api/auth/password, and/api/auth/logoutreturn403 {"error":"password_change_required"}. Password change is also async (202-> pollPOST /api/auth/password-status) and wipes all active sessions upon completion. - Lockout: 5 consecutive failures from an IP lock that IP for
900 s(15 min) (403 {"error":"temporarily_locked"}), tracking up to 8 IPs.
- Trigger:
- Embedded Installer SPA (
src/ux/index.html, 8 Sidebar Views):dashboard(Pulpit: 6 KPI cards, health pill jumping to affected tab),meters(Liczniki: grouped bymeasurement_point, CRUD + post-save control read, RS-485 bus scan),wifi(Sieć Wi-Fi: manual SSID/password, no Wi-Fi scanner),data(Dane i karta SD: SD/FIFO/quarantine stats, interval/enable form, paginated 10-item local history viewer),cloud(Serwer i czas: HTTPS/MQTT endpoint config + browser-to-RTC UTC sync),account(Konto i bezpieczeństwo: username/password change),diagnostics(Diagnostyka: full-bus test run up to 16 result cards, Modbus error counters, queueretry/skipactions when blocked),system(System: reboot, disabled v1 OTA button,"RESET"-confirmed factory reset).
3. Hard Business Rules, Validations, Calculations & Edge Cases
BR-UI-01(HTTP/1.1 Server Hard Limits):src/web/web_server.cbinds port80onIP_ANY_TYPE, allows max4concurrent TCP connections (HTTP_SERVER_MAX_CONNS), requiresfree_heap >= sizeof(http_connection_t) + 4096 + 2048before accepting (else503 Service Unavailable,Retry-After: 2), caps total request at4095 B(413on overflow), enforces10 sincomplete-request timeout, mandatesHTTP/1.1, singleHostheader, zeroTransfer-Encoding, and always responds withConnection: close.BR-UI-02(Bearer-Only IP-Bound Sessions):src/web/web_server.c:357-379&auth.caccept onlyAuthorization: Bearer <64-hex>(no cookies). Max4concurrent sessions,1800 s(30 min) sliding monotonic TTL, strictly bound to requester IPv4. All sessions are invalidated on password or username change.BR-UI-03(Password & Username Complexity): Passwords (is_strong_password(),auth.c:227-238):12..64printable ASCII (0x21..0x7E, no spaces), at least 1 uppercase, 1 lowercase, 1 digit, 1 special char, distinct from old password. Username:3..31chars[A-Za-z0-9._-], distinct from current.BR-UI-04(Captive Portal AP Identity & Lease Pool): AP SSID is"Planovi-%.23s"(OTP serial), WPA2-AES only (CYW43_AUTH_WPA2_AES_PSK), password = OTP setup password (8..63chars), IP10.10.10.254/24, DHCP pool10.10.10.16..31(16 leases,86400 s), DNS wildcard TTL30 s, no AP auto-shutdown timer.BR-UI-05(Destructive Confirmation Tokens):POST /api/system/factory-resetrequires{"confirmation":"RESET"}(preserves SD telemetry if journal isREADY);POST /api/cloud/deliveryskiprequires{"confirmation":"SKIP"}(emitsCLOUD_RECORD_SKIPPED5001);replayrequires{"confirmation":"REPLAY"}and decimal u64sequence.BR-UI-06(Embedded UI Zero-CDN & Zone 1 Branding):src/ux/index.htmlis compressed at build time viascripts/html_to_header.py(gzip.compress(..., compresslevel=9, mtime=0)) intoINDEX_HTML_GZstreamed zero-copy from Flash (TCP_MSSchunks,2 * TCP_MSSwindow) with strict CSP (default-src 'self'; object-src 'none'; frame-ancestors 'none'), neutral graphite#09090b/#121215/#18181b,#32ca42accent with#09090bbutton text, inline Planovi SVG logo, and Polish-only UI text.BR-UI-07(Single Active Role in Practice): AlthoughAPI_ROUTES[]distinguishesAUTH_ROLE_INSTALLERandAUTH_ROLE_ADMIN,auth.c:319assignsAUTH_ROLE_ADMINto every authenticated login session.BR-UI-08(UI Polling & Retry Discipline):src/ux/index.htmlapplies20 sfetch timeout, auto-retriesGETon503up to 3 times (200/400 ms), polls login at250 ms(max 480 tries), password change at500 ms(max 240 tries),dataview every10 s(when active), scan/test every1 s.
4. State Machines & Data Lifecycle
stateDiagram-v2
[*] --> DISCONNECTED
DISCONNECTED --> CONNECTING: Boot with wifi.is_configured=true
DISCONNECTED --> RUNNING_AP: Boot unconfigured or STA failure
CONNECTING --> CONNECTED_STA: WPA2-AES/Mixed + DHCP IP OK
CONNECTING --> RUNNING_AP: Timeout (15s) or auth failure
RUNNING_AP --> RUNNING_AP: Background STA probe (30s..300s backoff) fails -> disable STA
RUNNING_AP --> CONNECTED_STA: Background STA probe gets IP -> stop AP/DHCP/DNS
CONNECTED_STA --> CONNECTED_STA: Link drop -> 10s retry (+ fallback SSID) / Cloud Tier 2-3 heal
CONNECTED_STA --> RUNNING_AP: Remote reset_wifi_ap (5s delay) or 10s physical button hold
5. Technical Contract (Inputs -> Processing -> Side Effects)
- All 27 Local REST Routes (
src/web/api_endpoints.c:2044-2105):- Auth (7):
POST /api/login,POST /api/auth/login,POST /api/auth/login-status,POST /api/auth/logout,POST /api/change-password,POST /api/auth/password,POST /api/auth/password-status,GET/POST /api/auth/account(counting aliases/api/login&/api/change-password= 9 route entries). - Network & Cloud (6):
GET/POST /api/wifi,GET/POST /api/cloud,POST /api/cloud/delivery,GET /api/status. - Data & Meters (7):
GET/POST /api/data,GET /api/data/history,GET/POST/PUT/DELETE /api/meters. - Scan & Diagnostics (5):
POST /api/scan/start,POST /api/modbus-scan,GET /api/scan/status,POST /api/test-run,GET /api/test-status. - System (3):
POST /api/system/reboot,POST /api/system/factory-reset,POST /api/system/time.
- Auth (7):
- Side Effects: NVS writes (
config_store), portable SD backup trigger (portable_config), background tasks (AuthWorker,ModbusScan,MeterTest, transientReboot), live Wi-Fi/DHCP/DNS state changes.
6. Cross-Repository Dependencies
- None (fully offline local LAN/AP interface). Brand tokens/SVG synced from
PA-IDEAS/planovi-docsviascripts/sync-brand.sh.
7. Why It Works This Way (Decisions, Trade-offs & Workarounds)
- Async PBKDF2 Worker (
AuthWorker): Moving 100k-iteration PBKDF2 offtcpip_threadprevents HTTP/Wi-Fi stalls and watchdog timeouts during login/password changes. - No Mixed WPA/WPA2 on AP (
wifi_manager.c:133): Modern Windows WLAN clients display mixed-mode APs but fail association; AP strictly usesCYW43_AUTH_WPA2_AES_PSK. - Confirmed Bug (
api_endpoints.c:557-578,auth.c:953-992):POST /api/auth/account(username change) still runs 100k-iterationderive_password_hash()synchronously insidetcpip_thread, risking network stalls/watchdog reset. - Confirmed Bug (
api_endpoints.c:1869-1878vsindex.html:1886):GET /api/statusomitscloud.transport, yet the Dashboard callscloudStateLabel(value.cloud.state, value.cloud.transport)(andindex.htmlcheckstransport === 1for HTTPS whereas firmware definesCLOUD_TRANSPORT_MQTT = 1, CLOUD_TRANSPORT_HTTPS = 2), causing Dashboard to show MQTT labels in HTTPS mode. - Confirmed Security Gap (
auth.c:910-932):POST /api/auth/password-status(AUTH_ROLE_GUEST) is neither IP-bound nor TTL-expired (unlikelogin-status). - Confirmed UX Discrepancy (
index.html:1190vsapi_endpoints.c:2024): UI claims factory reset deletes “kolejkę danych”, whereas firmware preserves SD telemetry ("telemetry_preserved":true) when SD is ready. Alsoindex.html:962still mentions “testów T04” in#archive-warning. - Inconsistency (
wifi_manager.c:707-726): AP background recovery only triesWPA2_AES_PSK(omittingWPA2_MIXED_PSKfallback used inwifi_manager_connect_sta()), and fallback Wi-Fi creds remain RAM-only until promoted. [TEAM_WHY_NEEDED: No Wi-Fi SSID scanning endpoint exists in wifi_manager.c; installers must type SSIDs manually. Is SSID scan intentionally omitted for Flash/CYW43 stability in v1?][TEAM_WHY_NEEDED: POST /api/cloud/delivery supports action="replay", but src/ux/index.html only exposes "retry" and "skip". Is replay intentionally restricted to Cloud remote commands / CLI?]
8. Debugging, Logs & Common Failure Modes
| Symptom / Error Message | Root Cause in Code | How to Verify / Exact Command | Fix |
|---|---|---|---|
403 {"error":"password_change_required"} on all /api/* calls | Initial OTP setup password has not been changed yet (api_endpoints.c:2194-2203) | POST /api/auth/login-status returns password_change_required: true | Complete POST /api/auth/password with a 12–64 char strong password, then re-login |
403 {"error":"temporarily_locked"} | 5 failed login attempts from caller IP triggered 900 s lockout (auth.c:20,539-560) | Reproduce/verify with python3 tools/test_device_login_lockout.py | Wait 15 min or reboot converter |
503 {"error":"storage_busy","retry_after_ms":500} | SdWriter or TelemetryTask holds FIFO/SD mutex (api_endpoints.c) | Transient during SD commit/migration; UI auto-retries 3x | Retry after 500 ms |
| Captive portal doesn’t pop up on laptop | Client connected to STA LAN (where unmatched routes return 404), or OS didn’t follow DHCP Opt 114 / DNS wildcard | Connect to Planovi-<serial> AP, verify IP in 10.10.10.16..31, browse http://10.10.10.254/ | Open http://10.10.10.254/ manually |