Files
led-controller/docs/API.md
T
jimmyandClaude Opus 5.5 b2cd242390 docs: describe the v2 controller's API, UI and tests
API.md now documents what the firmware serves: groups, combined
brightness, beat-driven sequences, import/export, /api/audio, patterns
over ESP-NOW, outputs, /ws, driver OTA, and how API calls become driver
messages and group commands. The user guide follows the current UI; the
in-app audio help describes the microphone instead of input devices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 20:42:03 +13:00

333 lines
26 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# LED Controller API
The controller is an ESP32-S3 on Ethernet (W5500). It serves the web UI and a JSON API on port 80, detects beats from its I2S microphone and talks to the LED drivers over ESP-NOW. This document covers:
1. The HTTP and WebSocket API, by resource.
2. How the controller turns API calls into driver messages, and the message format.
Request and response bodies are JSON (`Content-Type: application/json`) unless noted. Errors come back as `{"error": "..."}` with a 4xx or 5xx status.
## Data and scoping
- **Storage.** Each resource is a collection (`device`, `zone`, `preset`, `profile`, `palette`, `pattern`, `sequence`, `scene`, `group`, `output`, `settings`), stored as one JSON object of id → record on the flash filesystem. New records get the next numeric id (highest + 1), as a string. Devices are keyed by MAC (12 lowercase hex digits, no colons) and patterns by name.
- **Current profile.** `settings.current_profile_id`, set by `POST /profiles/<id>/apply`. When it is unset or names a missing profile, the first profile is current. It is global (the same for every browser).
- **Profile scoping.** Presets and sequences belong to a profile (`profile_id`). The list routes return only the current profile's records, and the single-record routes answer 404 for another profile's. Groups with a `profile_id` are visible only while that profile is current; groups without one are shared.
- **Current zone.** A `current_zone` cookie, set by `POST /zones/<id>/set-current`. Without it, the current profile's first zone.
- **Migration.** At boot, groups, zones and sequences written by older versions get the fields described below.
---
## Pages and static files
| Method | Path | Description |
|--------|------|-------------|
| GET | `/` | Main UI |
| GET | `/settings/page` | Standalone settings page |
| GET | `/audio` | Live audio and beat page (level, tempo, bar position, tap) |
| GET | `/static/<path>` | UI scripts and styles |
| GET | `/favicon.ico` | 204 |
Pages and static files are built into the firmware (gzipped, sent with `Content-Encoding: gzip`). They carry `Cache-Control: no-cache` and an `ETag` of the firmware build, so a browser revalidates each load (304 until the next update).
## Controller
| Method | Path | Description |
|--------|------|-------------|
| GET | `/status` | IP, MAC, uptime, `free_heap`, `free_internal` (internal RAM), mic level, tempo and beat counts, ESP-NOW and link statistics |
| POST | `/reboot` | Replies `{"message":"rebooting"}`, then restarts after 0.5 s |
| GET | `/ota` | Running image: partition, version, build time, IDF version, sha |
| POST | `/ota` | Body: the raw firmware `.bin` (web UI included). Written to the idle slot, made the boot image, then the board reboots. A new image confirms itself after staying up a few seconds; one that crashes on start rolls back. `make ota HOST=<ip>` |
| GET | `/db/<collection>` | Export a whole collection |
| PUT | `/db/<collection>` | Replace a whole collection. Body: the object of id → record. Reply: `{"records": n}` |
**Bench tests** (see `docs/BENCH_TEST.md`):
| Method | Path | Description |
|--------|------|-------------|
| GET, POST | `/test/loss` | Simulated ESP-NOW loss. Body `{"percent": 0–100, "beats": bool}` (whether beat frames are dropped too). Reply: the current setting |
| POST | `/test/beats` | Body `{"bpm": 30–300, "count": n}` (0 = until stopped): synthetic beats to the drivers, with delivery and latency measured from their echoes. The mic's beats are muted meanwhile |
| GET | `/test/beats` | Results so far |
| POST | `/test/beats/stop` | Stop the generator |
## Settings — `/settings`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/settings` | The settings object |
| PUT | `/settings` or `/settings/settings` | Merge keys into the settings. Reply: `{"message": "Settings updated successfully"}` |
Keys with meaning on the controller (others are stored as they are):
| Key | Checked | Meaning |
|-----|---------|---------|
| `hostname` | | mDNS name (`<hostname>.local`, default `led-controller`); applies after a restart |
| `static_ips` | | List of `{ip, netmask?, gw, dns?}` tried in order when the Ethernet link comes up; the first whose gateway answers ARP is used, else DHCP. Applies after a restart |
| `global_brightness` | integer 0–255 | Global factor of each driver's brightness (see Groups). Stored only: the UI pushes each driver its combined value |
| `wifi_channel` | integer 1–11 | Stored for reference. The controller's ESP-NOW channel is set at build time (`make menuconfig`) |
| `audio_simulated_bpm` | clamped to 60–200 | Tempo of the beat clock (default 120) |
| `sequence_switch_wait` | `beat` or `downbeat` | When a newly started sequence takes over from the playing one |
| `audio_beat_phase_ms` | integer 0–500 | Stored for the UI |
| `audio_input_volume` | integer 0–200 | Stored for the UI |
| `current_profile_id` | | Set by profile apply and import |
| `audio_timing` | | Set by `/api/audio/start` and `/stop` |
Defaults filled at boot: `wifi_channel` (the build's ESP-NOW channel) and `global_brightness` (255).
## Profiles — `/profiles`
A profile is `{name, type: "zones", zones: [zone ids], scenes, palette_id}`.
| Method | Path | Description |
|--------|------|-------------|
| GET | `/profiles` | `{"profiles": {...}, "current_profile_id": "<id>"}` |
| GET | `/profiles/current` | `{"id": "<id>", "profile": {...}}`; 404 when there are no profiles |
| GET | `/profiles/<id>` | One profile (`current` works as an id) |
| POST | `/profiles` | Create. Body: `name` and any other fields; optional `seed_dj_zone`. Reply `{"<id>": profile}`, 201. See below |
| PUT | `/profiles/<id>`, `/profiles/current` | Merge fields |
| POST | `/profiles/<id>/apply` | Make it current. Reply `{"message": "Profile applied", "id": "<id>"}` |
| POST | `/profiles/<id>/clone` | Copy with its own palette, zones and presets (preset references in the zones point at the copies). Body: optional `name`. 201 |
| DELETE | `/profiles/<id>` | Delete it with its presets and sequences, and its zones and palette unless another profile lists them |
| GET | `/profiles/<id>/export` | Profile bundle (see Import and export) |
| POST | `/profiles/import` | Body: `{"bundle": {...}, "name"?, "apply"? (default true)}` or the bundle itself. Reply `{"<id>": profile, "id": "<id>"}`, 201 |
A new profile gets an empty palette, eight presets (`on`, `off`, `rainbow` (`colour_cycle`), `Colour Cycle`, `transition`, `flicker`, `flame`, `twinkle`) and a zone `default` that lists them and names driver `1`. With `seed_dj_zone` it also gets three `DJ …` presets in a zone `dj` naming driver `dj`.
## Presets — `/presets`
A preset has `name`, `pattern`, `colors` (`#RRGGBB`), `brightness`, `delay`, `n1`–`n8`, `profile_id`, and optionally `auto`, `palette_refs` (palette index per colour slot), `background` / `background_palette_ref`, `mode` (sent as `n6`) and `manual_beat_n`. New presets start with every field set and belong to the current profile.
| Method | Path | Description |
|--------|------|-------------|
| GET | `/presets` | The current profile's presets |
| GET | `/presets/<id>` | One preset (404 for another profile's) |
| POST | `/presets` | Create in the current profile. Reply `{"<id>": preset}`, 201 |
| PUT | `/presets/<id>` | Merge fields |
| DELETE | `/presets/<id>` | Delete |
| POST | `/presets/push` | Send driver messages. Body: `{"sequence": [message, ...]}` or `{"payload": message}`, optional `targets` (MACs: acked unicast to each). Without targets, broadcast. Reply `{"message": "Delivered"}`. See Driver messages |
| POST | `/presets/send` | Send stored presets. Body: `preset_ids` (or `ids`), `save` (default true), `default` (startup preset id), `targets` or `destination_mac`. Reply `{"message": "Presets sent", "presets_sent": n}` |
| GET | `/presets/<id>/export` | Preset bundle |
| POST | `/presets/import` | Body: a preset bundle (or `{"bundle": ...}`). New id in the current profile, 201 |
## Zones — `/zones`
A zone has `name`, `names` (driver names, the older way to target drivers), `group_ids` (groups it plays to), `presets` (rows of preset ids), `presets_flat`, `default_preset`, `preset_group_ids`, `sequence_ids`, `content_kind` (`presets` or `sequences`) and `brightness` (0–255, the zone slider).
| Method | Path | Description |
|--------|------|-------------|
| GET | `/zones` | `{"zones": {...all zones}, "zone_order": [current profile's zone ids], "current_zone_id", "profile_id"}` |
| GET | `/zones/current` | `{"zone": {...}, "zone_id": "<id>"}`, or 404 `{"error", "zone": null, "zone_id": null}` |
| GET | `/zones/<id>` | One zone |
| POST | `/zones` | Create (body: `name` required, `names` or `ids`, `group_ids`, `presets`, `content_kind`, ...). Added to the current profile's zone list. 201 |
| PUT | `/zones/<id>` | Merge fields |
| DELETE | `/zones/<id>` | Delete (`current` works as an id) and remove it from every profile. Clears the cookie if it was current |
| POST | `/zones/<id>/set-current` | Set the `current_zone` cookie |
| POST | `/zones/<id>/clone` | Copy into the current profile. Body: optional `name` (default `<name> Copy`). 201 |
| GET | `/zones/<id>/content-fragment` | With `HX-Request`: the zone's tab content (HTML); otherwise the main page |
| POST | `/zones/<id>/play` | Body `{"preset_id", "drivers"?}`: upload the preset to the zone's groups and select it (`drivers: false` skips sending). 404 for an unknown zone or preset |
| POST | `/zones/<id>/stop` | Select `off` on the zone's groups. `{"stopped": bool}` |
| GET | `/zones/engine/status` | Sequence playback status (as `/sequences/status`) |
## Groups — `/groups`
A group lists drivers by MAC (`devices`) and carries `output_brightness` (0–255), driver defaults (`wifi_driver_display_name`, `wifi_driver_num_leds`, `wifi_color_order`, `wifi_startup_mode`) and pattern fields. MACs are normalised to 12 lowercase hex digits. A driver's group membership is every group listing its MAC (see Driver groups), sent to it whenever groups, zones or devices change.
| Method | Path | Description |
|--------|------|-------------|
| GET | `/groups` | Groups visible in the current profile |
| GET | `/groups/<id>` | One group (404 when scoped to another profile) |
| POST | `/groups` | Create with defaults; `profile_scoped: true` ties it to the current profile, `profile_id` may only name the current profile or be null. Reply: the group, 201 |
| PUT | `/groups/<id>` | Merge fields |
| DELETE | `/groups/<id>` | Delete |
| POST | `/groups/<id>/brightness` | Each member gets its combined brightness, saved on the driver. `{"message", "sent", "errors": [{mac, error}]}` |
| POST | `/groups/<id>/driver-config` | Each member gets `device_config` from the group's driver defaults (body fields override for this send). 400 when none is set |
| POST | `/groups/<id>/identify` | All members blink red together for 2 s, then go off. 400 when the group has no devices |
**Combined brightness** for a driver: `round(255 × global/255 × g₁/255 × … × device/255 [× zone/255])`, with one factor per group listing it (`output_brightness`), the device's `output_brightness` and, when given, the zone slider.
## Devices — `/devices`
A device is `{id: MAC, name, type: "led", transport: "espnow" | "wifi", address, default_pattern, zones, output_brightness?}`. ESP-NOW drivers register themselves when they boot (announce) and when they answer a ping. For ESP-NOW devices `address` is the MAC. The controller has no Wi-Fi driver transport: Wi-Fi records are kept, but nothing is sent to them.
| Method | Path | Description |
|--------|------|-------------|
| GET | `/devices` | All devices, each with `connected` (`null` for ESP-NOW, `false` for Wi-Fi) |
| GET | `/devices/<id>` | One device (the id may be written with colons) |
| POST | `/devices` | Create. `name` required; `mac` (or, for ESP-NOW, a MAC in `address`); `transport` `espnow` (default) or `wifi`. Reply `{"<mac>": device}`, 201; 409 for a MAC already registered |
| PUT | `/devices/<id>` | Merge fields. `name` cannot be blank, the MAC cannot change, `output_brightness` 0–255. Changing `max_brightness`, `num_leds`, `color_order`, `startup_mode` or `reversed` also sends them to the driver as `device_config` |
| DELETE | `/devices/<id>` | Delete |
| GET | `/devices/status` | Per driver: `{"last_ack_ms_ago": ms or -1, "failed_messages": n}` from the acked link |
| POST | `/devices/ping` | Body `{"timeout_s": 0.5–30}` (default 3). Broadcasts a ping and collects replies: `{"ok", "ping_id", "timeout_s", "responses": {mac: {mac, name, rtt_ms}}, "registered": n}`. Drivers that answer are added or renamed |
| POST | `/devices/groups` | Send every ESP-NOW driver its groups and wait for the acks: `{"ok", "total", "sent", "failed"}` (503 when any failed, 400 with no ESP-NOW devices) |
| POST | `/devices/resolve-brightness` | Body `{"macs": [...], "zone_brightness"?}` → `{"values": {mac: brightness}}` |
| POST | `/devices/<id>/brightness` | Body `{"zone_brightness"?}`: send the combined brightness, saved on the driver. `{"message", "brightness"}` |
| POST | `/devices/<id>/driver-config` | Body: any of `name`, `num_leds` (1–2048), `color_order`, `startup_mode` (`default`, `last`, `off`) |
| POST | `/devices/<id>/identify` | Red 10 Hz blink for 2 s, then off |
## Sequences — `/sequences`
A sequence is `{name, profile_id, lanes: [[step, ...], ...], lanes_group_ids: [[group ids], ...], group_ids, loop (default true), advance_mode: "beats", steps, step_duration_ms, sequence_transition}`. A step is `{preset_id, beats (default 1), group_ids?}`.
| Method | Path | Description |
|--------|------|-------------|
| GET | `/sequences` | The current profile's sequences |
| GET | `/sequences/<id>` | One sequence |
| POST | `/sequences` | Create in the current profile. A non-empty `steps` without lanes becomes lane 0. Reply `{"<id>": sequence}`, 201 |
| PUT | `/sequences/<id>` | Merge fields; stops it when it is playing |
| DELETE | `/sequences/<id>` | Delete; stops it when it is playing |
| POST | `/sequences/<id>/play` | Body `{"zone_id"}` (required). Reply `{"ok": true, "pending": bool, ...}`. 400 for a missing zone, a sequence without steps or one from another profile |
| POST | `/sequences/stop` | Stop playback and clear the presets on the zone's groups. `{"ok": true}` |
| POST | `/sequences/sync-phase` | Body `{"mode": "step" | "pass"}`: `step` restarts the current step's beat count, `pass` restarts the sequence. Also makes this beat bar beat 1. 409 when nothing plays |
| GET | `/sequences/status` | Playback status (below) |
| GET | `/sequences/<id>/export` | Sequence bundle (the sequence and its presets) |
| POST | `/sequences/import` | Body: a sequence bundle. The presets are copied into the current profile and the steps point at the copies. 201 |
**Playback.** One sequence plays at a time, in one zone.
- **Start.** Each lane's first preset is uploaded to the lane's groups and selected, then the lane's other presets are uploaded, and every driver in the zone gets its combined brightness with the zone slider.
- **Advancing.** On each beat a lane counts towards its step's `beats`, then moves on: the next preset is uploaded (unless already there) and selected. A lane's groups are `lanes_group_ids[lane]`, else `group_ids`, else (single lane) the step's `group_ids`, else the zone's groups.
- **End.** Without `loop` the sequence ends after one pass. Its presets are cleared from the zone's groups, and the readout keeps `n/n`.
- **Switching.** Starting another sequence while one plays waits for the next beat. It waits for the next downbeat only when `sequence_switch_wait` is `downbeat` and the mic is timing. The current sequence holds meanwhile.
- **Beat source.** Beats come from the mic's beat detector while audio timing is on (`/api/audio/start`) and it has a tempo lock. Otherwise they come from a clock at `audio_simulated_bpm`, whose beats also go to the drivers. Beats closer than 0.3 s (200 BPM) are dropped.
Status: `{"active": false, "beat_readout": ""}` when idle, else `{active, advance_mode, sequence_id, zone_id, num_lanes, total_sequence_steps, lane0_current_step, lane0_lane_length, lane0_beat_in_step, lane0_beats_per_step, lane0_preset_id, lane0_preset_name, sequence_beat_at, sequence_beats_per_pass, sequence_loop_beat, beat_readout}`.
## Audio — `/api/audio`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/audio/status` | `{"status": {...}}`, see below |
| GET | `/api/audio/events` | Server-sent events, `data: {"type": "status" | "beat", "status": {...}}`: a status event first, one on every detected beat, and a status heartbeat every 0.5 s |
| POST | `/api/audio/start` | Mic beats time sequences and go to the drivers. Saved. `{"ok": true, "status"}` |
| POST | `/api/audio/stop` | The beat clock times sequences instead; the mic's beats stop going to the drivers. Saved |
| POST | `/api/audio/reset` | Forget the tempo and bar position and track again (409 while stopped) |
| POST | `/api/audio/anchor-bar` | Make the last beat bar beat 1 (409 while stopped) |
| GET | `/api/audio/devices` | The single input: `{"devices": [{"id": "i2s", "name", "display_name", "is_default": true}], "diagnostics": {}}` |
| PUT | `/api/audio/device` | Body `{"device_select"}`: stored only (there is one microphone) |
Status fields: `running` (audio timing on), `bpm` (locked tempo, `null` without a lock, the clock's tempo while stopped), `bpm_simulated`, `beat_seq`, `bar_beat`, `beats_per_bar`, `is_downbeat`, `bar_phase_readout`, `phase_confidence`, `input_level`, `last_beat_ts`, `sequence` (playback status), `sequence_pending`, `beat_readout`, `sequence_switch_wait` (in effect) and `sequence_switch_wait_saved`, `audio_simulated_bpm`, `simulated_beat_tick`, `audio_run`, `beat_phase_ms`, `input_volume`.
The `/audio` page uses its own routes:
| Method | Path | Description |
|--------|------|-------------|
| GET | `/audio.wav` | Live microphone audio (16 kHz mono WAV stream; one listener at a time) |
| GET | `/beats` | Server-sent events: `beat` (`bpm`, `n`, `bar`, `meter`, `sure`, `us`), `onset`, and `tempo` every second |
| POST | `/tap` | The user tapped bar beat 1 now |
| GET | `/time` | Board clock (`{"us": ...}`) for the page to line its clock up with |
## Patterns — `/patterns`
Pattern metadata is the `pattern` collection, keyed by name. Pattern sources are the led-driver `src/patterns/*.py` files built into the firmware, plus uploads (stored on the controller, and they take precedence). `on` and `off` are built into the driver and have no file.
| Method | Path | Description |
|--------|------|-------------|
| GET | `/patterns`, `/patterns/definitions` | Metadata, plus `{}` for every pattern file without metadata |
| GET | `/patterns/<name>` | Metadata record |
| POST | `/patterns` | Body `{name, data: {...}, ...}`: `data` and the other keys become the record under `name`. Reply: the record, 201 |
| PUT, DELETE | `/patterns/<name>` | Merge, delete (the file stays) |
| GET | `/patterns/ota/manifest` | `{"files": [{"name": "x.py", "url": "http://<Host>/patterns/ota/file/x.py"}]}` |
| GET | `/patterns/ota/file/<name>.py` | The source (`text/plain`); 400 for `on`/`off`, 404 when missing |
| POST | `/patterns/upload` | Body `{name, code, overwrite?}`: store a source. 409 when it exists and `overwrite` is false. 201 |
| POST | `/patterns/driver` | Body `{name, code, overwrite?, min_delay?, max_delay?, max_colors?, n1?..n8?}`: store the source and its metadata (`n1`–`n8` are parameter labels). The name must be an identifier. 201 |
| POST | `/patterns/<name>/send` | Push the source over ESP-NOW to one driver (`{"device_id"}`) or every ESP-NOW driver, as `patterns/<name>.py`; drivers that wrote it reset to load it. `{"message", "pattern", "device_ids", "sent_count", "results"}`; 503 when none took it |
| POST | `/devices/<id>/patterns/push` | 400: use `/patterns/<name>/send` |
## Palettes — `/palettes`
A palette is a list of colours.
| Method | Path | Description |
|--------|------|-------------|
| GET | `/palettes` | `{id: [colours]}` |
| GET | `/palettes/<id>` | `{"colors": [...], "id": "<id>"}` |
| POST | `/palettes` | Body `{"colors"}`. Reply `{"id", "colors"}`, 201 |
| PUT | `/palettes/<id>` | Body `{"colors"}`: replaces the list |
| DELETE | `/palettes/<id>` | Delete |
## Scenes — `/scenes`
Plain records: GET (list, one), POST (201), PUT (merge), DELETE. Scenes do not play.
## Outputs — `/outputs`
Network pixel fixtures. An output is `{id, name, protocol: "ddp" | "artnet" | "sacn" | "dmx_serial", host, port, universe, channel, serial_port, dmx_mode, pixel_count, pixel_offset, color_order, reverse, brightness, fps, enabled}` with defaults filled in. The checks:
- `ddp` needs a `host`. `dmx_serial` needs a `serial_port`, and its pixels must fit one DMX universe.
- Number ranges: `port` 1–65535, `universe` 0–32767 (sACN 1–63999), `channel` 1–512, `brightness` 0–255, `fps` 1–120.
- `color_order` is one of `rgb rbg grb gbr brg bgr`.
| Method | Path | Description |
|--------|------|-------------|
| GET | `/outputs`, `/outputs/<id>` | List, one |
| POST | `/outputs` | Create (400 with the failed check). Reply: the output, 201 |
| PUT | `/outputs/<id>` | Merge and check again |
| DELETE | `/outputs/<id>` | Delete |
| POST | `/outputs/<id>/test` | Body `{"step_s": 0.1–5}` (default 1): solid red, green, blue and white for `step_s` each at `fps`, then black. `{"message", "status": {name, protocol, kind, pixel_count, frames, packets, bytes, errors, last_error}}`. 503 for `dmx_serial` (no USB-DMX adapter on this board) |
Zones do not render to outputs: only the test pattern is sent.
## WebSocket — `/ws`
On connect the controller sends `{"type": "device_tcp_snapshot", "connected_ips": []}` (there are no Wi-Fi driver sessions). Each text frame is a driver message (JSON object), sent as `/presets/push` would send it: an optional `to` (MAC) addresses one driver, otherwise it is broadcast. A frame that is not a JSON object, or a failed send, gets `{"error": ...}` back. A plain GET gets 426.
## Driver app update — `/drivers/ota`
Pushes led-driver `.py` files to ESP-NOW drivers, one file per request; `tools/driver_ota.py` (`make ota-drivers`) runs a whole session. The wire format is in `led-driver/src/espnow_ota.py`. One request runs at a time; another gets 409.
| Method | Path | Description |
|--------|------|-------------|
| POST | `/drivers/ota/file?mac=<macs>&sess=<n>&path=<p>&sha=<64 hex>` | Body: the raw file (up to 65536 bytes). `mac` is a comma-separated list of MACs, or `all` for every ESP-NOW device. `sess` (1–65535) is shared by every file of one update. `path` is the driver path: a root file, `patterns/…` or `lib/…`. Drivers that already have that sha256 skip it. One target gets acked unicast. Several get one broadcast, then each is asked for its missing chunks and repaired. The file is staged until commit. Reply: `{"<mac>": {"result": "same" | "written" | "error", "code"?, "repaired": n}}` |
| POST | `/drivers/ota/commit?mac=<macs>&sess=<n>` | Drivers move their staged files into place, update `file_hashes.json` and reset if anything changed |
| POST | `/drivers/ota/abort?mac=<macs>&sess=<n>` | Drivers delete their staged files |
---
## Driver messages
The UI, `/presets/push`, `/ws` and the controller itself send drivers **v1 messages**: JSON objects with `"v": "1"`. The controller does not send them as they are:
- **Binary envelope.** A message that only carries presets, a select, brightness, `save` and `groups` goes out as a compact binary envelope (`main/envelope.c`, mirrored by `test/binary_envelope.py`).
- **JSON.** Any other message goes as JSON with short keys, split across several messages when it does not fit one ESP-NOW frame. A preset with a background colour (`bg`) is one of these: the envelope has no field for it.
- **Delivery.** Broadcasts are never acked (envelopes go out twice, JSON once); drivers that miss a state change notice from the state digest and ask to be brought up to date. Messages with `targets` are unicast to each MAC, acked and retried.
### Fields
| Long key | Short | Meaning |
|----------|-------|---------|
| `presets` | `p` | Map of preset id → preset |
| `select` | `s` | `["preset_id"]` or `["preset_id", step]` for every driver addressed; or a map of driver name → that list |
| `groups` | `g` | Only drivers in one of these groups apply the message |
| `set_groups` | `sg` | With `groups`: replace the driver's group list |
| `save` | `sv` | Persist presets, brightness or config on the driver |
| `default` | `df` | Startup preset id |
| `device_config` | `dc` | `name`, `num_leds`, `color_order`, `startup_mode`, `max_brightness`, `reversed` |
| `clear_presets` | `cp` | Drop stored presets |
| `manifest` | `mf` | Pattern files to fetch (Wi-Fi drivers) |
| `b` | | Driver brightness 0–255 |
Preset fields: `p`/`pattern`, `c`/`colors` (`#RRGGBB`), `d`/`delay` (ms, default 100), `b`/`brightness` (0–255), `a`/`auto` (`true` runs freely, `false` steps once per beat), `bg`/`background`, `n1`–`n6` (pattern parameters; `n5` is reverse, `n6` the style mode). Other fields (`name`, `manual_beat_n`, …) are dropped on the way out.
Sending `select` again with the same preset is a beat for that preset. Selecting `off` resets the step, so the next select starts every driver at step 0 unless a step is given.
### Driver groups
A driver keeps a list of group ids and applies a group command (or a message with `groups`) only when it holds one of them. The controller sends each ESP-NOW driver its list whenever groups, zones or devices change, when the driver boots, and when it asks to be brought up to date. A driver that has failed three messages in a row gets these updates at most every 30 s until it answers again. The list holds:
- every group (`group` collection) whose `devices` lists the driver's MAC, by group id;
- `z<zone id>` for every zone whose `names` lists the driver's name (zones from before groups).
A zone plays to its `group_ids` and, when it names drivers, to `z<zone id>`. A message with `groups` that fits the envelope goes out as one group command per group.
### Example
```json
{
"v": "1",
"presets": {
"12": {"pattern": "chase", "colors": ["#ff0000", "#0000ff"], "delay": 80, "brightness": 255, "auto": true, "n1": 4, "n2": 4}
},
"select": ["12"],
"groups": ["3"],
"save": true
}
```
Pattern parameters are documented in the led-driver repository.