Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Converters (IoT & Cloud) v1.0 (frozen on 2026-11-23, commit 71e82be). Switch to Latest →

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; fallback CYW43_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, IP 10.10.10.254/24), DHCPv4 server (UDP 67, pool 10.10.10.16..31, 24 h lease, RFC 8910 Opt 114 "http://10.10.10.254/"), and wildcard DNS server (UDP 53, all IN/A -> 10.10.10.254, TTL 30 s). Any unmatched HTTP GET in AP mode returns 302 Found -> http://10.10.10.254/.
  • 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 to 300 s (15 s attempt timeout). On DHCP IP acquisition, tears down AP/DHCP/DNS and promotes to WIFI_MODE_STA.
    • In STA mode: auto-reconnects every 10 s on link drop (promoting RAM-only fallback SSID if primary fails). On CLOUD_FAILURE_TRANSIENT streaks: Tier 2 at 3 and 6 failures resets STA interface; Tier 3 at 10 failures runs cyw43_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 arms 60 s rollback deadline disarmed only by successful cloud HTTPS response; timeout restores prior credentials ("wifi_60s_rollback_restored").
  • 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) -> returns 202 + 32-hex operation_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-lwIP tcpip_thread never blocks. Client polls POST /api/auth/login-status (IP-bound, 30 s TTL) until 200 with 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/logout return 403 {"error":"password_change_required"}. Password change is also async (202 -> poll POST /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.
  • Embedded Installer SPA (src/ux/index.html, 8 Sidebar Views):
    • dashboard (Pulpit: 6 KPI cards, health pill jumping to affected tab), meters (Liczniki: grouped by measurement_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, queue retry/skip actions 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.c binds port 80 on IP_ANY_TYPE, allows max 4 concurrent TCP connections (HTTP_SERVER_MAX_CONNS), requires free_heap >= sizeof(http_connection_t) + 4096 + 2048 before accepting (else 503 Service Unavailable, Retry-After: 2), caps total request at 4095 B (413 on overflow), enforces 10 s incomplete-request timeout, mandates HTTP/1.1, single Host header, zero Transfer-Encoding, and always responds with Connection: close.
  • BR-UI-02 (Bearer-Only IP-Bound Sessions): src/web/web_server.c:357-379 & auth.c accept only Authorization: Bearer <64-hex> (no cookies). Max 4 concurrent 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..64 printable ASCII (0x21..0x7E, no spaces), at least 1 uppercase, 1 lowercase, 1 digit, 1 special char, distinct from old password. Username: 3..31 chars [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..63 chars), IP 10.10.10.254/24, DHCP pool 10.10.10.16..31 (16 leases, 86400 s), DNS wildcard TTL 30 s, no AP auto-shutdown timer.
  • BR-UI-05 (Destructive Confirmation Tokens): POST /api/system/factory-reset requires {"confirmation":"RESET"} (preserves SD telemetry if journal is READY); POST /api/cloud/delivery skip requires {"confirmation":"SKIP"} (emits CLOUD_RECORD_SKIPPED 5001); replay requires {"confirmation":"REPLAY"} and decimal u64 sequence.
  • BR-UI-06 (Embedded UI Zero-CDN & Zone 1 Branding): src/ux/index.html is compressed at build time via scripts/html_to_header.py (gzip.compress(..., compresslevel=9, mtime=0)) into INDEX_HTML_GZ streamed zero-copy from Flash (TCP_MSS chunks, 2 * TCP_MSS window) with strict CSP (default-src 'self'; object-src 'none'; frame-ancestors 'none'), neutral graphite #09090b/#121215/#18181b, #32ca42 accent with #09090b button text, inline Planovi SVG logo, and Polish-only UI text.
  • BR-UI-07 (Single Active Role in Practice): Although API_ROUTES[] distinguishes AUTH_ROLE_INSTALLER and AUTH_ROLE_ADMIN, auth.c:319 assigns AUTH_ROLE_ADMIN to every authenticated login session.
  • BR-UI-08 (UI Polling & Retry Discipline): src/ux/index.html applies 20 s fetch timeout, auto-retries GET on 503 up to 3 times (200/400 ms), polls login at 250 ms (max 480 tries), password change at 500 ms (max 240 tries), data view every 10 s (when active), scan/test every 1 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.
  • Side Effects: NVS writes (config_store), portable SD backup trigger (portable_config), background tasks (AuthWorker, ModbusScan, MeterTest, transient Reboot), 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-docs via scripts/sync-brand.sh.

7. Why It Works This Way (Decisions, Trade-offs & Workarounds)

  • Async PBKDF2 Worker (AuthWorker): Moving 100k-iteration PBKDF2 off tcpip_thread prevents 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 uses CYW43_AUTH_WPA2_AES_PSK.
  • Confirmed Bug (api_endpoints.c:557-578, auth.c:953-992): POST /api/auth/account (username change) still runs 100k-iteration derive_password_hash() synchronously inside tcpip_thread, risking network stalls/watchdog reset.
  • Confirmed Bug (api_endpoints.c:1869-1878 vs index.html:1886): GET /api/status omits cloud.transport, yet the Dashboard calls cloudStateLabel(value.cloud.state, value.cloud.transport) (and index.html checks transport === 1 for HTTPS whereas firmware defines CLOUD_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 (unlike login-status).
  • Confirmed UX Discrepancy (index.html:1190 vs api_endpoints.c:2024): UI claims factory reset deletes “kolejkę danych”, whereas firmware preserves SD telemetry ("telemetry_preserved":true) when SD is ready. Also index.html:962 still mentions “testów T04” in #archive-warning.
  • Inconsistency (wifi_manager.c:707-726): AP background recovery only tries WPA2_AES_PSK (omitting WPA2_MIXED_PSK fallback used in wifi_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 MessageRoot Cause in CodeHow to Verify / Exact CommandFix
403 {"error":"password_change_required"} on all /api/* callsInitial OTP setup password has not been changed yet (api_endpoints.c:2194-2203)POST /api/auth/login-status returns password_change_required: trueComplete 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.pyWait 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 3xRetry after 500 ms
Captive portal doesn’t pop up on laptopClient connected to STA LAN (where unmatched routes return 404), or OS didn’t follow DHCP Opt 114 / DNS wildcardConnect 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