Replace form-urlencoded handlers with a JSON API + CORS

Both httpd servers now expose JSON endpoints (POST /api/wifi on the
commissioning AP; GET /api/status, GET/POST /api/mqtt on the settings
server) instead of form-urlencoded bodies, with CORS enabled
(http_cors.h) so a separately-hosted web app can call them from a
browser across origins -- not just the on-device pages, which now use
the same endpoints via fetch() too.

No JSON library ships with ESP-IDF v6.0.2 core (verified: no cJSON, no
bundled json component). Given these payloads are tiny, flat,
fixed-shape objects, json_helpers.h hand-rolls minimal strstr-based
extraction rather than adding a 4th external registry dependency
(already have mdns, mqtt, led_strip).

The settings page (mqtt.cpp) changes from server-side snprintf-built
dynamic HTML to a static embedded settings.html that fetches
/api/mqtt on load -- simpler code, and the actual point of the
refactor: the same API a future kvida-sdk client can use.

url_decode.h is removed (no longer needed once request bodies are
JSON instead of form-urlencoded).

Verified end-to-end against real hardware: /api/status, /api/mqtt,
and the CORS preflight for POST /api/mqtt all return correct
responses/headers when queried with a cross-origin Origin header.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Ronny Eia
2026-07-11 14:52:54 +02:00
parent 4af0f1b248
commit 3fee19c60a
9 changed files with 306 additions and 93 deletions

View File

@@ -12,7 +12,7 @@ Future transports (Zigbee, Thread, Matter) should implement the same publish API
- On boot, `try_stored_credentials()` attempts to connect using credentials saved in NVS from a previous session.
- If none exist (or the caller chooses to), `start_commissioning()` opens a SoftAP (`Kvida-XXXXXX`, derived from the MAC) with a captive portal: a DNS server (`src/dns_server.c`/`.h`, vendored from ESP-IDF's official `captive_portal` example, Unlicense/CC0) answers every query with the AP's own IP, and DHCP option 114 plus a 404-redirects-to-`/` HTTP handler get most phones/laptops to auto-open the setup page (`src/portal.html`) in a plain browser.
- Submitting the form (`POST /connect`) saves the credentials to NVS and switches Wi-Fi to STA mode. The AP is open (no password) by design -- see the comment above `ap_config.ap.authmode` in `commissioning.cpp` for the reasoning and the tradeoff.
- Submitting the form (`POST /api/wifi`, JSON body `{"ssid","password"}`) saves the credentials to NVS and switches Wi-Fi to STA mode. The AP is open (no password) by design -- see the comment above `ap_config.ap.authmode` in `commissioning.cpp` for the reasoning and the tradeoff.
- A 5-minute `esp_timer` closes the commissioning window automatically if nobody submits credentials.
- **IPv6**: once STA gets its IPv4 address (`IP_EVENT_STA_GOT_IP` -- not `WIFI_EVENT_STA_CONNECTED`, see the comment in `commissioning.cpp` for why that timing matters), `esp_netif_create_ip6_linklocal()` requests a link-local address (`CONFIG_LWIP_IPV6=y` is set explicitly in `sdkconfig.defaults`); `IP_EVENT_GOT_IP6` is logged when it arrives. Verified end-to-end on real ESP32-C6 hardware.
- Not yet wired up: re-entering commissioning on an already-configured device needs a physical trigger (the user button) per AGENTS.md's "configuration mode requires physical user interaction" principle -- blocked on `drivers` having a real button implementation. Network scanning (SSID dropdown instead of free text) was left out of this first pass to keep scope tight.
@@ -27,4 +27,16 @@ Future transports (Zigbee, Thread, Matter) should implement the same publish API
- On `MQTT_EVENT_CONNECTED`: publishes (retained) an HA MQTT Discovery config for a diagnostic `connectivity` binary_sensor, grouped under a `device` block (`identifiers`/`name` = the same `kvida-xxxxxx` id, `manufacturer` "Xylon", `model` "Kvida"), then publishes `online` to the availability topic. MQTT's own LWT (`session.last_will`, set at client init) publishes `offline` to the same topic if the connection drops. Verified end-to-end: device appears in Home Assistant with a "Connected" Connectivity sensor.
- No generic semantic `publish(topic, value)` API yet -- deferred until `profiles` has real sensor data to publish; building it now would be speculative.
## JSON API
Both httpd servers (the commissioning AP's and the settings server's) expose a small JSON API, CORS-enabled (`src/http_cors.h`) so a separately-hosted web app (`kvida-sdk`, e.g. via `npm run dev`) can call them from a browser across origins -- not just the on-device pages, which use the same endpoints via `fetch()`:
- `POST /api/wifi` (commissioning AP only) -- `{"ssid","password"}`, replaces the old form-urlencoded `/connect`.
- `GET /api/status` (settings server) -- `{"device_id","wifi_connected","mqtt_connected"}`.
- `GET /api/mqtt` / `POST /api/mqtt` (settings server) -- `{"host","port","username"[,"password"]}`; `GET` never returns the password.
No JSON library ships with ESP-IDF v6.0.2 core (verified: no `cJSON`, no bundled `json` component). Given these payloads are tiny, flat, fixed-shape objects, `src/json_helpers.h` hand-rolls minimal `strstr`-based extraction rather than adding a 4th external registry dependency (already have `mdns`, `mqtt`, `led_strip`) -- explicitly not a general parser (no nesting, arrays, or escaping beyond what these specific request bodies need).
**Important constraint that shaped this**: the Wi-Fi captive portal must keep being served by the device itself -- a phone connected to the isolated SoftAP has no route to any externally-run app. Only the MQTT/settings step (once the device has real LAN connectivity) can be driven by a separately-run web app. See `kvida-sdk`.
TODO: A/B OTA update-checking belongs here, driven by ESP-IDF's native `esp_ota_ops` against the `ota_0`/`ota_1` partitions in `partitions.csv` — no extra dependency needed either.