feat(v2): ESP32-S3 controller with Ethernet, I2S mic beat detection and ESP-NOW
New ESP-IDF project in v2/ that replaces the Pi and the UART bridge: - W5500 Ethernet, INMP441 beat/tempo detector (from esp32-eth), ESP-NOW master - LittleFS data store and a JSON API over the Pi's db/*.json collections, with /db import and export; web UI minified and gzipped at build time - Zone play/stop as 0x4C GROUP_CMD, preset push/send as CMD (binary v2 envelope, byte-identical to src/util/binary_envelope.py), sequencer and scenes, driver registration from the boot hello - Reliable bulk link: acks with retransmit, fragments, state-version digest and resync; beat frames sent twice with a lead so drivers fire together - Bench tooling: lossy-link mode, synthetic beats with echo measurement, USB and logic-analyzer latency scripts, and docs/BENCH_TEST.md Needs the matching led-driver changes (p2p branch) to receive the link and beat frames. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7336c7fb22
commit
a94d6a7de5
37 files changed
+5109
No files matched your search
@@ -0,0 +1,5 @@
|
||||
build/
|
||||
sdkconfig
|
||||
sdkconfig.old
|
||||
managed_components/
|
||||
www_dist/
|
||||
@@ -0,0 +1,3 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
project(led_controller_v2)
|
||||
@@ -0,0 +1,20 @@
|
||||
dependencies:
|
||||
idf:
|
||||
source:
|
||||
type: idf
|
||||
version: 5.5.5
|
||||
joltwallet/littlefs:
|
||||
component_hash: e1a0f4a6adf821759cb34703a91107bbdce5d7ff6f4728f40ab012bb87842974
|
||||
dependencies:
|
||||
- name: idf
|
||||
require: private
|
||||
version: '>=5.0'
|
||||
source:
|
||||
registry_url: https://components.espressif.com/
|
||||
type: service
|
||||
version: 1.23.1
|
||||
direct_dependencies:
|
||||
- joltwallet/littlefs
|
||||
manifest_hash: 39931b5fd49af3f43a545f2b46eed14a91ad9a530706d1e14335b6dbea19a246
|
||||
target: esp32s3
|
||||
version: 2.0.0
|
||||
@@ -0,0 +1,253 @@
|
||||
# v2 bench test: one S3 controller and one LED driver
|
||||
|
||||
This walks one ESP32-S3 controller (W5500 Ethernet, INMP441 mic) and one `led-driver` unit through flashing, a smoke test, a lossy-link test and a beat latency measurement. Nothing here has been run on hardware yet, so treat the expected numbers as targets to check, not results.
|
||||
|
||||
## 0. What you need
|
||||
|
||||
- Controller: XIAO ESP32-S3 with a W5500 module wired as in `main/Kconfig.projbuild` (SCLK 7, MISO 8, MOSI 9, CS 2, INT 3, RST 1), Ethernet cable to a DHCP network. The mic is optional for this test; the bench generator makes its own beats.
|
||||
- Driver: one `led-driver` unit (MicroPython, the `p2p` ESP-NOW branch) with a few LEDs. It needs no Wi-Fi network.
|
||||
- A PC on the same network. Docker with `espressif/idf:v5.5.5` for building.
|
||||
- For the true latency measurement: a logic analyzer or scope with two channels and a common ground. Optional: the software echo numbers need nothing extra.
|
||||
|
||||
**Channel rule.** ESP-NOW only works when both radios use the same channel. The p2p driver uses its `wifi_channel` setting (default 5); the controller's default is now 5 as well (`CONFIG_ESPNOW_CHANNEL` in `sdkconfig.defaults`). If your driver uses another channel, change the controller before building:
|
||||
|
||||
```bash
|
||||
cd v2 && docker run --rm -v "$PWD":/project -w /project espressif/idf:v5.5.5 idf.py menuconfig
|
||||
```
|
||||
|
||||
then *ESP-NOW config → Wi-Fi channel*. Alternatively set `CONFIG_ESPNOW_CHANNEL=<n>` in `sdkconfig.defaults` (delete `sdkconfig` after, so it is regenerated). To use the beat marker pin, also set `CONFIG_BEAT_TEST_GPIO` (for example 4) in the same menu.
|
||||
|
||||
## 1. Build and flash the controller
|
||||
|
||||
```bash
|
||||
cd v2
|
||||
tools/build_web.sh
|
||||
docker run --rm -v "$PWD":/project -w /project espressif/idf:v5.5.5 idf.py build
|
||||
```
|
||||
|
||||
Expect `Project build complete`, the app well under its 2 MB slot, and `build/www.bin` present. Fix ownership if Docker left it root-owned: `docker run --rm -v "$PWD":/project espressif/idf:v5.5.5 chown -R 0:0 /project`.
|
||||
|
||||
Flash with the S3 on USB (check which port it is; `ls /dev/ttyACM*`):
|
||||
|
||||
```bash
|
||||
docker run --rm --device=/dev/ttyACM0 -v "$PWD":/project -w /project espressif/idf:v5.5.5 idf.py -p /dev/ttyACM0 flash
|
||||
```
|
||||
|
||||
This writes the bootloader, partition table, app and the web UI image. Watch the log:
|
||||
|
||||
```bash
|
||||
docker run --rm -it --device=/dev/ttyACM0 -v "$PWD":/project -w /project espressif/idf:v5.5.5 idf.py -p /dev/ttyACM0 monitor
|
||||
```
|
||||
|
||||
Look for, in order: `store: ... records` lines, `espnow_tx: ESP-NOW up on channel N`, `rel: reliable link up`, `Ethernet Link Up`, `Got IP: x.x.x.x`, `HTTP server started`.
|
||||
|
||||
## 2. First checks (replace `$S3` with the IP)
|
||||
|
||||
```bash
|
||||
export S3=192.168.1.50
|
||||
curl -s http://$S3/status
|
||||
```
|
||||
|
||||
Expect JSON with `uptime_s`, `bpm`, an `espnow` block and a `link` block (`ver` nonzero, `digests` increasing by one about every 1.5 s). If the mic hears music, `bpm` and `beats_sent` move too, which means beats are already being broadcast. Open `http://$S3/` in a browser: the UI should load, and the dev tools network tab should show `Content-Encoding: gzip` on `/static/*.js`.
|
||||
|
||||
```bash
|
||||
curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' http://$S3/static/presets.js | grep -i -E 'content-encoding|content-type'
|
||||
```
|
||||
|
||||
## 3. Load data and add a test zone
|
||||
|
||||
Import the Pi database (the files hold your real zones and presets, so use a copy if you want a smaller test):
|
||||
|
||||
```bash
|
||||
for n in device zone preset profile palette pattern sequence scene; do
|
||||
curl -s -X PUT --data-binary @../db/$n.json http://$S3/db/$n; echo " $n"
|
||||
done
|
||||
```
|
||||
|
||||
The driver registers itself: it broadcasts a hello at boot, the controller adds it to the device list under its MAC and sends it its group list. Check with `curl -s http://$S3/devices/<mac>` once the driver is running (step 4). Zones are the drivers' groups: a zone's `names` must contain the driver's **name** exactly (`led-<mac>` by default, see its `settings.json`).
|
||||
|
||||
```bash
|
||||
curl -s -X POST -d '{"name":"bench","names":["led-aabbccddeeff"]}' http://$S3/zones
|
||||
curl -s -X POST -d '{"name":"bench red","pattern":"on","colors":["#ff0000"],"delay":100,"brightness":255,"auto":true}' http://$S3/presets
|
||||
```
|
||||
|
||||
Note the returned ids (`<zone>` and `<preset>` below). Creating or changing a zone re-sends group lists to every registered ESP-NOW driver.
|
||||
|
||||
## 4. Prepare the driver
|
||||
|
||||
The driver runs the `p2p` branch of `led-driver` plus these files from this work: `src/beat_sync.py`, `src/espnow_rx.py`, and changed `src/main.py` and `src/presets.py`. Back up the device's own copies first (`mpremote fs cp :main.py ./main.py.bak`), then copy the new ones (`mpremote fs cp src/main.py :main.py` and so on) and reset.
|
||||
|
||||
Optional keys in the driver's `settings.json` for the later tests:
|
||||
|
||||
| key | value | meaning |
|
||||
|---|---|---|
|
||||
| `bench` | `true` | echo every fired beat to the controller and print stats every 50 beats |
|
||||
| `beat_pin` | e.g. `5` | GPIO toggled on every fired beat, for the logic analyzer |
|
||||
| `espnow_loss` | `0` | percent of received frames the driver discards (set later) |
|
||||
|
||||
After boot, the controller's `/devices` list should contain the driver's MAC and `/status` should show `link.acked` rising (the group list was acknowledged). `mpremote` interrupts the running program, so reset the driver after using it.
|
||||
|
||||
## 5. Smoke test
|
||||
|
||||
```bash
|
||||
curl -s -X POST -d '{"preset_id":"<preset>"}' http://$S3/zones/<zone>/play
|
||||
```
|
||||
|
||||
The driver's console should log the preset and select it received (once each, although the controller sends every state frame twice), and the LEDs should go red within a fraction of a second. Then:
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://$S3/zones/<zone>/stop # LEDs off
|
||||
curl -s http://$S3/devices/status # last_ack_ms_ago / failed_messages per registered driver
|
||||
```
|
||||
|
||||
Zone play is a group broadcast, so `devices/status` only changes for acked (unicast) traffic. Trigger one with a targeted push:
|
||||
|
||||
```bash
|
||||
curl -s -X POST -d '{"sequence":[{"v":"1","select":{"led-aabbccddeeff":["<preset>"]}}],"targets":["aabbccddeeff"]}' http://$S3/presets/push
|
||||
curl -s http://$S3/devices/status
|
||||
```
|
||||
|
||||
Expected: `last_ack_ms_ago` is small (tens of ms) and `failed_messages` is 0. `/status` shows `link.acked` increased.
|
||||
|
||||
## 6. Lossy-link test
|
||||
|
||||
The loss mode discards a percentage of frames before the radio on the controller (all outgoing frames, and incoming acks and echoes). The driver can discard received frames too. This makes the retry, fragment and resync layers do real work without moving antennas.
|
||||
|
||||
```bash
|
||||
# controller: 40% loss, beats included
|
||||
curl -s -X POST -d '{"percent":40,"beats":true}' http://$S3/test/loss
|
||||
curl -s http://$S3/status # sim_dropped counts dropped frames
|
||||
```
|
||||
|
||||
Run these and compare with the table:
|
||||
|
||||
| test | how | expected |
|
||||
|---|---|---|
|
||||
| Acked unicast under loss | repeat the targeted push from step 5 twenty times at 40% (give each a different select step so you can tell them apart on the driver console) | all reach the driver; `link.retransmits` rises. A message needs its data and its ack to both survive, and there are 5 sends in total, so about 1 in 10 is reported as timed out even though the driver usually has it |
|
||||
| Give up and report | set `percent` to 100, push once, wait 2 s | `link.ack_timeouts` +1 and `devices/status` shows `failed_messages: 1` |
|
||||
| Lost broadcast, digest recovery | `percent` 100, play a different preset on the zone, then set `percent` 0 | the LEDs do not change at first, then within about 1.5 to 5 s the driver sends a resync and shows the new preset; `link.resyncs` +1 |
|
||||
| Driver-side loss | set `"espnow_loss": 40` in the driver's `settings.json` (restore it afterwards), controller loss 0, push twenty times | every push is processed once on the driver (retransmissions are de-duplicated); `link.retransmits` rises. Lost acks are covered by the controller-side loss rows above, because that setting also drops incoming acks |
|
||||
| Multi-message send | `POST /presets/send` with 10+ preset ids, `save: false` and `targets` | the controller packs the presets into a few binary messages (14 presets took 2); all arrive under loss, with retransmits. `save: true` makes the driver write its `presets.json`, so restore that file afterwards. Frame-level fragmentation exists in the link but nothing in the current API produces a message over one frame, so it is only covered by the driver's unit tests |
|
||||
|
||||
Set loss back to 0 when done: `curl -s -X POST -d '{"percent":0}' http://$S3/test/loss`.
|
||||
|
||||
Reading the numbers: the controller drops a reply with the same probability as a request, so under loss an unicast message needs both the data and the ack to survive. Resync requests are also subject to loss and to the driver's 3 s minimum gap, so recovery may take a few digests.
|
||||
|
||||
### Results of the first run (S3 to one p2p driver, channel 5)
|
||||
|
||||
| test | result |
|
||||
|---|---|
|
||||
| 20 acked pushes, controller loss 40% | 20 of 20 reached the driver; 19 acked, 1 reported timed out (its ack was lost); 19 retransmits; 34 frames dropped by the test mode |
|
||||
| 1 push, loss 100% | gave up after 2.0 s with 4 retransmits; `failed_messages` 1; driver heard nothing |
|
||||
| zone play during a 100% outage, then loss back to 0 | driver was untouched during the outage; 1.5 s after the link returned it received its groups, the preset and the select, one resync, and the new state |
|
||||
| 20 acked pushes, driver-side loss 40% | 20 of 20 processed exactly once; 14 retransmits; 0 timeouts |
|
||||
| `/presets/send` of 14 presets at driver loss 40% | 2 messages (209 and 217 bytes), both acked, 1 retransmit |
|
||||
|
||||
## 7. Beat latency and delivery
|
||||
|
||||
### Software numbers (no equipment)
|
||||
|
||||
Start synthetic beats with the driver in `bench` mode:
|
||||
|
||||
```bash
|
||||
curl -s -X POST -d '{"bpm":120,"count":200}' http://$S3/test/beats
|
||||
sleep 105
|
||||
curl -s http://$S3/test/beats
|
||||
```
|
||||
|
||||
Results include:
|
||||
|
||||
- `beats_sent`, `echoes` and `hit_pct_total`: the share of beats each driver fired on and reported. With no loss expect 100%.
|
||||
- `rtt_minus_lead_min/avg/max_us`: time from the first beat copy going out to the driver's echo coming back, minus the 30 ms the driver deliberately waits (`CONFIG_BEAT_LEAD_MS`). This is out-airtime plus the driver's MicroPython work plus return airtime, so it overstates one-way delay. Expect roughly 2 to 15 ms; the maximum shows the worst case you will see on the LEDs.
|
||||
- `spread_avg_us` and `spread_max_us`: only meaningful with two or more drivers; shows how far apart they fire for the same beat.
|
||||
|
||||
On the driver's serial console every 50 beats you get the true driver-side counts, for example `beat {'fires': 100, 'dups': 100, 'late': 0, 'freerun': 0}`:
|
||||
|
||||
- `fires`: beats it acted on.
|
||||
- `dups`: second copies dropped (with the double send this should be close to `fires`).
|
||||
- `freerun`: beats it generated itself because both copies were missed. Zero without loss.
|
||||
- `late`: frames rejected as too soon or old.
|
||||
|
||||
### Delivery under loss
|
||||
|
||||
Repeat the run with loss on:
|
||||
|
||||
```bash
|
||||
curl -s -X POST -d '{"percent":30,"beats":true}' http://$S3/test/loss
|
||||
curl -s -X POST -d '{"bpm":120,"count":200}' http://$S3/test/beats
|
||||
```
|
||||
|
||||
Judge delivery from the driver's own `fires` and `freerun` counts: with two copies the chance of missing both is about 9% at 30% loss, and the free-run covers those, so `fires` should stay near `beats_sent` with `freerun` around 9% of it. The controller's `hit_pct_total` is lower because echoes are dropped by the same loss setting; it is a lower bound, roughly `(1 - loss) × delivery`.
|
||||
|
||||
### Latency over USB (no extra equipment)
|
||||
|
||||
Both boards are on USB, so the PC can timestamp one event line from each and compare them. Settings already applied for this: the driver has `"usb_log": true` in `settings.json`. The controller prints `BT <beat> <microseconds>` for every synthetic beat; the driver prints `FIRE <beat> <ticks_us>` when it fires.
|
||||
|
||||
```bash
|
||||
python3 tools/usb_latency.py --ctrl-port /dev/ttyACM0 --drv-port /dev/ttyACM1 --url http://$S3 --beats 200
|
||||
```
|
||||
|
||||
The script starts the generator, reads both ports, and maps each board's clock onto the PC's by using the fastest USB deliveries per 5 s window (this also removes crystal drift). USB serial delivers in bursts, so single lines arrive up to about 50 ms late; the fastest ones are close to on time, which is what the mapping relies on. The remaining error is the difference between the two ports' fastest delivery, roughly 1 ms, so read results to about a millisecond. The script prints the delivery jitter so you can see how noisy the ports were. The driver's `FIRE` time is when the beat triggers the pattern step; the LED data follows within the same loop pass, and a 119-LED strip takes about 3.6 ms to clock out.
|
||||
|
||||
Close any serial monitor first (only one program can hold a port). Do not run long `mpremote exec` commands on the driver during the capture (see Troubleshooting).
|
||||
|
||||
### True latency with a logic analyzer
|
||||
|
||||
For a measurement that does not depend on USB. Marker pins are set up already: the controller toggles **GPIO4 (D3)** when the first copy of each beat goes out (`CONFIG_BEAT_TEST_GPIO=4`, in `sdkconfig.defaults`) and the driver toggles **GPIO4 (D3)** when it fires (`"beat_pin": 4` in its `settings.json`). Both are XIAO ESP32S3 boards, where D3 is free.
|
||||
|
||||
Wiring (3.3 V logic, any 2 or 3 channel analyzer):
|
||||
|
||||
| analyzer | connect to |
|
||||
|---|---|
|
||||
| GND | GND on the controller **and** GND on the driver (one common ground) |
|
||||
| channel 0 | controller **D3** |
|
||||
| channel 1 | driver **D3** |
|
||||
| channel 2 (optional) | driver **D10** (GPIO9, the LED data line) to see when the LEDs really update |
|
||||
|
||||
Steps:
|
||||
|
||||
1. Make sure the driver runs a preset that changes on every beat if you use channel 2, for example a `chase` preset with `auto` off, selected on the zone. With the plain `on` preset the LED data line stays quiet.
|
||||
2. Start a capture: sample rate at least 1 MS/s, length at least 60 s (edges only; it stays small), trigger on any edge of channel 0.
|
||||
3. Start the beats: `curl -s -X POST -d '{"bpm":120,"count":100}' http://$S3/test/beats`. Both markers toggle on every beat, so you will see edges 500 ms apart.
|
||||
4. Stop the capture when the generator finishes (about 52 s) and export the digital data as CSV (time in seconds, one column per channel).
|
||||
5. Analyze: `python3 tools/analyze_edges.py capture.csv --ctrl 0 --drv 1 --time-unit s`. Use `--lead-ms` if you changed `CONFIG_BEAT_LEAD_MS`. It pairs each controller edge with the next driver edge and prints the delay beyond the 30 ms lead, with min, mean, median, p95, max and jitter, plus the count of unmatched beats. On the scope, channel 2 shows the true light delay: the first data burst after the driver edge.
|
||||
|
||||
Targets from the plan: under about 10 ms from the controller edge to the driver edge (after subtracting the lead).
|
||||
|
||||
Return to normal use by deleting `beat_pin` and `usb_log` from the driver's `settings.json` and setting `CONFIG_BEAT_TEST_GPIO=-1` (the marker pin otherwise toggles on every beat, including live mic beats).
|
||||
|
||||
### Results of the first run (software numbers, one driver, channel 5)
|
||||
|
||||
Synthetic beats at 120 BPM, 160 beats per run, mic beats muted while the generator runs, driver in `bench` mode.
|
||||
|
||||
| | no loss | 30% loss (beats included) |
|
||||
|---|---|---|
|
||||
| beats the driver acted on, per beat sent | 1.00 | 1.00 |
|
||||
| beats the driver invented itself (free-run) | 0% | 11% (theory for two independent copies: 9%) |
|
||||
| second copies dropped as duplicates | 100% | 47% (theory: 49%) |
|
||||
| echoes the controller received | 162 of 162 | 96 of 161 (echoes are lost at 30% too, and invented beats do not echo) |
|
||||
| round trip minus the 30 ms lead, min / avg / max | 9.8 / 15.0 / 25.7 ms | 3.4 / 16.2 / 26.0 ms |
|
||||
|
||||
Reading it: the double send plus free-run gave the driver a beat every time, even with 30% of frames lost. The round-trip figure includes the driver's loop and the echo's trip back, so it is an upper bound on the delay the LEDs see; it is not the controller-to-LED latency. The USB and logic analyzer measurements below give the real figure.
|
||||
|
||||
Latency over USB (200 beats at 120 BPM, one driver, 119 LEDs): delay beyond the 30 ms lead min 0.49, mean 2.07, median 1.77, p95 4.41, max 7.95 ms (std 1.3 ms; accuracy about 1 ms). 197 of 200 beats matched. Both clocks drifted by 60 to 80 ppm against the PC, and individual USB lines arrived up to 54 ms late, which is why the script uses the fastest deliveries. This is the time from the controller sending a beat to the driver firing, beyond the built-in lead. The logic analyzer run has not been done.
|
||||
|
||||
## 8. Troubleshooting
|
||||
|
||||
- **Running a long `mpremote exec` on the driver resets it:** the driver's watchdog (10 s) keeps running after `mpremote` interrupts `main.py`, so keep REPL experiments under about 8 s and reset the driver afterwards.
|
||||
|
||||
- **Driver never reacts, no acks:** channel mismatch. Check `CONFIG_ESPNOW_CHANNEL` against the driver's `wifi_channel`. Neighbouring channels can still work at bench range, so a working link does not prove they match.
|
||||
- **Zone play logs nothing on the driver:** the driver is not in the zone's group (silent). Check the zone's `names` against the driver's `name`.
|
||||
- **Devices show `last_ack_ms_ago: -1`:** the device record has no usable 12-character MAC in `address` or as its key.
|
||||
- **`beats_sent` rises but `echoes` stays 0:** the driver is not in `bench` mode, or it has not yet heard a controller frame (it learns the controller's MAC from the first data or digest frame; wait a few seconds).
|
||||
- **Resync never triggers:** the driver ignores a digest equal to its own version; confirm with `/status` that `link.ver` changed after the missed play.
|
||||
- **Web UI is blank:** the `www` image was not built before flashing; run `tools/build_web.sh` and flash again.
|
||||
|
||||
## 9. Cleanup
|
||||
|
||||
```bash
|
||||
curl -s -X POST -d '{"percent":0}' http://$S3/test/loss
|
||||
curl -s -X POST http://$S3/test/beats/stop
|
||||
```
|
||||
|
||||
Set the driver's `bench` and `espnow_loss` back to off for normal use.
|
||||
@@ -0,0 +1,10 @@
|
||||
idf_component_register(SRCS "main.c" "mic.c" "beat.c" "beat_dsp.c" "espnow_tx.c" "store.c" "api.c" "web.c" "envelope.c" "engine.c" "rel.c" "bench.c"
|
||||
INCLUDE_DIRS "."
|
||||
REQUIRES esp_eth esp_netif esp_event esp_driver_spi esp_driver_gpio nvs_flash
|
||||
esp_http_server esp_timer esp_driver_i2s esp_wifi esp_rom json esp_driver_gpio
|
||||
PRIV_REQUIRES littlefs)
|
||||
|
||||
# Flash the gzipped web UI into the www partition (run tools/build_web.sh first)
|
||||
if(EXISTS ${PROJECT_DIR}/www_dist)
|
||||
littlefs_create_partition_image(www ${PROJECT_DIR}/www_dist FLASH_IN_PROJECT)
|
||||
endif()
|
||||
@@ -0,0 +1,139 @@
|
||||
menu "W5500 config"
|
||||
|
||||
config W5500_SPI_HOST
|
||||
int "SPI host number (1=SPI2, 2=SPI3)"
|
||||
range 1 2
|
||||
default 1
|
||||
|
||||
config W5500_SPI_CLOCK_MHZ
|
||||
int "SPI clock speed (MHz)"
|
||||
range 5 80
|
||||
default 20
|
||||
|
||||
config W5500_SCLK_GPIO
|
||||
int "SCLK GPIO (XIAO D8)"
|
||||
default 7
|
||||
|
||||
config W5500_MISO_GPIO
|
||||
int "MISO GPIO (XIAO D9)"
|
||||
default 8
|
||||
|
||||
config W5500_MOSI_GPIO
|
||||
int "MOSI GPIO (XIAO D10)"
|
||||
default 9
|
||||
|
||||
config W5500_CS_GPIO
|
||||
int "CS GPIO (XIAO D1)"
|
||||
default 2
|
||||
|
||||
config W5500_INT_GPIO
|
||||
int "INT GPIO (XIAO D2), -1 to poll"
|
||||
default 3
|
||||
|
||||
config W5500_POLL_PERIOD_MS
|
||||
int "RX poll period (ms) when INT is -1"
|
||||
default 10
|
||||
|
||||
config W5500_RST_GPIO
|
||||
int "RST GPIO (XIAO D0), -1 if not wired"
|
||||
default 1
|
||||
|
||||
endmenu
|
||||
|
||||
menu "INMP441 mic config"
|
||||
|
||||
config MIC_SCK_GPIO
|
||||
int "SCK GPIO (XIAO D4)"
|
||||
default 5
|
||||
|
||||
config MIC_WS_GPIO
|
||||
int "WS GPIO (XIAO D5)"
|
||||
default 6
|
||||
|
||||
config MIC_SD_GPIO
|
||||
int "SD GPIO (XIAO D6)"
|
||||
default 43
|
||||
|
||||
config MIC_STREAM_GAIN
|
||||
int "Digital gain for the audio stream (x)"
|
||||
range 1 256
|
||||
default 16
|
||||
help
|
||||
The INMP441 is quiet at full scale; x16 (+24 dB) makes speech
|
||||
audible without clipping at normal distances.
|
||||
|
||||
endmenu
|
||||
|
||||
menu "Beat detection config"
|
||||
|
||||
config BEAT_LED_GPIO
|
||||
int "Beat LED GPIO (XIAO user LED is 21), -1 for none"
|
||||
default 21
|
||||
|
||||
config BEAT_LED_ACTIVE_LOW
|
||||
bool "Beat LED lights when the pin is low"
|
||||
default y
|
||||
|
||||
config BEAT_LED_PULSE_MS
|
||||
int "Beat LED flash length (ms)"
|
||||
range 10 500
|
||||
default 60
|
||||
|
||||
config BEAT_LED_DOWNBEAT_MS
|
||||
int "Beat LED flash length on the first beat of a bar (ms)"
|
||||
range 10 1000
|
||||
default 200
|
||||
|
||||
config BEAT_GATE_DBFS
|
||||
int "Ignore audio quieter than this (dBFS, before stream gain)"
|
||||
range -100 -20
|
||||
default -75
|
||||
help
|
||||
The INMP441 self-noise is about -87 dBFS. Background music in a
|
||||
room can sit around -65 dBFS, so keep this well below that.
|
||||
|
||||
config BEAT_LEAD_MS
|
||||
int "Fire predicted beats this early (ms)"
|
||||
range 0 200
|
||||
default 30
|
||||
help
|
||||
Beats are predicted from the tempo, so they can be sent early
|
||||
to cancel the ~30 ms of capture and analysis latency. Raise it
|
||||
to cover output latency too (e.g. network or lights).
|
||||
|
||||
endmenu
|
||||
|
||||
menu "ESP-NOW config"
|
||||
|
||||
config ESPNOW_CHANNEL
|
||||
int "Wi-Fi channel shared with the LED drivers"
|
||||
range 1 13
|
||||
default 6
|
||||
|
||||
config BEAT_TX_COPIES
|
||||
int "Copies sent of every beat frame"
|
||||
range 1 4
|
||||
default 2
|
||||
help
|
||||
Each beat is broadcast this many times with the same beat index.
|
||||
Drivers act on the first copy that arrives and drop the rest.
|
||||
|
||||
config BEAT_TX_GAP_US
|
||||
int "Gap between beat copies (us)"
|
||||
range 500 10000
|
||||
default 2000
|
||||
|
||||
config BEAT_TEST_GPIO
|
||||
int "GPIO toggled on every beat sent (-1 = off)"
|
||||
range -1 48
|
||||
default -1
|
||||
help
|
||||
For latency measurement: a logic analyzer or scope on this pin and on
|
||||
the driver's beat pin shows the true master-to-LED delay.
|
||||
|
||||
config BULK_HOLDOFF_US
|
||||
int "Hold bulk traffic back after a beat (us)"
|
||||
range 0 20000
|
||||
default 3000
|
||||
|
||||
endmenu
|
||||
+583
@@ -0,0 +1,583 @@
|
||||
#include "api.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "cJSON.h"
|
||||
#include "esp_log.h"
|
||||
#include "bench.h"
|
||||
#include "engine.h"
|
||||
#include "espnow_tx.h"
|
||||
#include "rel.h"
|
||||
#include "store.h"
|
||||
#include "web.h"
|
||||
|
||||
static const char *TAG = "api";
|
||||
|
||||
#define BODY_MAX (256 * 1024)
|
||||
|
||||
// URL resource -> store collection
|
||||
static const struct {
|
||||
const char *res;
|
||||
const char *coll;
|
||||
} RES[] = {
|
||||
{ "devices", "device" }, { "zones", "zone" }, { "presets", "preset" },
|
||||
{ "profiles", "profile" }, { "palettes", "palette" }, { "patterns", "pattern" },
|
||||
{ "sequences", "sequence" }, { "scenes", "scene" }, { "groups", "group" },
|
||||
{ "outputs", "output" },
|
||||
};
|
||||
|
||||
static esp_err_t send_json(httpd_req_t *req, const char *status, cJSON *obj, bool own)
|
||||
{
|
||||
char *s = cJSON_PrintUnformatted(obj);
|
||||
if (own) {
|
||||
cJSON_Delete(obj);
|
||||
}
|
||||
if (!s) {
|
||||
return httpd_resp_send_500(req);
|
||||
}
|
||||
httpd_resp_set_status(req, status);
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
esp_err_t ret = httpd_resp_send(req, s, HTTPD_RESP_USE_STRLEN);
|
||||
free(s);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static esp_err_t send_error(httpd_req_t *req, const char *status, const char *msg)
|
||||
{
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "error", msg);
|
||||
return send_json(req, status, o, true);
|
||||
}
|
||||
|
||||
// Parsed JSON object body, or NULL after an error response has been sent
|
||||
static cJSON *read_body(httpd_req_t *req)
|
||||
{
|
||||
if (req->content_len == 0 || req->content_len > BODY_MAX) {
|
||||
send_error(req, "400 Bad Request", req->content_len ? "body too large" : "body required");
|
||||
return NULL;
|
||||
}
|
||||
char *buf = malloc(req->content_len + 1);
|
||||
if (!buf) {
|
||||
httpd_resp_send_500(req);
|
||||
return NULL;
|
||||
}
|
||||
size_t got = 0;
|
||||
while (got < req->content_len) {
|
||||
int r = httpd_req_recv(req, buf + got, req->content_len - got);
|
||||
if (r <= 0) {
|
||||
free(buf);
|
||||
httpd_resp_send_err(req, HTTPD_408_REQ_TIMEOUT, "read failed");
|
||||
return NULL;
|
||||
}
|
||||
got += r;
|
||||
}
|
||||
buf[got] = 0;
|
||||
cJSON *obj = cJSON_Parse(buf);
|
||||
free(buf);
|
||||
if (!cJSON_IsObject(obj)) {
|
||||
cJSON_Delete(obj);
|
||||
send_error(req, "400 Bad Request", "JSON object required");
|
||||
return NULL;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
// Split "/res/id/action?query" into up to three segments
|
||||
static int split_path(const char *uri, char seg[3][64])
|
||||
{
|
||||
int n = 0;
|
||||
const char *p = uri;
|
||||
while (*p == '/' && n < 3) {
|
||||
p++;
|
||||
size_t len = strcspn(p, "/?");
|
||||
if (len == 0 || len >= 64) {
|
||||
break;
|
||||
}
|
||||
memcpy(seg[n], p, len);
|
||||
seg[n][len] = 0;
|
||||
n++;
|
||||
p += len;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
static const char *coll_for(const char *res)
|
||||
{
|
||||
for (size_t i = 0; i < sizeof(RES) / sizeof(RES[0]); i++) {
|
||||
if (strcmp(RES[i].res, res) == 0) {
|
||||
return RES[i].coll;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static const char *current_profile(void)
|
||||
{
|
||||
cJSON *v = cJSON_GetObjectItem(store_settings(), "current_profile_id");
|
||||
if (cJSON_IsString(v) && cJSON_GetObjectItem(store_coll("profile"), v->valuestring)) {
|
||||
return v->valuestring;
|
||||
}
|
||||
cJSON *first = store_coll("profile")->child; // fall back to the first profile
|
||||
return first ? first->string : NULL;
|
||||
}
|
||||
|
||||
static bool preset_in_profile(cJSON *rec)
|
||||
{
|
||||
const char *cur = current_profile();
|
||||
cJSON *pid = cJSON_GetObjectItem(rec, "profile_id");
|
||||
if (!cur) {
|
||||
return true;
|
||||
}
|
||||
char num[24] = "";
|
||||
if (cJSON_IsNumber(pid)) {
|
||||
snprintf(num, sizeof(num), "%d", (int)pid->valuedouble);
|
||||
}
|
||||
return (cJSON_IsString(pid) && strcmp(pid->valuestring, cur) == 0) || strcmp(num, cur) == 0;
|
||||
}
|
||||
|
||||
static void merge(cJSON *dst, cJSON *src)
|
||||
{
|
||||
cJSON *it;
|
||||
cJSON_ArrayForEach(it, src)
|
||||
{
|
||||
if (strcmp(it->string, "id") == 0) {
|
||||
continue;
|
||||
}
|
||||
cJSON *copy = cJSON_Duplicate(it, true);
|
||||
if (cJSON_GetObjectItem(dst, it->string)) {
|
||||
cJSON_ReplaceItemInObject(dst, it->string, copy);
|
||||
} else {
|
||||
cJSON_AddItemToObject(dst, it->string, copy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static esp_err_t send_message(httpd_req_t *req, const char *status, const char *msg)
|
||||
{
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "message", msg);
|
||||
return send_json(req, status, o, true);
|
||||
}
|
||||
|
||||
static esp_err_t result(httpd_req_t *req, esp_err_t err, const char *ok_msg)
|
||||
{
|
||||
switch (err) {
|
||||
case ESP_OK:
|
||||
return send_message(req, "200 OK", ok_msg);
|
||||
case ESP_ERR_NOT_FOUND:
|
||||
return send_error(req, "404 Not Found", "not found");
|
||||
case ESP_ERR_INVALID_SIZE:
|
||||
return send_error(req, "413 Payload Too Large", "preset too large for one ESP-NOW frame");
|
||||
default:
|
||||
return send_error(req, "503 Service Unavailable", "send failed");
|
||||
}
|
||||
}
|
||||
|
||||
static esp_err_t not_implemented(httpd_req_t *req, const char *what)
|
||||
{
|
||||
char msg[96];
|
||||
snprintf(msg, sizeof(msg), "%s is not implemented in v2 yet", what);
|
||||
return send_error(req, "501 Not Implemented", msg);
|
||||
}
|
||||
|
||||
static esp_err_t handle_profile_action(httpd_req_t *req, const char *id, const char *action)
|
||||
{
|
||||
if (strcmp(action, "apply") == 0) {
|
||||
if (!cJSON_GetObjectItem(store_coll("profile"), id)) {
|
||||
return send_error(req, "404 Not Found", "profile not found");
|
||||
}
|
||||
cJSON *st = store_settings();
|
||||
cJSON_DeleteItemFromObject(st, "current_profile_id");
|
||||
cJSON_AddStringToObject(st, "current_profile_id", id);
|
||||
store_save("settings");
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "message", "Profile applied");
|
||||
return send_json(req, "200 OK", o, true);
|
||||
}
|
||||
return not_implemented(req, action);
|
||||
}
|
||||
|
||||
static esp_err_t collection_handler_inner(httpd_req_t *req)
|
||||
{
|
||||
char seg[3][64];
|
||||
int n = split_path(req->uri, seg);
|
||||
const char *coll = n ? coll_for(seg[0]) : NULL;
|
||||
if (!coll) {
|
||||
return send_error(req, "404 Not Found", "unknown resource");
|
||||
}
|
||||
const bool is_presets = strcmp(coll, "preset") == 0;
|
||||
const bool is_profiles = strcmp(coll, "profile") == 0;
|
||||
cJSON *all = store_coll(coll);
|
||||
const int method = req->method;
|
||||
|
||||
// GET /devices/status: per-driver delivery health from the acked link
|
||||
if (n == 2 && method == HTTP_GET && !strcmp(seg[0], "devices") && !strcmp(seg[1], "status")) {
|
||||
cJSON *o = cJSON_CreateObject(), *d;
|
||||
cJSON_ArrayForEach(d, all)
|
||||
{
|
||||
const cJSON *addr = cJSON_GetObjectItem(d, "address");
|
||||
const char *hex = (cJSON_IsString(addr) && strlen(addr->valuestring) == 12) ? addr->valuestring
|
||||
: (strlen(d->string) == 12 ? d->string : NULL);
|
||||
uint8_t mac[6];
|
||||
unsigned v[6];
|
||||
if (hex && sscanf(hex, "%2x%2x%2x%2x%2x%2x", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5]) == 6) {
|
||||
for (int i = 0; i < 6; i++) {
|
||||
mac[i] = v[i];
|
||||
}
|
||||
int fails;
|
||||
int age = rel_peer_status(mac, &fails);
|
||||
cJSON *e = cJSON_AddObjectToObject(o, d->string);
|
||||
cJSON_AddNumberToObject(e, "last_ack_ms_ago", age);
|
||||
cJSON_AddNumberToObject(e, "failed_messages", fails);
|
||||
}
|
||||
}
|
||||
return send_json(req, "200 OK", o, true);
|
||||
}
|
||||
// /<res>/<id>/<action>
|
||||
if (n == 3 && !strcmp(seg[0], "zones") && !strcmp(seg[1], "engine") && !strcmp(seg[2], "status")) {
|
||||
return send_json(req, "200 OK", engine_status(), true);
|
||||
}
|
||||
if (n == 3 && method == HTTP_POST && !strcmp(seg[0], "zones")) {
|
||||
if (!strcmp(seg[2], "play")) {
|
||||
cJSON *body = read_body(req);
|
||||
if (!body) {
|
||||
return ESP_OK;
|
||||
}
|
||||
const cJSON *pid = cJSON_GetObjectItem(body, "preset_id");
|
||||
const cJSON *drv = cJSON_GetObjectItem(body, "drivers");
|
||||
char key[24] = "";
|
||||
if (cJSON_IsString(pid)) {
|
||||
snprintf(key, sizeof(key), "%s", pid->valuestring);
|
||||
} else if (cJSON_IsNumber(pid)) {
|
||||
snprintf(key, sizeof(key), "%d", (int)pid->valuedouble);
|
||||
}
|
||||
// The UI sends drivers:false when it pushes to drivers itself; v2 has no pixel outputs
|
||||
bool skip = cJSON_IsFalse(drv);
|
||||
cJSON_Delete(body);
|
||||
if (!key[0]) {
|
||||
return send_error(req, "400 Bad Request", "preset_id required");
|
||||
}
|
||||
return result(req, skip ? ESP_OK : engine_play(seg[1], key), "Playing");
|
||||
}
|
||||
if (!strcmp(seg[2], "stop")) {
|
||||
return result(req, engine_stop(seg[1]), "Stopped");
|
||||
}
|
||||
}
|
||||
if (n == 3 && method == HTTP_POST && !strcmp(seg[0], "sequences")) {
|
||||
if (!strcmp(seg[2], "play")) {
|
||||
return result(req, engine_seq_play(seg[1]), "Sequence started");
|
||||
}
|
||||
if (!strcmp(seg[2], "stop")) {
|
||||
return result(req, engine_seq_stop(seg[1]), "Sequence stopped");
|
||||
}
|
||||
}
|
||||
if (n == 3 && method == HTTP_POST && !strcmp(seg[0], "scenes")) {
|
||||
if (!strcmp(seg[2], "play")) {
|
||||
return result(req, engine_scene_play(seg[1]), "Scene started");
|
||||
}
|
||||
if (!strcmp(seg[2], "stop")) {
|
||||
return result(req, engine_scene_stop(seg[1]), "Scene stopped");
|
||||
}
|
||||
}
|
||||
if (n == 2 && method == HTTP_GET && !strcmp(seg[0], "sequences") && !strcmp(seg[1], "status")) {
|
||||
return send_json(req, "200 OK", engine_status(), true);
|
||||
}
|
||||
if (n == 3) {
|
||||
if (is_profiles && method == HTTP_POST) {
|
||||
return handle_profile_action(req, seg[1], seg[2]);
|
||||
}
|
||||
return not_implemented(req, seg[2]);
|
||||
}
|
||||
// /presets/send, /presets/push
|
||||
if (is_presets && n == 2 && method == HTTP_POST && !strcmp(seg[1], "push")) {
|
||||
cJSON *body = read_body(req);
|
||||
if (!body) {
|
||||
return ESP_OK;
|
||||
}
|
||||
const cJSON *seq = cJSON_GetObjectItem(body, "sequence");
|
||||
const cJSON *payload = cJSON_GetObjectItem(body, "payload");
|
||||
cJSON *one = NULL;
|
||||
if (!cJSON_IsArray(seq) && payload) {
|
||||
one = cJSON_CreateArray();
|
||||
cJSON_AddItemReferenceToArray(one, (cJSON *)payload);
|
||||
seq = one;
|
||||
}
|
||||
esp_err_t err = ESP_ERR_INVALID_ARG;
|
||||
if (cJSON_IsArray(seq) && cJSON_GetArraySize(seq)) {
|
||||
err = engine_push(seq, cJSON_GetObjectItem(body, "targets"));
|
||||
}
|
||||
cJSON_Delete(one);
|
||||
cJSON_Delete(body);
|
||||
return err == ESP_ERR_INVALID_ARG ? send_error(req, "400 Bad Request", "sequence or payload required")
|
||||
: result(req, err, "Delivered");
|
||||
}
|
||||
if (is_presets && n == 2 && method == HTTP_POST && !strcmp(seg[1], "send")) {
|
||||
cJSON *body = read_body(req);
|
||||
if (!body) {
|
||||
return ESP_OK;
|
||||
}
|
||||
const cJSON *ids = cJSON_GetObjectItem(body, "preset_ids");
|
||||
if (!cJSON_IsArray(ids)) {
|
||||
ids = cJSON_GetObjectItem(body, "ids");
|
||||
}
|
||||
if (!cJSON_IsArray(ids) || !cJSON_GetArraySize(ids)) {
|
||||
cJSON_Delete(body);
|
||||
return send_error(req, "400 Bad Request", "preset_ids must be a non-empty list");
|
||||
}
|
||||
const cJSON *save = cJSON_GetObjectItem(body, "save");
|
||||
const cJSON *def = cJSON_GetObjectItem(body, "default");
|
||||
char defbuf[24] = "";
|
||||
if (cJSON_IsString(def)) {
|
||||
snprintf(defbuf, sizeof(defbuf), "%s", def->valuestring);
|
||||
} else if (cJSON_IsNumber(def)) {
|
||||
snprintf(defbuf, sizeof(defbuf), "%d", (int)def->valuedouble);
|
||||
}
|
||||
const cJSON *targets = cJSON_GetObjectItem(body, "targets");
|
||||
cJSON *single = NULL;
|
||||
const cJSON *dest = cJSON_GetObjectItem(body, "destination_mac");
|
||||
if (!cJSON_IsArray(targets) && cJSON_IsString(dest)) {
|
||||
single = cJSON_CreateArray();
|
||||
cJSON_AddItemToArray(single, cJSON_CreateString(dest->valuestring));
|
||||
targets = single;
|
||||
}
|
||||
int sent = 0;
|
||||
esp_err_t err = engine_send_presets(ids, !save || cJSON_IsTrue(save), defbuf[0] ? defbuf : NULL, targets, &sent);
|
||||
cJSON_Delete(single);
|
||||
cJSON_Delete(body);
|
||||
if (err != ESP_OK) {
|
||||
return result(req, err, "");
|
||||
}
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "message", "Presets sent");
|
||||
cJSON_AddNumberToObject(o, "presets_sent", sent);
|
||||
return send_json(req, "200 OK", o, true);
|
||||
}
|
||||
|
||||
// "current" profile aliases
|
||||
const char *id = n == 2 ? seg[1] : NULL;
|
||||
if (is_profiles && id && strcmp(id, "current") == 0) {
|
||||
id = current_profile();
|
||||
if (!id) {
|
||||
return send_error(req, "404 Not Found", "no profiles");
|
||||
}
|
||||
if (method == HTTP_GET) {
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "id", id);
|
||||
cJSON_AddItemReferenceToObject(o, "profile", cJSON_GetObjectItem(all, id));
|
||||
return send_json(req, "200 OK", o, true);
|
||||
}
|
||||
}
|
||||
|
||||
if (!id) {
|
||||
if (method == HTTP_GET) {
|
||||
if (is_profiles) {
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddItemReferenceToObject(o, "profiles", all);
|
||||
const char *cur = current_profile();
|
||||
cJSON_AddStringToObject(o, "current_profile_id", cur ? cur : "");
|
||||
return send_json(req, "200 OK", o, true);
|
||||
}
|
||||
if (is_presets) {
|
||||
cJSON *o = cJSON_CreateObject(), *it;
|
||||
cJSON_ArrayForEach(it, all)
|
||||
{
|
||||
if (preset_in_profile(it)) {
|
||||
cJSON_AddItemReferenceToObject(o, it->string, it);
|
||||
}
|
||||
}
|
||||
return send_json(req, "200 OK", o, true);
|
||||
}
|
||||
return send_json(req, "200 OK", all, false);
|
||||
}
|
||||
if (method == HTTP_POST) {
|
||||
cJSON *body = read_body(req);
|
||||
if (!body) {
|
||||
return ESP_OK;
|
||||
}
|
||||
char nid[16];
|
||||
store_next_id(coll, nid, sizeof(nid));
|
||||
cJSON_AddStringToObject(body, "id", nid);
|
||||
if (is_presets && current_profile() && !cJSON_GetObjectItem(body, "profile_id")) {
|
||||
cJSON_AddStringToObject(body, "profile_id", current_profile());
|
||||
}
|
||||
cJSON_AddItemToObject(all, nid, body);
|
||||
store_save(coll);
|
||||
if (!strcmp(coll, "zone") || !strcmp(coll, "device")) {
|
||||
engine_groups_changed();
|
||||
}
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddItemReferenceToObject(o, nid, body);
|
||||
return send_json(req, "201 Created", o, true);
|
||||
}
|
||||
return send_error(req, "405 Method Not Allowed", "method not allowed");
|
||||
}
|
||||
|
||||
cJSON *rec = cJSON_GetObjectItem(all, id);
|
||||
if (!rec || (is_presets && !preset_in_profile(rec))) {
|
||||
return send_error(req, "404 Not Found", "not found");
|
||||
}
|
||||
switch (method) {
|
||||
case HTTP_GET:
|
||||
return send_json(req, "200 OK", rec, false);
|
||||
case HTTP_PUT: {
|
||||
cJSON *body = read_body(req);
|
||||
if (!body) {
|
||||
return ESP_OK;
|
||||
}
|
||||
merge(rec, body);
|
||||
cJSON_Delete(body);
|
||||
store_save(coll);
|
||||
if (!strcmp(coll, "zone") || !strcmp(coll, "device")) {
|
||||
engine_groups_changed();
|
||||
}
|
||||
return send_json(req, "200 OK", rec, false);
|
||||
}
|
||||
case HTTP_DELETE: {
|
||||
cJSON_DeleteItemFromObject(all, id);
|
||||
store_save(coll);
|
||||
if (!strcmp(coll, "zone") || !strcmp(coll, "device")) {
|
||||
engine_groups_changed();
|
||||
}
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "message", "Deleted");
|
||||
return send_json(req, "200 OK", o, true);
|
||||
}
|
||||
default:
|
||||
return send_error(req, "405 Method Not Allowed", "method not allowed");
|
||||
}
|
||||
}
|
||||
|
||||
static esp_err_t settings_handler_inner(httpd_req_t *req)
|
||||
{
|
||||
char seg[3][64];
|
||||
int n = split_path(req->uri, seg);
|
||||
if (n == 2 && strcmp(seg[1], "page") == 0 && req->method == HTTP_GET) {
|
||||
return web_send_page(req, "settings.html");
|
||||
}
|
||||
if (n == 1 && req->method == HTTP_GET) {
|
||||
return send_json(req, "200 OK", store_settings(), false);
|
||||
}
|
||||
if (n == 2 && strcmp(seg[1], "settings") == 0 && req->method == HTTP_PUT) {
|
||||
cJSON *body = read_body(req);
|
||||
if (!body) {
|
||||
return ESP_OK;
|
||||
}
|
||||
merge(store_settings(), body);
|
||||
cJSON_Delete(body);
|
||||
store_save("settings");
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "message", "Settings updated successfully");
|
||||
return send_json(req, "200 OK", o, true);
|
||||
}
|
||||
return not_implemented(req, "this settings route");
|
||||
}
|
||||
|
||||
// GET /db/<name> exports a collection, PUT /db/<name> replaces it (import of the Pi's db/*.json)
|
||||
static esp_err_t db_handler_inner(httpd_req_t *req)
|
||||
{
|
||||
char seg[3][64];
|
||||
int n = split_path(req->uri, seg);
|
||||
if (n != 2 || !store_known(seg[1])) {
|
||||
return send_error(req, "404 Not Found", "unknown collection");
|
||||
}
|
||||
if (req->method == HTTP_GET) {
|
||||
return send_json(req, "200 OK", store_coll(seg[1]), false);
|
||||
}
|
||||
if (req->method == HTTP_PUT) {
|
||||
cJSON *body = read_body(req);
|
||||
if (!body) {
|
||||
return ESP_OK;
|
||||
}
|
||||
if (store_replace(seg[1], body) != ESP_OK) {
|
||||
return send_error(req, "500 Internal Server Error", "save failed");
|
||||
}
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddNumberToObject(o, "records", cJSON_GetArraySize(store_coll(seg[1])));
|
||||
return send_json(req, "200 OK", o, true);
|
||||
}
|
||||
return send_error(req, "405 Method Not Allowed", "method not allowed");
|
||||
}
|
||||
|
||||
#define LOCKED(name) \
|
||||
static esp_err_t name(httpd_req_t *req) \
|
||||
{ \
|
||||
store_lock(); \
|
||||
esp_err_t r = name##_inner(req); \
|
||||
store_unlock(); \
|
||||
return r; \
|
||||
}
|
||||
LOCKED(collection_handler)
|
||||
LOCKED(settings_handler)
|
||||
LOCKED(db_handler)
|
||||
|
||||
// Bench tests: /test/loss and /test/beats
|
||||
static esp_err_t test_handler_inner(httpd_req_t *req)
|
||||
{
|
||||
char seg[3][64];
|
||||
int n = split_path(req->uri, seg);
|
||||
if (n >= 2 && !strcmp(seg[1], "loss")) {
|
||||
if (req->method == HTTP_POST) {
|
||||
cJSON *b = read_body(req);
|
||||
if (!b) {
|
||||
return ESP_OK;
|
||||
}
|
||||
const cJSON *p = cJSON_GetObjectItem(b, "percent"), *beats = cJSON_GetObjectItem(b, "beats");
|
||||
espnow_tx_set_loss(cJSON_IsNumber(p) ? (int)p->valuedouble : 0, !cJSON_IsFalse(beats));
|
||||
cJSON_Delete(b);
|
||||
}
|
||||
bool inc;
|
||||
int pct = espnow_tx_loss(&inc);
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddNumberToObject(o, "percent", pct);
|
||||
cJSON_AddBoolToObject(o, "beats", inc);
|
||||
return send_json(req, "200 OK", o, true);
|
||||
}
|
||||
if (n >= 2 && !strcmp(seg[1], "beats")) {
|
||||
if (req->method == HTTP_POST && n == 3 && !strcmp(seg[2], "stop")) {
|
||||
bench_stop();
|
||||
} else if (req->method == HTTP_POST) {
|
||||
cJSON *b = read_body(req);
|
||||
if (!b) {
|
||||
return ESP_OK;
|
||||
}
|
||||
const cJSON *bpm = cJSON_GetObjectItem(b, "bpm"), *count = cJSON_GetObjectItem(b, "count");
|
||||
esp_err_t err = bench_start(cJSON_IsNumber(bpm) ? (float)bpm->valuedouble : 120,
|
||||
cJSON_IsNumber(count) ? (int)count->valuedouble : 100);
|
||||
cJSON_Delete(b);
|
||||
if (err != ESP_OK) {
|
||||
return send_error(req, "400 Bad Request", "bpm must be 30-300");
|
||||
}
|
||||
}
|
||||
return send_json(req, "200 OK", bench_results(), true);
|
||||
}
|
||||
return send_error(req, "404 Not Found", "unknown test");
|
||||
}
|
||||
LOCKED(test_handler)
|
||||
|
||||
esp_err_t api_register(httpd_handle_t server)
|
||||
{
|
||||
static const char *const ROUTES[] = {
|
||||
"/devices*", "/zones*", "/presets*", "/profiles*", "/palettes*",
|
||||
"/patterns*", "/sequences*", "/scenes*", "/groups*", "/outputs*",
|
||||
};
|
||||
static const httpd_method_t METHODS[] = { HTTP_GET, HTTP_POST, HTTP_PUT, HTTP_DELETE };
|
||||
for (size_t r = 0; r < sizeof(ROUTES) / sizeof(ROUTES[0]); r++) {
|
||||
for (size_t m = 0; m < 4; m++) {
|
||||
httpd_uri_t u = { .uri = ROUTES[r], .method = METHODS[m], .handler = collection_handler };
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &u));
|
||||
}
|
||||
}
|
||||
for (size_t m = 0; m < 4; m++) {
|
||||
httpd_uri_t t = { .uri = "/test/*", .method = METHODS[m], .handler = test_handler };
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &t));
|
||||
}
|
||||
for (size_t m = 0; m < 4; m++) {
|
||||
httpd_uri_t s = { .uri = "/settings*", .method = METHODS[m], .handler = settings_handler };
|
||||
httpd_uri_t d = { .uri = "/db/*", .method = METHODS[m], .handler = db_handler };
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &s));
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &d));
|
||||
}
|
||||
ESP_LOGI(TAG, "API registered");
|
||||
return ESP_OK;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "esp_err.h"
|
||||
#include "esp_http_server.h"
|
||||
|
||||
// Register the JSON API (CRUD over the store collections, profiles, settings,
|
||||
// /db import and export). Actions that need the engine answer 501 for now.
|
||||
esp_err_t api_register(httpd_handle_t server);
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
/*
|
||||
* Beat detection glue: runs beat_dsp on the mic feed, pulses the beat LED
|
||||
* (longer on the downbeat), keeps the latest tempo and bar position for
|
||||
* /status and fans events out to SSE listeners.
|
||||
*/
|
||||
#include <math.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/queue.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_check.h"
|
||||
#include "esp_timer.h"
|
||||
#include "driver/gpio.h"
|
||||
#include "beat_dsp.h"
|
||||
#include "beat.h"
|
||||
|
||||
#define MAX_SUBSCRIBERS 4
|
||||
#define LOG_EVERY_BEATS 64
|
||||
|
||||
static const char *TAG = "beat";
|
||||
|
||||
static beat_dsp_t s_dsp; // ~10 KB, too big for the mic task's stack
|
||||
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
|
||||
static beat_info_t s_info;
|
||||
// Queue sends may yield, so the subscriber list gets a mutex, not s_lock
|
||||
static SemaphoreHandle_t s_subs_mutex;
|
||||
static QueueHandle_t s_subs[MAX_SUBSCRIBERS];
|
||||
static esp_timer_handle_t s_led_timer;
|
||||
static bool s_was_locked;
|
||||
static int64_t s_tap_us; // pending tap time, 0 if none (guarded by s_lock)
|
||||
|
||||
static void led_set(bool on)
|
||||
{
|
||||
#if CONFIG_BEAT_LED_GPIO >= 0
|
||||
#if CONFIG_BEAT_LED_ACTIVE_LOW
|
||||
on = !on;
|
||||
#endif
|
||||
gpio_set_level(CONFIG_BEAT_LED_GPIO, on);
|
||||
#endif
|
||||
}
|
||||
|
||||
static void led_off_cb(void *arg)
|
||||
{
|
||||
led_set(false);
|
||||
}
|
||||
|
||||
static beat_cb_t s_cb;
|
||||
|
||||
void beat_set_callback(beat_cb_t cb)
|
||||
{
|
||||
s_cb = cb;
|
||||
}
|
||||
|
||||
static void publish(beat_event_t ev)
|
||||
{
|
||||
xSemaphoreTake(s_subs_mutex, portMAX_DELAY);
|
||||
for (int i = 0; i < MAX_SUBSCRIBERS; i++) {
|
||||
if (s_subs[i]) {
|
||||
// A slow listener just misses events rather than stalling audio
|
||||
xQueueSend(s_subs[i], &ev, 0);
|
||||
}
|
||||
}
|
||||
xSemaphoreGive(s_subs_mutex);
|
||||
}
|
||||
|
||||
static void dsp_event(void *ctx, int events, const beat_dsp_t *d)
|
||||
{
|
||||
int64_t now = esp_timer_get_time();
|
||||
beat_info_t info;
|
||||
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
if (events & BEAT_EV_ONSET) {
|
||||
s_info.onset_count++;
|
||||
s_info.last_onset_us = now;
|
||||
}
|
||||
if (events & BEAT_EV_BEAT) {
|
||||
s_info.beat_count++;
|
||||
s_info.last_beat_us = now;
|
||||
s_info.meter = d->meter;
|
||||
s_info.bar_beat = d->bar_beat;
|
||||
s_info.bar_sure = d->bar_sure;
|
||||
}
|
||||
if (events & BEAT_EV_DOWNBEAT) {
|
||||
s_info.downbeat_count++;
|
||||
}
|
||||
info = s_info;
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
|
||||
if (events & BEAT_EV_ONSET) {
|
||||
publish(BEAT_EVENT_ONSET);
|
||||
}
|
||||
if (events & BEAT_EV_BEAT) {
|
||||
if (s_cb) {
|
||||
s_cb(&info, beat_dsp_bpm(d), (events & BEAT_EV_DOWNBEAT) != 0);
|
||||
}
|
||||
led_set(true);
|
||||
esp_timer_stop(s_led_timer);
|
||||
int pulse_ms = events & BEAT_EV_DOWNBEAT ? CONFIG_BEAT_LED_DOWNBEAT_MS : CONFIG_BEAT_LED_PULSE_MS;
|
||||
esp_timer_start_once(s_led_timer, pulse_ms * 1000);
|
||||
publish(BEAT_EVENT_BEAT);
|
||||
if (info.beat_count % LOG_EVERY_BEATS == 0) {
|
||||
ESP_LOGI(TAG, "%.1f BPM, confidence %.2f, %lu beats, %d/4 time, bar contrast %.2f",
|
||||
beat_dsp_bpm(d), d->confidence, (unsigned long)info.beat_count, d->meter, d->bar_contrast);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t beat_start(float sample_rate)
|
||||
{
|
||||
float gate_rms = powf(10.0f, CONFIG_BEAT_GATE_DBFS / 20.0f);
|
||||
beat_dsp_init(&s_dsp, sample_rate, gate_rms, CONFIG_BEAT_LEAD_MS / 1000.0f);
|
||||
s_info.meter = s_dsp.meter;
|
||||
s_subs_mutex = xSemaphoreCreateMutex();
|
||||
ESP_RETURN_ON_FALSE(s_subs_mutex, ESP_ERR_NO_MEM, TAG, "Mutex alloc failed");
|
||||
|
||||
#if CONFIG_BEAT_LED_GPIO >= 0
|
||||
gpio_config_t io = {
|
||||
.pin_bit_mask = 1ULL << CONFIG_BEAT_LED_GPIO,
|
||||
.mode = GPIO_MODE_OUTPUT,
|
||||
};
|
||||
ESP_RETURN_ON_ERROR(gpio_config(&io), TAG, "LED GPIO config failed");
|
||||
#endif
|
||||
led_set(false);
|
||||
const esp_timer_create_args_t timer_args = { .callback = led_off_cb, .name = "beat_led" };
|
||||
ESP_RETURN_ON_ERROR(esp_timer_create(&timer_args, &s_led_timer), TAG, "LED timer create failed");
|
||||
ESP_LOGI(TAG, "Beat detection on, %.1f onset frames/s, gate %d dBFS",
|
||||
s_dsp.frame_rate, CONFIG_BEAT_GATE_DBFS);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void beat_tap(void)
|
||||
{
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
s_tap_us = esp_timer_get_time();
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
}
|
||||
|
||||
void beat_feed(const float *x, size_t n)
|
||||
{
|
||||
beat_dsp_feed(&s_dsp, x, n, dsp_event, NULL);
|
||||
|
||||
// Taps arrive from the HTTP task; apply them here, in the detector's task
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
int64_t tap_us = s_tap_us;
|
||||
s_tap_us = 0;
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
if (tap_us) {
|
||||
// The newest analysed frame is ~30 ms behind real time (capture block
|
||||
// plus half the FFT window), so the tap is that much further back
|
||||
float ago_s = (esp_timer_get_time() - tap_us) / 1e6f + 0.03f;
|
||||
beat_dsp_tap(&s_dsp, ago_s * s_dsp.frame_rate);
|
||||
ESP_LOGI(TAG, "Tap: beat 1 set, holding the bar for a while");
|
||||
}
|
||||
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
s_info.bpm = beat_dsp_bpm(&s_dsp);
|
||||
s_info.confidence = s_dsp.confidence;
|
||||
s_info.locked = s_dsp.locked;
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
|
||||
if (s_dsp.locked != s_was_locked) {
|
||||
s_was_locked = s_dsp.locked;
|
||||
if (s_was_locked) {
|
||||
ESP_LOGI(TAG, "Locked at %.1f BPM (confidence %.2f)", beat_dsp_bpm(&s_dsp), s_dsp.confidence);
|
||||
} else {
|
||||
ESP_LOGI(TAG, "Lost the beat");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void beat_get_info(beat_info_t *out)
|
||||
{
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
*out = s_info;
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
}
|
||||
|
||||
esp_err_t beat_subscribe(QueueHandle_t q)
|
||||
{
|
||||
esp_err_t ret = ESP_ERR_NO_MEM;
|
||||
xSemaphoreTake(s_subs_mutex, portMAX_DELAY);
|
||||
for (int i = 0; i < MAX_SUBSCRIBERS; i++) {
|
||||
if (!s_subs[i]) {
|
||||
s_subs[i] = q;
|
||||
ret = ESP_OK;
|
||||
break;
|
||||
}
|
||||
}
|
||||
xSemaphoreGive(s_subs_mutex);
|
||||
return ret;
|
||||
}
|
||||
|
||||
void beat_unsubscribe(QueueHandle_t q)
|
||||
{
|
||||
// Once this returns the queue is no longer touched and can be deleted
|
||||
xSemaphoreTake(s_subs_mutex, portMAX_DELAY);
|
||||
for (int i = 0; i < MAX_SUBSCRIBERS; i++) {
|
||||
if (s_subs[i] == q) {
|
||||
s_subs[i] = NULL;
|
||||
}
|
||||
}
|
||||
xSemaphoreGive(s_subs_mutex);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "esp_err.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/queue.h"
|
||||
|
||||
typedef struct {
|
||||
float bpm; // 0 until a tempo has been found
|
||||
float confidence; // 0..1, how periodic the onsets are
|
||||
bool locked; // beats are being emitted
|
||||
uint32_t beat_count;
|
||||
int64_t last_beat_us; // esp_timer time of the last beat, 0 if none
|
||||
int meter; // beats per bar, 3 or 4
|
||||
int bar_beat; // 1..meter of the last beat (best guess), 0 early on
|
||||
bool bar_sure; // bar_beat is reliable, downbeats are being flashed
|
||||
uint32_t downbeat_count;
|
||||
uint32_t onset_count;
|
||||
int64_t last_onset_us;
|
||||
} beat_info_t;
|
||||
|
||||
// Event codes posted to subscriber queues
|
||||
typedef enum {
|
||||
BEAT_EVENT_ONSET,
|
||||
BEAT_EVENT_BEAT,
|
||||
} beat_event_t;
|
||||
|
||||
// Set up the detector and beat LED; call before feeding audio
|
||||
esp_err_t beat_start(float sample_rate);
|
||||
|
||||
// Feed DC-free mono samples at full scale +/-1 (called from the mic task)
|
||||
void beat_feed(const float *x, size_t n);
|
||||
|
||||
void beat_get_info(beat_info_t *out);
|
||||
|
||||
// The user tapped beat 1 just now: correct the bar position to match
|
||||
void beat_tap(void);
|
||||
|
||||
// Have beat_event_t values posted (without blocking) to a queue of
|
||||
// beat_event_t. Returns ESP_ERR_NO_MEM when all subscriber slots are taken.
|
||||
esp_err_t beat_subscribe(QueueHandle_t q);
|
||||
void beat_unsubscribe(QueueHandle_t q);
|
||||
|
||||
// Called from the audio task the moment a beat is emitted, before any queue
|
||||
// fan-out, so the radio can send it with minimal delay. Must not block.
|
||||
typedef void (*beat_cb_t)(const beat_info_t *info, float bpm, bool downbeat);
|
||||
void beat_set_callback(beat_cb_t cb);
|
||||
@@ -0,0 +1,532 @@
|
||||
/*
|
||||
* Realtime beat tracker.
|
||||
*
|
||||
* 1. Onsets: every 16 ms, Hann-windowed 512-point FFT; novelty is the
|
||||
* half-wave rectified rise in log magnitude (spectral flux) plus the rise
|
||||
* in bass power. Log flux catches every instrument but rates a faint hat
|
||||
* like a loud kick; the uncompressed bass term keeps the kick on the beat.
|
||||
* 2. Tempo: every ~0.5 s, autocorrelate the last ~8 s of log flux alone
|
||||
* (bass would pull rock with kicks on 1 and 3 to half time), weight
|
||||
* lags with a log-normal prior around 120 BPM, and add the 2x lag so the
|
||||
* bar-level pulse backs up the beat. A new tempo has to clearly beat the
|
||||
* current one, several times in a row, before it is taken.
|
||||
* 3. Phase: every frame, find the offset whose comb of past beat positions
|
||||
* collects the most novelty. When that offset wraps back to zero a beat is
|
||||
* due, so beats keep coming through quiet bars instead of only on onsets.
|
||||
* 4. Lock: beats only go out while autocorrelation confidence times phase
|
||||
* salience (on-grid vs. average onset energy) is high. Speech and noise
|
||||
* can score on one of them but not both. Tuned on real music clips.
|
||||
* 5. Bar: each grid beat gets two downbeat cues, the bass hit on it and how
|
||||
* much new spectral energy its beat brings over the one before (chords
|
||||
* change on the one). Cues are averaged per bar position
|
||||
* for 3/4 and 4/4; the meter whose positions differ most wins, and its
|
||||
* strongest position is the downbeat.
|
||||
*/
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "beat_dsp.h"
|
||||
|
||||
#define NV_MASK (BEAT_NV_LEN - 1)
|
||||
#define FLUX_MAX_BIN 192 // ~6 kHz; above that is mostly hats and hiss
|
||||
#define BASS_MAX_BIN 6 // <~190 Hz, kick drums
|
||||
#define BASS_WEIGHT 1.0f // bass power rise vs. full-band log flux
|
||||
#define LOG_GAMMA 100.0f // log(1 + g*|X|) compression
|
||||
#define TEMPO_EVERY 32 // frames between tempo estimates
|
||||
#define TEMPO_MIN_EXTRA 128 // history beyond the longest lag before estimating
|
||||
#define PRIOR_BPM 120.0f
|
||||
#define PRIOR_OCTAVES 1.0f // std dev of the tempo prior
|
||||
#define TEMPO_TOL 0.06f // relative change treated as the same tempo
|
||||
#define TEMPO_MEMORY_S 3.0f // time constant of the history fade
|
||||
#define TEMPO_MARGIN 1.5f // a new tempo must score this much better
|
||||
#define TEMPO_SWITCH 3 // estimates in a row needed to jump tempo
|
||||
#define COMB_BEATS 6 // past beats the phase comb looks at
|
||||
#define COMB_DECAY 0.88f
|
||||
#define PHASE_STICK 1.3f // bonus for the phase that follows on
|
||||
#define LOCK_STRENGTH 0.9f // confidence x salience to start emitting beats
|
||||
#define UNLOCK_STRENGTH 0.5f // ...and to keep going
|
||||
#define ONSET_K 1.5f // onset threshold, x running novelty mean
|
||||
#define ONSET_GAP_S 0.1f
|
||||
#define SALIENCE_S 2.0f // smoothing of the on-beat energy ratio
|
||||
#define ACTIVE_HOLD_S 2.0f // keep beating this long into silence
|
||||
#define KICK_WEIGHT 1.0f // downbeat cue: bass hit on the beat
|
||||
#define CHANGE_WEIGHT 1.0f // downbeat cue: spectral change into the beat
|
||||
#define SPAN_FRAC 1.0f // part of each beat compared for harmonic change
|
||||
#define BAR_RATE 0.08f // per-bar update rate of the position scores
|
||||
#define BAR_MARGIN 1.1f // a new downbeat position must score this much more
|
||||
#define METER_MARGIN 1.5f // ...and a new meter must stand out this much more
|
||||
#define METER3_BIAS 0.5f // weight on the 3/4 evidence
|
||||
#define BAR_SURE_ON 0.3f // contrast to call the bar position sure
|
||||
#define BAR_SURE_OFF 0.2f // ...and to stop
|
||||
#define BAR_WARMUP 8 // grid beats before guessing a bar position
|
||||
#define TAP_BOOST 2.0f // head start for a tapped beat 1, x the best score
|
||||
#define TAP_HOLD_BARS 16 // bars a tap holds the bar position
|
||||
|
||||
static float s_window[BEAT_FFT_SIZE];
|
||||
static float s_cos[BEAT_FFT_SIZE / 2], s_sin[BEAT_FFT_SIZE / 2];
|
||||
static uint16_t s_bitrev[BEAT_FFT_SIZE];
|
||||
static int8_t s_band[FLUX_MAX_BIN + 1]; // bin -> band, -1 if unused
|
||||
static float s_band_w[BEAT_BANDS]; // 1 / bins in band
|
||||
static const int s_meters[BEAT_METERS] = {3, 4};
|
||||
static bool s_tables_ready;
|
||||
|
||||
static void init_tables(void)
|
||||
{
|
||||
if (s_tables_ready) {
|
||||
return;
|
||||
}
|
||||
const int n = BEAT_FFT_SIZE;
|
||||
int bits = 0;
|
||||
while ((1 << bits) < n) {
|
||||
bits++;
|
||||
}
|
||||
for (int i = 0; i < n; i++) {
|
||||
s_window[i] = 0.5f - 0.5f * cosf(2.0f * (float)M_PI * i / n);
|
||||
int r = 0;
|
||||
for (int b = 0; b < bits; b++) {
|
||||
r |= ((i >> b) & 1) << (bits - 1 - b);
|
||||
}
|
||||
s_bitrev[i] = r;
|
||||
}
|
||||
for (int i = 0; i < n / 2; i++) {
|
||||
s_cos[i] = cosf(2.0f * (float)M_PI * i / n);
|
||||
s_sin[i] = -sinf(2.0f * (float)M_PI * i / n);
|
||||
}
|
||||
// Bands spaced evenly in log frequency from bin 2 (~60 Hz) up
|
||||
int count[BEAT_BANDS] = {0};
|
||||
for (int k = 0; k <= FLUX_MAX_BIN; k++) {
|
||||
int b = k < 2 ? -1 : (int)(BEAT_BANDS * logf(k / 2.0f) / logf(FLUX_MAX_BIN / 2.0f));
|
||||
s_band[k] = b < 0 ? -1 : b >= BEAT_BANDS ? BEAT_BANDS - 1 : b;
|
||||
if (s_band[k] >= 0) {
|
||||
count[s_band[k]]++;
|
||||
}
|
||||
}
|
||||
for (int b = 0; b < BEAT_BANDS; b++) {
|
||||
s_band_w[b] = count[b] ? 1.0f / count[b] : 0.0f;
|
||||
}
|
||||
s_tables_ready = true;
|
||||
}
|
||||
|
||||
// In-place iterative radix-2 complex FFT
|
||||
static void fft(float *re, float *im)
|
||||
{
|
||||
const int n = BEAT_FFT_SIZE;
|
||||
for (int i = 0; i < n; i++) {
|
||||
int j = s_bitrev[i];
|
||||
if (j > i) {
|
||||
float t = re[i]; re[i] = re[j]; re[j] = t;
|
||||
t = im[i]; im[i] = im[j]; im[j] = t;
|
||||
}
|
||||
}
|
||||
for (int len = 2; len <= n; len <<= 1) {
|
||||
int half = len >> 1, step = n / len;
|
||||
for (int start = 0; start < n; start += len) {
|
||||
for (int k = 0; k < half; k++) {
|
||||
float wr = s_cos[k * step], wi = s_sin[k * step];
|
||||
int a = start + k, b = a + half;
|
||||
float tr = re[b] * wr - im[b] * wi;
|
||||
float ti = re[b] * wi + im[b] * wr;
|
||||
re[b] = re[a] - tr; im[b] = im[a] - ti;
|
||||
re[a] += tr; im[a] += ti;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static inline float nv_at(const beat_dsp_t *d, uint32_t i)
|
||||
{
|
||||
return d->nv[i & NV_MASK];
|
||||
}
|
||||
|
||||
// Onsets can land a frame either side of the beat grid
|
||||
static inline float nv_max3(const beat_dsp_t *d, uint32_t i, uint32_t cur)
|
||||
{
|
||||
float v = fmaxf(nv_at(d, i), nv_at(d, i - 1));
|
||||
return i < cur ? fmaxf(v, nv_at(d, i + 1)) : v;
|
||||
}
|
||||
|
||||
void beat_dsp_init(beat_dsp_t *d, float sample_rate, float gate_rms, float lead_s)
|
||||
{
|
||||
init_tables();
|
||||
memset(d, 0, sizeof(*d));
|
||||
d->frame_rate = sample_rate / BEAT_HOP;
|
||||
d->gate_rms = gate_rms;
|
||||
d->lead_frames = (int)lrintf(lead_s * d->frame_rate);
|
||||
d->min_lag = (int)floorf(d->frame_rate * 60.0f / BEAT_MAX_BPM);
|
||||
d->max_lag = (int)ceilf(d->frame_rate * 60.0f / BEAT_MIN_BPM);
|
||||
// Start half a window in so the first frame comes after one hop
|
||||
d->in_fill = BEAT_FFT_SIZE - BEAT_HOP;
|
||||
d->meter = 4;
|
||||
}
|
||||
|
||||
static float onset_strength(beat_dsp_t *d, bool *active, float *tempo_nv, float *bass_nv)
|
||||
{
|
||||
float sum_sq = 0.0f;
|
||||
for (int i = 0; i < BEAT_FFT_SIZE; i++) {
|
||||
float x = d->in[i];
|
||||
sum_sq += x * x;
|
||||
d->re[i] = x * s_window[i];
|
||||
d->im[i] = 0.0f;
|
||||
}
|
||||
*active = sqrtf(sum_sq / BEAT_FFT_SIZE) >= d->gate_rms;
|
||||
fft(d->re, d->im);
|
||||
|
||||
float flux = 0.0f, bass = 0.0f;
|
||||
memset(d->band_now, 0, sizeof(d->band_now));
|
||||
for (int k = 1; k <= FLUX_MAX_BIN; k++) {
|
||||
float mag2 = d->re[k] * d->re[k] + d->im[k] * d->im[k];
|
||||
float l = log1pf(LOG_GAMMA * sqrtf(mag2));
|
||||
flux += fmaxf(l - d->prev_log[k], 0.0f);
|
||||
d->prev_log[k] = l;
|
||||
if (s_band[k] >= 0) {
|
||||
d->band_now[s_band[k]] += l * s_band_w[s_band[k]];
|
||||
}
|
||||
if (k <= BASS_MAX_BIN) {
|
||||
bass += mag2;
|
||||
}
|
||||
}
|
||||
float bass_rise = fmaxf(bass - d->prev_bass, 0.0f);
|
||||
d->prev_bass = bass;
|
||||
if (!*active) {
|
||||
flux = bass_rise = 0.0f;
|
||||
}
|
||||
|
||||
// Each channel minus its ~0.5 s running mean, so sustained texture
|
||||
// doesn't count, and over it, so neither channel's units dominate
|
||||
const float a = 1.0f / (0.5f * d->frame_rate);
|
||||
d->flux_mean += a * (flux - d->flux_mean);
|
||||
d->bass_mean += a * (bass_rise - d->bass_mean);
|
||||
float full = fmaxf(flux - d->flux_mean, 0.0f) / (d->flux_mean + 1e-6f);
|
||||
*tempo_nv = full;
|
||||
*bass_nv = fmaxf(bass_rise - d->bass_mean, 0.0f) / (d->bass_mean + 1e-12f);
|
||||
return full + BASS_WEIGHT * *bass_nv;
|
||||
}
|
||||
|
||||
static void estimate_tempo(beat_dsp_t *d)
|
||||
{
|
||||
int n = d->t < BEAT_NV_LEN ? (int)d->t : BEAT_NV_LEN;
|
||||
int top = 2 * (d->max_lag + 1);
|
||||
if (n < top + TEMPO_MIN_EXTRA || top >= BEAT_AC_LEN) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Oldest-first, mean-removed copy of the history (re[] is free here)
|
||||
float *x = d->re, mean = 0.0f;
|
||||
for (int i = 0; i < n; i++) {
|
||||
x[i] = d->tempo_nv[(d->t - n + i) & NV_MASK];
|
||||
mean += x[i];
|
||||
}
|
||||
mean /= n;
|
||||
// Fade older frames so a tempo change wins within a few seconds
|
||||
const float fade = expf(-1.0f / (TEMPO_MEMORY_S * d->frame_rate));
|
||||
float w = 1.0f;
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
x[i] = (x[i] - mean) * w;
|
||||
w *= fade;
|
||||
}
|
||||
for (int l = 0; l <= top; l++) {
|
||||
float s = 0.0f;
|
||||
for (int i = l; i < n; i++) {
|
||||
s += x[i] * x[i - l];
|
||||
}
|
||||
d->ac[l] = s / (n - l);
|
||||
}
|
||||
if (d->ac[0] <= 1e-9f) {
|
||||
d->confidence *= 0.5f;
|
||||
return;
|
||||
}
|
||||
|
||||
// score[l] for l in [min_lag-1, max_lag+1], kept in im[] for interpolation
|
||||
float *score = d->im;
|
||||
const float l0 = d->frame_rate * 60.0f / PRIOR_BPM;
|
||||
int best = d->min_lag;
|
||||
for (int l = d->min_lag - 1; l <= d->max_lag + 1; l++) {
|
||||
float o = log2f((float)l / l0) / PRIOR_OCTAVES;
|
||||
// The 2x lag backs up a beat but can't carry it: in 3/4, 2/3 of the
|
||||
// beat is barely periodic yet its double is a whole bar
|
||||
score[l] = expf(-0.5f * o * o) * (d->ac[l] + 0.5f * fminf(d->ac[2 * l], fmaxf(d->ac[l], 0.0f)));
|
||||
if (l >= d->min_lag && l <= d->max_lag && score[l] > score[best]) {
|
||||
best = l;
|
||||
}
|
||||
}
|
||||
// Hold the current tempo unless another clearly beats it; real music
|
||||
// often has a 3:2 or 2:1 alternative that is nearly as periodic
|
||||
if (d->period > 0.0f) {
|
||||
int lo = (int)fmaxf(floorf(d->period * (1.0f - TEMPO_TOL)), d->min_lag);
|
||||
int hi = (int)fminf(ceilf(d->period * (1.0f + TEMPO_TOL)), d->max_lag);
|
||||
int near = lo;
|
||||
for (int l = lo + 1; l <= hi; l++) {
|
||||
if (score[l] > score[near]) {
|
||||
near = l;
|
||||
}
|
||||
}
|
||||
if (score[near] > 0.0f && score[best] < TEMPO_MARGIN * score[near]) {
|
||||
best = near;
|
||||
}
|
||||
}
|
||||
float a = score[best - 1], b = score[best], c = score[best + 1];
|
||||
float denom = a - 2.0f * b + c;
|
||||
float period = best + (denom < 0.0f ? 0.5f * (a - c) / denom : 0.0f);
|
||||
float conf = fminf(fmaxf(d->ac[best] / d->ac[0], 0.0f), 1.0f);
|
||||
d->confidence += 0.3f * (conf - d->confidence);
|
||||
|
||||
if (d->period == 0.0f) {
|
||||
d->period = period; // tentative; locking decides whether beats go out
|
||||
} else if (fabsf(period / d->period - 1.0f) < TEMPO_TOL) {
|
||||
d->period += 0.2f * (period - d->period);
|
||||
d->pending_count = 0;
|
||||
} else if (d->pending_count > 0 && fabsf(period / d->pending_period - 1.0f) < TEMPO_TOL) {
|
||||
if (++d->pending_count >= TEMPO_SWITCH) {
|
||||
d->period = period;
|
||||
d->pending_count = 0;
|
||||
}
|
||||
} else {
|
||||
d->pending_period = period;
|
||||
d->pending_count = 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Frames since the most recent beat according to the comb over past beats
|
||||
static int best_phase(beat_dsp_t *d, uint32_t cur)
|
||||
{
|
||||
const float p = d->period;
|
||||
const int np = (int)p;
|
||||
const int expect = (d->prev_phase - d->lead_frames + 1 + 2 * np) % np;
|
||||
int best = 0;
|
||||
float best_score = -1.0f, total = 0.0f;
|
||||
for (int phi = 0; phi < np; phi++) {
|
||||
float s = 0.0f, w = 1.0f;
|
||||
for (int k = 0; k < COMB_BEATS; k++) {
|
||||
float back = phi + k * p;
|
||||
if (back >= BEAT_NV_LEN - 2 || back > cur) {
|
||||
break;
|
||||
}
|
||||
s += w * nv_max3(d, cur - (uint32_t)lrintf(back), cur);
|
||||
w *= COMB_DECAY;
|
||||
}
|
||||
total += s;
|
||||
if (abs(phi - expect) <= 1) {
|
||||
s *= PHASE_STICK;
|
||||
}
|
||||
if (s > best_score) {
|
||||
best_score = s;
|
||||
best = phi;
|
||||
}
|
||||
}
|
||||
// How much more onset energy sits on the beat grid than off it
|
||||
float salience = total > 0.0f ? best_score * np / total : 0.0f;
|
||||
// Plain running mean until the window fills, so locking isn't held back
|
||||
float span = fminf(SALIENCE_S * d->frame_rate, (float)++d->salience_n);
|
||||
d->salience += (salience - d->salience) / span;
|
||||
return best;
|
||||
}
|
||||
|
||||
// Add one cue value to the bar position of grid beat n, for every meter
|
||||
static void bar_cue(beat_dsp_t *d, uint32_t n, float v)
|
||||
{
|
||||
for (int m = 0; m < BEAT_METERS; m++) {
|
||||
float *s = &d->bar_score[m][n % s_meters[m]];
|
||||
*s += BAR_RATE * (v - *s);
|
||||
}
|
||||
}
|
||||
|
||||
// Pick the downbeat position per meter, then the meter, with hysteresis
|
||||
static void bar_decide(beat_dsp_t *d)
|
||||
{
|
||||
float contrast[BEAT_METERS];
|
||||
for (int m = 0; m < BEAT_METERS; m++) {
|
||||
const int len = s_meters[m];
|
||||
const float *s = d->bar_score[m];
|
||||
int best = 0;
|
||||
float mean = 0.0f;
|
||||
for (int i = 0; i < len; i++) {
|
||||
mean += s[i] / len;
|
||||
if (s[i] > s[best]) {
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
// A tap holds the bar for a while; the audio only takes over after
|
||||
if (d->tap_hold == 0 && s[best] > BAR_MARGIN * s[d->down_pos[m]]) {
|
||||
d->down_pos[m] = best;
|
||||
}
|
||||
contrast[m] = mean > 0.0f ? s[d->down_pos[m]] / mean - 1.0f : 0.0f;
|
||||
}
|
||||
// Most music is in 4/4, so 3/4 has to make a stronger case
|
||||
contrast[0] *= METER3_BIAS;
|
||||
int cur = d->meter == 3 ? 0 : 1, other = 1 - cur;
|
||||
if (d->tap_hold == 0 && contrast[other] > METER_MARGIN * contrast[cur]) {
|
||||
cur = other;
|
||||
}
|
||||
d->meter = s_meters[cur];
|
||||
d->bar_contrast = contrast[cur];
|
||||
}
|
||||
|
||||
// Runs a couple of frames after grid beat pending_n landed
|
||||
static void analyse_beat(beat_dsp_t *d)
|
||||
{
|
||||
uint32_t beat = d->pending_frame - 2;
|
||||
float kick = 0.0f;
|
||||
for (uint32_t i = beat - 1; i <= beat + 2; i++) {
|
||||
kick = fmaxf(kick, d->bass_nv[i & NV_MASK]);
|
||||
}
|
||||
d->kick_mean += 0.1f * (kick - d->kick_mean);
|
||||
bar_cue(d, d->pending_n, KICK_WEIGHT * kick / (d->kick_mean + 1e-6f));
|
||||
bar_decide(d);
|
||||
d->pending = false;
|
||||
}
|
||||
|
||||
// A beat just landed: close the spectrum of the previous beat and score how
|
||||
// much new energy it brought over the one before as a bar start
|
||||
static void close_span(beat_dsp_t *d)
|
||||
{
|
||||
if (d->band_frames > 0) {
|
||||
float change = 0.0f;
|
||||
for (int b = 0; b < BEAT_BANDS; b++) {
|
||||
float v = d->band_acc[b] / d->band_frames;
|
||||
// Rises only: a chord fading out late in the bar isn't a change
|
||||
change += fmaxf(v - d->prev_span[b], 0.0f);
|
||||
d->prev_span[b] = v;
|
||||
d->band_acc[b] = 0.0f;
|
||||
}
|
||||
d->band_frames = 0;
|
||||
d->change_mean += 0.1f * (change - d->change_mean);
|
||||
if (d->span_n > 0) { // the first span has nothing to compare with
|
||||
bar_cue(d, d->span_n, CHANGE_WEIGHT * change / (d->change_mean + 1e-6f));
|
||||
}
|
||||
}
|
||||
d->span_n = d->pending_n;
|
||||
}
|
||||
|
||||
static int process_frame(beat_dsp_t *d)
|
||||
{
|
||||
int events = 0;
|
||||
bool active;
|
||||
float tempo_nv, bass_nv;
|
||||
float nv = onset_strength(d, &active, &tempo_nv, &bass_nv);
|
||||
uint32_t cur = d->t++;
|
||||
d->nv[cur & NV_MASK] = nv;
|
||||
d->tempo_nv[cur & NV_MASK] = tempo_nv;
|
||||
d->bass_nv[cur & NV_MASK] = bass_nv;
|
||||
if (d->pending && cur == d->pending_frame - 2) {
|
||||
close_span(d);
|
||||
}
|
||||
if (d->period > 0.0f && cur - (d->pending_frame - 2) < SPAN_FRAC * d->period) {
|
||||
for (int b = 0; b < BEAT_BANDS; b++) {
|
||||
d->band_acc[b] += d->band_now[b];
|
||||
}
|
||||
d->band_frames++;
|
||||
}
|
||||
if (d->pending && cur >= d->pending_frame) {
|
||||
analyse_beat(d);
|
||||
}
|
||||
if (active) {
|
||||
d->last_active = cur;
|
||||
}
|
||||
|
||||
// Onset: previous frame is a local peak above the adaptive threshold
|
||||
if (cur >= 2) {
|
||||
uint32_t c = cur - 1;
|
||||
float v = nv_at(d, c);
|
||||
if (v > nv_at(d, c - 1) && v >= nv && v > ONSET_K * d->nv_mean + 1e-3f &&
|
||||
(d->last_onset == 0 || c - d->last_onset >= ONSET_GAP_S * d->frame_rate)) {
|
||||
d->last_onset = c;
|
||||
events |= BEAT_EV_ONSET;
|
||||
}
|
||||
}
|
||||
d->nv_mean += (nv - d->nv_mean) / d->frame_rate;
|
||||
|
||||
if (d->t % TEMPO_EVERY == 0) {
|
||||
estimate_tempo(d);
|
||||
}
|
||||
if (d->period == 0.0f) {
|
||||
return events;
|
||||
}
|
||||
|
||||
bool audible = cur - d->last_active < ACTIVE_HOLD_S * d->frame_rate;
|
||||
// Speech and noise can score on one measure, music with a beat on both
|
||||
float strength = d->confidence * d->salience;
|
||||
d->locked = audible && strength >= (d->locked ? UNLOCK_STRENGTH : LOCK_STRENGTH);
|
||||
// Shifting the phase by the lead makes it wrap that many frames early
|
||||
int np = (int)d->period;
|
||||
int phase = (best_phase(d, cur) + d->lead_frames) % np;
|
||||
// Phase dropping by more than half a beat means it wrapped: beat due now
|
||||
if (phase + d->period / 2 < d->prev_phase && cur - d->last_beat >= d->period / 2) {
|
||||
if (d->pending) {
|
||||
if (cur < d->pending_frame - 2) {
|
||||
close_span(d);
|
||||
}
|
||||
analyse_beat(d);
|
||||
}
|
||||
uint32_t n = d->grid_n++;
|
||||
int pos = (int)((n + 4 * 3 - (uint32_t)d->down_pos[d->meter == 3 ? 0 : 1]) % d->meter);
|
||||
// Always offer a best guess, but only call downbeats when sure
|
||||
if (d->tap_hold > 0) {
|
||||
d->tap_hold--;
|
||||
d->bar_beat = pos + 1;
|
||||
d->bar_sure = true;
|
||||
} else {
|
||||
d->bar_beat = n >= BAR_WARMUP ? pos + 1 : 0;
|
||||
d->bar_sure = d->bar_contrast >= (d->bar_sure ? BAR_SURE_OFF : BAR_SURE_ON);
|
||||
}
|
||||
if (d->locked) {
|
||||
events |= BEAT_EV_BEAT;
|
||||
if (d->bar_beat == 1 && d->bar_sure) {
|
||||
events |= BEAT_EV_DOWNBEAT;
|
||||
}
|
||||
}
|
||||
d->last_beat = cur;
|
||||
// The beat lands lead_frames from now; look at it 2 frames after
|
||||
d->pending_frame = cur + d->lead_frames + 2;
|
||||
d->pending_n = n;
|
||||
d->pending = true;
|
||||
}
|
||||
d->prev_phase = phase;
|
||||
return events;
|
||||
}
|
||||
|
||||
void beat_dsp_tap(beat_dsp_t *d, float frames_ago)
|
||||
{
|
||||
if (d->period <= 0.0f || d->grid_n == 0) {
|
||||
return;
|
||||
}
|
||||
// Grid beat grid_n - 1 lands lead_frames after it was announced; snap the
|
||||
// tap to that beat or the one either side, whichever is nearest
|
||||
float tap = (float)d->t - frames_ago;
|
||||
float last = (float)(d->last_beat + d->lead_frames);
|
||||
int k = (int)lrintf((tap - last) / d->period);
|
||||
k = k < -1 ? -1 : k > 1 ? 1 : k;
|
||||
int32_t n = (int32_t)d->grid_n - 1 + k;
|
||||
n = n < 0 ? 0 : n;
|
||||
for (int m = 0; m < BEAT_METERS; m++) {
|
||||
float top = 1e-3f;
|
||||
for (int i = 0; i < s_meters[m]; i++) {
|
||||
top = fmaxf(top, d->bar_score[m][i]);
|
||||
}
|
||||
int pos = n % s_meters[m];
|
||||
d->bar_score[m][pos] = TAP_BOOST * top;
|
||||
d->down_pos[m] = pos;
|
||||
}
|
||||
d->tap_hold = TAP_HOLD_BARS * d->meter;
|
||||
d->bar_sure = true;
|
||||
}
|
||||
|
||||
void beat_dsp_feed(beat_dsp_t *d, const float *x, size_t n, beat_dsp_cb_t cb, void *ctx)
|
||||
{
|
||||
while (n > 0) {
|
||||
size_t take = BEAT_FFT_SIZE - d->in_fill;
|
||||
take = take < n ? take : n;
|
||||
memcpy(d->in + d->in_fill, x, take * sizeof(float));
|
||||
d->in_fill += take;
|
||||
x += take;
|
||||
n -= take;
|
||||
if (d->in_fill < BEAT_FFT_SIZE) {
|
||||
break;
|
||||
}
|
||||
int events = process_frame(d);
|
||||
memmove(d->in, d->in + BEAT_HOP, (BEAT_FFT_SIZE - BEAT_HOP) * sizeof(float));
|
||||
d->in_fill = BEAT_FFT_SIZE - BEAT_HOP;
|
||||
if (events && cb) {
|
||||
cb(ctx, events, d);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
* Realtime beat tracker, plain C with no ESP-IDF dependencies so it can be
|
||||
* tested on a PC. Spectral-flux onsets -> autocorrelation tempo -> comb-filter
|
||||
* phase tracking that predicts beats from the last few bars -> bar position
|
||||
* (downbeats and 3/4 vs 4/4) from bass hits and harmonic changes per beat.
|
||||
*/
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define BEAT_FFT_SIZE 512 // 32 ms window at 16 kHz
|
||||
#define BEAT_HOP 256 // 16 ms between onset frames
|
||||
#define BEAT_NV_LEN 512 // onset history (~8 s), power of two
|
||||
#define BEAT_MIN_BPM 60.0f
|
||||
#define BEAT_MAX_BPM 200.0f
|
||||
#define BEAT_AC_LEN (BEAT_NV_LEN / 2) // autocorrelation lags kept
|
||||
|
||||
#define BEAT_BANDS 16 // log-spaced bands for harmonic change
|
||||
#define BEAT_METERS 2 // 3/4 and 4/4
|
||||
|
||||
#define BEAT_EV_ONSET 0x1
|
||||
#define BEAT_EV_BEAT 0x2
|
||||
#define BEAT_EV_DOWNBEAT 0x4 // with BEAT_EV_BEAT, when the bar is sure
|
||||
|
||||
typedef struct {
|
||||
// Settings (from beat_dsp_init)
|
||||
float frame_rate; // onset frames per second
|
||||
float gate_rms; // frames quieter than this are treated as silence
|
||||
int min_lag, max_lag; // beat period search range, frames
|
||||
int lead_frames; // emit predicted beats this early
|
||||
|
||||
// Onset detection
|
||||
float in[BEAT_FFT_SIZE];
|
||||
size_t in_fill;
|
||||
float re[BEAT_FFT_SIZE], im[BEAT_FFT_SIZE]; // FFT work, reused as scratch
|
||||
float prev_log[BEAT_FFT_SIZE / 2 + 1];
|
||||
float prev_bass;
|
||||
float flux_mean, bass_mean, nv_mean;
|
||||
float nv[BEAT_NV_LEN]; // novelty (onset strength) ring, indexed by frame
|
||||
float tempo_nv[BEAT_NV_LEN]; // log flux only, for the tempo estimate
|
||||
float bass_nv[BEAT_NV_LEN]; // bass rise only, for downbeats
|
||||
uint32_t t; // frames processed
|
||||
uint32_t last_active, last_onset;
|
||||
|
||||
// Tempo
|
||||
float ac[BEAT_AC_LEN];
|
||||
float period; // frames per beat, 0 until found
|
||||
float confidence; // 0..1 periodicity of the onset envelope
|
||||
float pending_period;
|
||||
int pending_count;
|
||||
|
||||
// Beat phase
|
||||
float salience; // on-beat vs. average onset energy, 1 = no beat
|
||||
uint32_t salience_n;
|
||||
int prev_phase;
|
||||
uint32_t last_beat;
|
||||
bool locked;
|
||||
|
||||
// Bar position. Grid beats are numbered whether or not they are emitted;
|
||||
// each one is analysed a couple of frames after it lands.
|
||||
uint32_t grid_n; // grid beats so far
|
||||
uint32_t pending_frame; // frame to analyse the latest beat at
|
||||
uint32_t pending_n; // its grid number
|
||||
bool pending;
|
||||
float band_now[BEAT_BANDS]; // log band energy of the current frame
|
||||
float band_acc[BEAT_BANDS]; // ...summed over the start of the latest beat
|
||||
float prev_span[BEAT_BANDS]; // ...averaged over the start of the one before
|
||||
int band_frames;
|
||||
uint32_t span_n; // grid number of the beat band_acc belongs to
|
||||
float kick_mean, change_mean;
|
||||
float bar_score[BEAT_METERS][4]; // cue strength per meter and position
|
||||
int down_pos[BEAT_METERS]; // grid_n % meter of the downbeat
|
||||
int meter; // 3 or 4
|
||||
float bar_contrast; // how clearly one position stands out
|
||||
int bar_beat; // 1..meter of the last grid beat (best guess), 0 early on
|
||||
bool bar_sure; // bar_beat is reliable; downbeats only go out then
|
||||
uint32_t tap_hold; // grid beats left that a tap holds the bar for
|
||||
} beat_dsp_t;
|
||||
|
||||
// lead_s fires predicted beats early to cover capture and output latency
|
||||
void beat_dsp_init(beat_dsp_t *d, float sample_rate, float gate_rms, float lead_s);
|
||||
|
||||
// Feed mono samples scaled to +/-1. Calls cb once per frame that produced
|
||||
// events (BEAT_EV_* bits). Beats are predicted, so they arrive lead_s ahead
|
||||
// of the frame they belong to; onsets need one frame of lookahead.
|
||||
typedef void (*beat_dsp_cb_t)(void *ctx, int events, const beat_dsp_t *d);
|
||||
void beat_dsp_feed(beat_dsp_t *d, const float *x, size_t n, beat_dsp_cb_t cb, void *ctx);
|
||||
|
||||
// The user tapped beat 1 frames_ago frames back: make the nearest grid beat
|
||||
// beat 1 and hold that for a while before the audio can move it again
|
||||
void beat_dsp_tap(beat_dsp_t *d, float frames_ago);
|
||||
|
||||
static inline float beat_dsp_bpm(const beat_dsp_t *d)
|
||||
{
|
||||
return d->period > 0.0f ? 60.0f * d->frame_rate / d->period : 0.0f;
|
||||
}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
#include "bench.h"
|
||||
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "driver/gpio.h"
|
||||
#include "esp_timer.h"
|
||||
#include "espnow_tx.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/portmacro.h"
|
||||
#include "freertos/queue.h"
|
||||
#include "freertos/task.h"
|
||||
|
||||
#define RING 64
|
||||
#define MAX_DRIVERS 8
|
||||
|
||||
typedef struct {
|
||||
uint16_t idx;
|
||||
int64_t tx_us;
|
||||
int64_t first_us, last_us;
|
||||
uint8_t echoes;
|
||||
int fire_in_ms;
|
||||
} beat_t;
|
||||
|
||||
typedef struct {
|
||||
uint8_t mac[6];
|
||||
uint32_t echoes;
|
||||
} drv_t;
|
||||
|
||||
static portMUX_TYPE s_mux = portMUX_INITIALIZER_UNLOCKED;
|
||||
static beat_t s_ring[RING];
|
||||
static drv_t s_drv[MAX_DRIVERS];
|
||||
static uint32_t s_sent, s_echoes, s_late_echoes;
|
||||
static int64_t s_min_us, s_max_us, s_sum_us;
|
||||
static int64_t s_spread_sum, s_spread_max;
|
||||
static uint32_t s_spread_n;
|
||||
static int s_remaining;
|
||||
static bool s_running;
|
||||
static float s_bpm;
|
||||
#if CONFIG_BEAT_TEST_GPIO >= 0
|
||||
static bool s_gpio_ready;
|
||||
static int s_level;
|
||||
#endif
|
||||
static esp_timer_handle_t s_timer;
|
||||
static QueueHandle_t s_logq;
|
||||
|
||||
// USB latency test: one "BT <idx> <esp_timer us>" line per synthetic beat, printed from a low-priority
|
||||
// task so the beat path itself never waits on the console. tools/usb_latency.py reads these.
|
||||
typedef struct {
|
||||
uint16_t idx;
|
||||
int64_t tx_us;
|
||||
} beat_log_t;
|
||||
|
||||
static void log_task(void *arg)
|
||||
{
|
||||
beat_log_t l;
|
||||
for (;;) {
|
||||
if (xQueueReceive(s_logq, &l, portMAX_DELAY) == pdTRUE) {
|
||||
printf("BT %u %lld\n", l.idx, (long long)l.tx_us);
|
||||
}
|
||||
}
|
||||
}
|
||||
static uint32_t s_gen_count;
|
||||
|
||||
static void gpio_mark(void)
|
||||
{
|
||||
#if CONFIG_BEAT_TEST_GPIO >= 0
|
||||
if (!s_gpio_ready) {
|
||||
gpio_set_direction(CONFIG_BEAT_TEST_GPIO, GPIO_MODE_OUTPUT);
|
||||
s_gpio_ready = true;
|
||||
}
|
||||
s_level = !s_level;
|
||||
gpio_set_level(CONFIG_BEAT_TEST_GPIO, s_level);
|
||||
#endif
|
||||
}
|
||||
|
||||
void bench_on_beat_tx(uint16_t idx, int64_t tx_us, int fire_in_ms)
|
||||
{
|
||||
gpio_mark(); // edge as the first copy goes out
|
||||
if (s_running && s_logq) {
|
||||
beat_log_t l = { .idx = idx, .tx_us = tx_us };
|
||||
xQueueSend(s_logq, &l, 0);
|
||||
}
|
||||
portENTER_CRITICAL(&s_mux);
|
||||
beat_t *b = &s_ring[idx % RING];
|
||||
memset(b, 0, sizeof(*b));
|
||||
b->idx = idx;
|
||||
b->tx_us = tx_us;
|
||||
b->fire_in_ms = fire_in_ms;
|
||||
s_sent++;
|
||||
portEXIT_CRITICAL(&s_mux);
|
||||
}
|
||||
|
||||
void bench_on_echo(const uint8_t mac[6], uint16_t idx, int64_t rx_us)
|
||||
{
|
||||
portENTER_CRITICAL(&s_mux);
|
||||
beat_t *b = &s_ring[idx % RING];
|
||||
if (b->idx != idx || b->tx_us == 0) {
|
||||
s_late_echoes++; // beat already overwritten in the ring
|
||||
portEXIT_CRITICAL(&s_mux);
|
||||
return;
|
||||
}
|
||||
// Round trip minus the deliberate fire_in wait: airtime out + driver work + airtime back
|
||||
int64_t dt = rx_us - b->tx_us - (int64_t)b->fire_in_ms * 1000;
|
||||
if (s_echoes == 0 || dt < s_min_us) {
|
||||
s_min_us = dt;
|
||||
}
|
||||
if (s_echoes == 0 || dt > s_max_us) {
|
||||
s_max_us = dt;
|
||||
}
|
||||
s_sum_us += dt;
|
||||
s_echoes++;
|
||||
if (b->echoes++ == 0) {
|
||||
b->first_us = rx_us;
|
||||
} else {
|
||||
int64_t spread = rx_us - b->first_us;
|
||||
if (spread > s_spread_max) {
|
||||
s_spread_max = spread;
|
||||
}
|
||||
s_spread_n++; // one sample per extra driver that heard this beat
|
||||
s_spread_sum += spread;
|
||||
}
|
||||
b->last_us = rx_us;
|
||||
drv_t *d = NULL;
|
||||
for (int i = 0; i < MAX_DRIVERS && !d; i++) {
|
||||
if (memcmp(s_drv[i].mac, mac, 6) == 0 && s_drv[i].echoes) {
|
||||
d = &s_drv[i];
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < MAX_DRIVERS && !d; i++) {
|
||||
if (!s_drv[i].echoes) {
|
||||
d = &s_drv[i];
|
||||
memcpy(d->mac, mac, 6);
|
||||
}
|
||||
}
|
||||
if (d) {
|
||||
d->echoes++;
|
||||
}
|
||||
portEXIT_CRITICAL(&s_mux);
|
||||
}
|
||||
|
||||
static void gen_cb(void *arg)
|
||||
{
|
||||
if (!s_running) {
|
||||
return;
|
||||
}
|
||||
s_gen_count++;
|
||||
// Downbeat on every fourth beat, like a 4/4 bar
|
||||
espnow_tx_beat(s_bpm, (s_gen_count % 4) == 1, ((s_gen_count - 1) % 4) + 1);
|
||||
if (s_remaining > 0 && --s_remaining == 0) {
|
||||
bench_stop();
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t bench_start(float bpm, int count)
|
||||
{
|
||||
if (bpm < 30 || bpm > 300) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
bench_stop();
|
||||
if (!s_logq) {
|
||||
s_logq = xQueueCreate(32, sizeof(beat_log_t));
|
||||
if (s_logq) {
|
||||
xTaskCreate(log_task, "bench_log", 3072, NULL, 2, NULL);
|
||||
}
|
||||
}
|
||||
portENTER_CRITICAL(&s_mux);
|
||||
memset(s_ring, 0, sizeof(s_ring));
|
||||
memset(s_drv, 0, sizeof(s_drv));
|
||||
s_sent = s_echoes = s_late_echoes = 0;
|
||||
s_min_us = s_max_us = s_sum_us = 0;
|
||||
s_spread_sum = s_spread_max = 0;
|
||||
s_spread_n = 0;
|
||||
portEXIT_CRITICAL(&s_mux);
|
||||
if (!s_timer) {
|
||||
const esp_timer_create_args_t ta = { .callback = gen_cb, .name = "bench_beat", .dispatch_method = ESP_TIMER_TASK };
|
||||
esp_err_t err = esp_timer_create(&ta, &s_timer);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
}
|
||||
s_bpm = bpm;
|
||||
s_remaining = count;
|
||||
s_gen_count = 0;
|
||||
s_running = true;
|
||||
return esp_timer_start_periodic(s_timer, (uint64_t)(60e6 / bpm));
|
||||
}
|
||||
|
||||
bool bench_running(void)
|
||||
{
|
||||
return s_running;
|
||||
}
|
||||
|
||||
void bench_stop(void)
|
||||
{
|
||||
s_running = false;
|
||||
if (s_timer) {
|
||||
esp_timer_stop(s_timer);
|
||||
}
|
||||
}
|
||||
|
||||
cJSON *bench_results(void)
|
||||
{
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
portENTER_CRITICAL(&s_mux);
|
||||
uint32_t sent = s_sent, echoes = s_echoes, late = s_late_echoes, spread_n = s_spread_n;
|
||||
int64_t mn = s_min_us, mx = s_max_us, sum = s_sum_us, ssum = s_spread_sum, smax = s_spread_max;
|
||||
drv_t drv[MAX_DRIVERS];
|
||||
memcpy(drv, s_drv, sizeof(drv));
|
||||
portEXIT_CRITICAL(&s_mux);
|
||||
|
||||
int ndrv = 0;
|
||||
cJSON *drivers = cJSON_AddObjectToObject(o, "drivers");
|
||||
for (int i = 0; i < MAX_DRIVERS; i++) {
|
||||
if (drv[i].echoes) {
|
||||
char key[13];
|
||||
snprintf(key, sizeof(key), "%02x%02x%02x%02x%02x%02x", drv[i].mac[0], drv[i].mac[1], drv[i].mac[2],
|
||||
drv[i].mac[3], drv[i].mac[4], drv[i].mac[5]);
|
||||
cJSON *d = cJSON_AddObjectToObject(drivers, key);
|
||||
cJSON_AddNumberToObject(d, "echoes", drv[i].echoes);
|
||||
cJSON_AddNumberToObject(d, "hit_pct", sent ? 100.0 * drv[i].echoes / sent : 0);
|
||||
ndrv++;
|
||||
}
|
||||
}
|
||||
cJSON_AddBoolToObject(o, "running", s_running);
|
||||
cJSON_AddNumberToObject(o, "beats_sent", sent);
|
||||
cJSON_AddNumberToObject(o, "echoes", echoes);
|
||||
cJSON_AddNumberToObject(o, "late_echoes", late);
|
||||
// Fraction of beats each driver acted on; ~100 with the double send even at moderate loss
|
||||
cJSON_AddNumberToObject(o, "hit_pct_total", sent && ndrv ? 100.0 * echoes / ((double)sent * ndrv) : 0);
|
||||
cJSON_AddNumberToObject(o, "rtt_minus_lead_min_us", mn);
|
||||
cJSON_AddNumberToObject(o, "rtt_minus_lead_avg_us", echoes ? (double)sum / echoes : 0);
|
||||
cJSON_AddNumberToObject(o, "rtt_minus_lead_max_us", mx);
|
||||
// Arrival spread between drivers for the same beat (needs two or more drivers echoing)
|
||||
cJSON_AddNumberToObject(o, "spread_avg_us", spread_n ? (double)ssum / spread_n : 0);
|
||||
cJSON_AddNumberToObject(o, "spread_max_us", smax);
|
||||
bool beats_lossy;
|
||||
cJSON_AddNumberToObject(o, "loss_pct", espnow_tx_loss(&beats_lossy));
|
||||
cJSON_AddBoolToObject(o, "loss_includes_beats", beats_lossy);
|
||||
return o;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include "cJSON.h"
|
||||
#include "esp_err.h"
|
||||
|
||||
// Bench-test helpers: a synthetic beat generator, an echo-based latency and
|
||||
// delivery measurement, and the optional GPIO marker for a logic analyzer.
|
||||
|
||||
// Called by espnow_tx for every beat (first copy time, and how long drivers wait before firing)
|
||||
void bench_on_beat_tx(uint16_t idx, int64_t tx_us, int fire_in_ms);
|
||||
// A driver echoed beat `idx` right after it fired (called from the Wi-Fi task)
|
||||
void bench_on_echo(const uint8_t mac[6], uint16_t idx, int64_t rx_us);
|
||||
|
||||
// Send `count` synthetic beats at `bpm` (count 0 = until stopped); resets the results
|
||||
esp_err_t bench_start(float bpm, int count);
|
||||
void bench_stop(void);
|
||||
|
||||
// True while the synthetic generator runs; mic beats are muted meanwhile so they cannot mix in
|
||||
bool bench_running(void);
|
||||
|
||||
// Results so far; caller owns the object
|
||||
cJSON *bench_results(void);
|
||||
@@ -0,0 +1,928 @@
|
||||
#include "engine.h"
|
||||
|
||||
#include <ctype.h>
|
||||
#include <strings.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "envelope.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_timer.h"
|
||||
#include "espnow_tx.h"
|
||||
#include "rel.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "store.h"
|
||||
|
||||
static const char *TAG = "engine";
|
||||
|
||||
#define FRAME_REPEAT 2 // every state frame goes out twice; messages are idempotent
|
||||
#define MAX_RUNNERS 8
|
||||
#define JSON_MAX 232
|
||||
|
||||
/* ---------------------------------------------------------------- sending */
|
||||
|
||||
static esp_err_t tx(const uint8_t *mac, const void *data, size_t len, bool commit, int repeat)
|
||||
{
|
||||
// The bulk queue is bounded; wait for room instead of dropping state
|
||||
for (int i = 0; i < 400; i++) {
|
||||
esp_err_t err = rel_send(mac, data, len, commit, repeat);
|
||||
if (err != ESP_ERR_NO_MEM) {
|
||||
return err;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(5));
|
||||
}
|
||||
return ESP_ERR_TIMEOUT;
|
||||
}
|
||||
|
||||
static bool parse_mac(const char *s, uint8_t mac[6])
|
||||
{
|
||||
if (strlen(s) != 12) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < 6; i++) {
|
||||
if (!isxdigit((unsigned char)s[2 * i]) || !isxdigit((unsigned char)s[2 * i + 1])) {
|
||||
return false;
|
||||
}
|
||||
char b[3] = { s[2 * i], s[2 * i + 1], 0 };
|
||||
mac[i] = strtoul(b, NULL, 16);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Broadcast (no targets): sent `repeat` times under one sequence number, never acked; the
|
||||
// state version digest covers losses. With targets: unicast per MAC, acked and retransmitted.
|
||||
// commit (broadcast only) tells drivers this frame completes a state change.
|
||||
static char s_gid[16]; // zone being played; "" = plain CMD (all addressed drivers apply it)
|
||||
static bool s_save; // append the CMD save byte (driver persists presets / brightness)
|
||||
|
||||
// Envelopes travel as 0x4C CMD (4C 03 env) or, for a zone, GROUP_CMD (4C 04 <len><group> env) so only
|
||||
// drivers in that group apply them. JSON messages go as they are.
|
||||
static size_t wrap_wire(uint8_t *out, const uint8_t *frame, size_t len)
|
||||
{
|
||||
if (len == 0 || frame[0] != 2) { // not a v2 envelope
|
||||
memcpy(out, frame, len);
|
||||
return len;
|
||||
}
|
||||
size_t off = 0;
|
||||
out[off++] = 0x4C;
|
||||
if (s_gid[0]) {
|
||||
size_t gl = strlen(s_gid);
|
||||
out[off++] = 0x04;
|
||||
out[off++] = gl;
|
||||
memcpy(out + off, s_gid, gl);
|
||||
off += gl;
|
||||
} else {
|
||||
out[off++] = 0x03;
|
||||
}
|
||||
memcpy(out + off, frame, len);
|
||||
off += len;
|
||||
if (s_save) {
|
||||
out[off++] = 1; // 4C 03 / 4C 04 carry an optional trailing save flag after the envelope
|
||||
}
|
||||
return off;
|
||||
}
|
||||
|
||||
static esp_err_t emit_c(const cJSON *targets, const uint8_t *frame, size_t len, int repeat, bool commit)
|
||||
{
|
||||
uint8_t wire[REL_FRAG_MAX];
|
||||
if (len + 3 + strlen(s_gid) + 1 > sizeof(wire)) {
|
||||
return ESP_ERR_INVALID_SIZE;
|
||||
}
|
||||
len = wrap_wire(wire, frame, len);
|
||||
frame = wire;
|
||||
esp_err_t ret = ESP_OK;
|
||||
int n = cJSON_IsArray(targets) ? cJSON_GetArraySize(targets) : 0;
|
||||
if (n == 0) {
|
||||
return tx(NULL, frame, len, commit, repeat);
|
||||
}
|
||||
for (int i = 0; i < n; i++) {
|
||||
const cJSON *t = cJSON_GetArrayItem(targets, i);
|
||||
uint8_t mac[6];
|
||||
if (cJSON_IsString(t) && parse_mac(t->valuestring, mac)) {
|
||||
esp_err_t e = tx(mac, frame, len, false, 1);
|
||||
if (e != ESP_OK) {
|
||||
ret = e;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
static esp_err_t emit(const cJSON *targets, const uint8_t *frame, size_t len, int repeat)
|
||||
{
|
||||
return emit_c(targets, frame, len, repeat, false);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- presets */
|
||||
|
||||
// Preset record with palette references applied. Caller deletes the result.
|
||||
static cJSON *preset_payload(const char *preset_id)
|
||||
{
|
||||
cJSON *rec = cJSON_GetObjectItem(store_coll("preset"), preset_id);
|
||||
if (!rec) {
|
||||
return NULL;
|
||||
}
|
||||
cJSON *out = cJSON_Duplicate(rec, true);
|
||||
cJSON *refs = cJSON_GetObjectItem(out, "palette_refs");
|
||||
cJSON *colors = cJSON_GetObjectItem(out, "colors");
|
||||
if (!cJSON_IsArray(refs) || !cJSON_IsArray(colors)) {
|
||||
return out;
|
||||
}
|
||||
cJSON *pid = cJSON_GetObjectItem(out, "profile_id");
|
||||
char pidbuf[24] = "";
|
||||
if (cJSON_IsString(pid)) {
|
||||
snprintf(pidbuf, sizeof(pidbuf), "%s", pid->valuestring);
|
||||
} else if (cJSON_IsNumber(pid)) {
|
||||
snprintf(pidbuf, sizeof(pidbuf), "%d", (int)pid->valuedouble);
|
||||
}
|
||||
cJSON *profile = cJSON_GetObjectItem(store_coll("profile"), pidbuf);
|
||||
cJSON *palid = cJSON_GetObjectItem(profile, "palette_id");
|
||||
char palbuf[24] = "";
|
||||
if (cJSON_IsString(palid)) {
|
||||
snprintf(palbuf, sizeof(palbuf), "%s", palid->valuestring);
|
||||
} else if (cJSON_IsNumber(palid)) {
|
||||
snprintf(palbuf, sizeof(palbuf), "%d", (int)palid->valuedouble);
|
||||
}
|
||||
cJSON *pal = cJSON_GetObjectItem(store_coll("palette"), palbuf);
|
||||
if (!cJSON_IsArray(pal)) {
|
||||
return out;
|
||||
}
|
||||
int n = cJSON_GetArraySize(colors);
|
||||
for (int i = 0; i < n; i++) {
|
||||
cJSON *ref = cJSON_GetArrayItem(refs, i);
|
||||
if (cJSON_IsNumber(ref)) {
|
||||
int idx = (int)ref->valuedouble;
|
||||
cJSON *c = cJSON_GetArrayItem(pal, idx);
|
||||
if (idx >= 0 && c && (cJSON_IsString(c) ? c->valuestring[0] : true)) {
|
||||
cJSON_ReplaceItemInArray(colors, i, cJSON_Duplicate(c, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ zone play */
|
||||
|
||||
static const cJSON *zone_names(const char *zone_id)
|
||||
{
|
||||
cJSON *z = cJSON_GetObjectItem(store_coll("zone"), zone_id);
|
||||
cJSON *names = cJSON_GetObjectItem(z, "names");
|
||||
return cJSON_IsArray(names) ? names : NULL;
|
||||
}
|
||||
|
||||
static bool name_seen(const cJSON *names, int upto, const char *name)
|
||||
{
|
||||
for (int i = 0; i < upto; i++) {
|
||||
const cJSON *o = cJSON_GetArrayItem(names, i);
|
||||
if (cJSON_IsString(o) && strcmp(o->valuestring, name) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Select a preset for the whole zone: one GROUP_CMD, applied by every driver in the zone's group.
|
||||
// The select entry's key is ignored by drivers when it is the only entry.
|
||||
static esp_err_t select_zone(const char *zone_id, const char *preset_name)
|
||||
{
|
||||
uint8_t frame[ENV_FRAME_MAX];
|
||||
env_blob_t sel;
|
||||
env_blob_init(&sel);
|
||||
env_add_select(&sel, "*", preset_name, -1);
|
||||
snprintf(s_gid, sizeof(s_gid), "%s", zone_id);
|
||||
esp_err_t ret = emit_c(NULL, frame, env_frame(frame, -1, NULL, &sel), FRAME_REPEAT, true);
|
||||
s_gid[0] = 0;
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* What each zone last played, so a driver that missed it can be brought back in step */
|
||||
typedef struct {
|
||||
char zone[16];
|
||||
char preset[24];
|
||||
uint16_t ver;
|
||||
} zone_cur_t;
|
||||
static zone_cur_t s_cur[16];
|
||||
|
||||
static void zone_cur_set(const char *zone_id, const char *preset_id)
|
||||
{
|
||||
zone_cur_t *slot = NULL;
|
||||
for (int i = 0; i < 16; i++) {
|
||||
if (strcmp(s_cur[i].zone, zone_id) == 0) {
|
||||
slot = &s_cur[i];
|
||||
break;
|
||||
}
|
||||
if (!slot && !s_cur[i].zone[0]) {
|
||||
slot = &s_cur[i];
|
||||
}
|
||||
}
|
||||
if (slot) {
|
||||
snprintf(slot->zone, sizeof(slot->zone), "%s", zone_id);
|
||||
snprintf(slot->preset, sizeof(slot->preset), "%s", preset_id);
|
||||
slot->ver = rel_ver();
|
||||
}
|
||||
}
|
||||
|
||||
static void runner_stop_zone(const char *zone_id);
|
||||
|
||||
static esp_err_t play_locked(const char *zone_id, const char *preset_id)
|
||||
{
|
||||
const cJSON *names = zone_names(zone_id);
|
||||
if (!names) {
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
cJSON *payload = preset_payload(preset_id);
|
||||
if (!payload) {
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
uint8_t frame[ENV_FRAME_MAX];
|
||||
env_blob_t pb;
|
||||
env_blob_init(&pb);
|
||||
rel_bump_ver();
|
||||
bool fit = env_add_preset(&pb, preset_id, payload);
|
||||
cJSON_Delete(payload);
|
||||
if (!fit) {
|
||||
return ESP_ERR_INVALID_SIZE;
|
||||
}
|
||||
size_t len = env_frame(frame, -1, &pb, NULL);
|
||||
snprintf(s_gid, sizeof(s_gid), "%s", zone_id);
|
||||
esp_err_t ret = emit(NULL, frame, len, FRAME_REPEAT);
|
||||
s_gid[0] = 0;
|
||||
if (ret == ESP_OK) {
|
||||
ret = select_zone(zone_id, preset_id);
|
||||
}
|
||||
if (ret == ESP_OK) {
|
||||
zone_cur_set(zone_id, preset_id);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
esp_err_t engine_play(const char *zone_id, const char *preset_id)
|
||||
{
|
||||
store_lock();
|
||||
runner_stop_zone(zone_id); // a manual pick ends that zone's sequence
|
||||
esp_err_t ret = play_locked(zone_id, preset_id);
|
||||
store_unlock();
|
||||
return ret;
|
||||
}
|
||||
|
||||
esp_err_t engine_stop(const char *zone_id)
|
||||
{
|
||||
store_lock();
|
||||
runner_stop_zone(zone_id);
|
||||
const cJSON *names = zone_names(zone_id);
|
||||
rel_bump_ver();
|
||||
esp_err_t ret = names ? select_zone(zone_id, "off") : ESP_ERR_NOT_FOUND;
|
||||
if (names) {
|
||||
zone_cur_set(zone_id, "off");
|
||||
}
|
||||
store_unlock();
|
||||
return ret;
|
||||
}
|
||||
|
||||
static const char *device_name_for(const uint8_t mac[6]);
|
||||
|
||||
/* ------------------------------------------------------------ push/send */
|
||||
|
||||
static bool only_binary_keys(const cJSON *m)
|
||||
{
|
||||
const cJSON *it;
|
||||
cJSON_ArrayForEach(it, m)
|
||||
{
|
||||
const char *k = it->string;
|
||||
if (strcmp(k, "v") && strcmp(k, "presets") && strcmp(k, "select") && strcmp(k, "b") && strcmp(k, "save")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static esp_err_t push_binary(const cJSON *m, const cJSON *targets)
|
||||
{
|
||||
uint8_t frame[ENV_FRAME_MAX];
|
||||
esp_err_t ret = ESP_OK;
|
||||
const cJSON *b = cJSON_GetObjectItem(m, "b");
|
||||
int brightness = cJSON_IsNumber(b) ? (int)b->valuedouble : -1;
|
||||
const cJSON *sv = cJSON_GetObjectItem(m, "save");
|
||||
const bool save = cJSON_IsTrue(sv) || (cJSON_IsNumber(sv) && sv->valuedouble != 0);
|
||||
bool sent_any = false;
|
||||
|
||||
const cJSON *presets = cJSON_GetObjectItem(m, "presets"), *it;
|
||||
const cJSON *select_obj = cJSON_GetObjectItem(m, "select");
|
||||
const bool has_select = cJSON_IsObject(select_obj) && select_obj->child;
|
||||
env_blob_t pb;
|
||||
env_blob_init(&pb);
|
||||
cJSON_ArrayForEach(it, presets)
|
||||
{
|
||||
if (!env_add_preset(&pb, it->string, it)) {
|
||||
size_t len = env_frame(frame, sent_any ? -1 : brightness, &pb, NULL);
|
||||
ret = emit_c(targets, frame, len, FRAME_REPEAT, false);
|
||||
sent_any = true;
|
||||
env_blob_init(&pb);
|
||||
if (!env_add_preset(&pb, it->string, it)) {
|
||||
ESP_LOGW(TAG, "preset %s too large for one frame", it->string);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pb.data[0]) {
|
||||
size_t len = env_frame(frame, sent_any ? -1 : brightness, &pb, NULL);
|
||||
s_save = save; // only the last presets frame asks the driver to persist
|
||||
ret = emit_c(targets, frame, len, FRAME_REPEAT, !has_select);
|
||||
s_save = false;
|
||||
sent_any = true;
|
||||
}
|
||||
|
||||
const cJSON *select = cJSON_GetObjectItem(m, "select");
|
||||
env_blob_t sb;
|
||||
env_blob_init(&sb);
|
||||
cJSON_ArrayForEach(it, select)
|
||||
{
|
||||
const char *pname = NULL;
|
||||
int step = -1;
|
||||
if (cJSON_IsArray(it) && cJSON_GetArraySize(it) > 0) {
|
||||
const cJSON *p0 = cJSON_GetArrayItem(it, 0), *s1 = cJSON_GetArrayItem(it, 1);
|
||||
pname = cJSON_IsString(p0) ? p0->valuestring : NULL;
|
||||
if (cJSON_IsNumber(s1)) {
|
||||
step = (int)s1->valuedouble;
|
||||
}
|
||||
} else if (cJSON_IsString(it)) {
|
||||
pname = it->valuestring;
|
||||
}
|
||||
if (!pname) {
|
||||
continue;
|
||||
}
|
||||
if (!env_add_select(&sb, it->string, pname, step)) {
|
||||
size_t len = env_frame(frame, sent_any ? -1 : brightness, NULL, &sb);
|
||||
ret = emit_c(targets, frame, len, FRAME_REPEAT, true);
|
||||
sent_any = true;
|
||||
env_blob_init(&sb);
|
||||
env_add_select(&sb, it->string, pname, step);
|
||||
}
|
||||
}
|
||||
if (sb.data[0]) {
|
||||
size_t len = env_frame(frame, sent_any ? -1 : brightness, NULL, &sb);
|
||||
ret = emit_c(targets, frame, len, FRAME_REPEAT, true);
|
||||
sent_any = true;
|
||||
}
|
||||
if (!sent_any && brightness >= 0) { // brightness-only message
|
||||
size_t len = env_frame(frame, brightness, NULL, NULL);
|
||||
s_save = save;
|
||||
ret = emit_c(targets, frame, len, FRAME_REPEAT, true);
|
||||
s_save = false;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
// JSON text path for keys the binary envelope cannot carry (save, default, manifest, ...)
|
||||
static esp_err_t push_json(const cJSON *m, const cJSON *targets)
|
||||
{
|
||||
char *s = cJSON_PrintUnformatted(m);
|
||||
if (!s) {
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
esp_err_t ret;
|
||||
if (strlen(s) <= JSON_MAX) {
|
||||
ret = emit_c(targets, (const uint8_t *)s, strlen(s), 1, true);
|
||||
free(s);
|
||||
return ret;
|
||||
}
|
||||
free(s);
|
||||
|
||||
// Too big: split the presets over several messages, the other keys go on the last one
|
||||
const cJSON *presets = cJSON_GetObjectItem(m, "presets");
|
||||
if (!cJSON_IsObject(presets)) {
|
||||
return ESP_ERR_INVALID_SIZE;
|
||||
}
|
||||
const size_t base = strlen("{\"v\":\"1\",\"presets\":{}}");
|
||||
const size_t room = JSON_MAX - 48; // keep space for save/default on the last message
|
||||
ret = ESP_OK;
|
||||
cJSON *batch = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(batch, "v", "1");
|
||||
cJSON *bp = cJSON_AddObjectToObject(batch, "presets");
|
||||
size_t cur = base;
|
||||
const cJSON *it;
|
||||
cJSON_ArrayForEach(it, presets)
|
||||
{
|
||||
char *ps = cJSON_PrintUnformatted(it);
|
||||
size_t need = (ps ? strlen(ps) : 0) + strlen(it->string) + 4;
|
||||
free(ps);
|
||||
if (bp->child && cur + need > room) {
|
||||
char *out = cJSON_PrintUnformatted(batch);
|
||||
ret = emit(targets, (const uint8_t *)out, strlen(out), 1);
|
||||
free(out);
|
||||
cJSON_Delete(batch);
|
||||
batch = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(batch, "v", "1");
|
||||
bp = cJSON_AddObjectToObject(batch, "presets");
|
||||
cur = base;
|
||||
}
|
||||
cJSON_AddItemReferenceToObject(bp, it->string, (cJSON *)it);
|
||||
cur += need;
|
||||
}
|
||||
const cJSON *k;
|
||||
cJSON_ArrayForEach(k, m)
|
||||
{
|
||||
if (strcmp(k->string, "v") && strcmp(k->string, "presets")) {
|
||||
cJSON_AddItemReferenceToObject(batch, k->string, (cJSON *)k);
|
||||
}
|
||||
}
|
||||
char *out = cJSON_PrintUnformatted(batch);
|
||||
if (out) {
|
||||
ret = emit_c(targets, (const uint8_t *)out, strlen(out), 1, true);
|
||||
free(out);
|
||||
}
|
||||
cJSON_Delete(batch);
|
||||
return ret;
|
||||
}
|
||||
|
||||
esp_err_t engine_push(const cJSON *messages, const cJSON *targets)
|
||||
{
|
||||
esp_err_t ret = ESP_OK;
|
||||
const cJSON *m;
|
||||
store_lock();
|
||||
cJSON_ArrayForEach(m, messages)
|
||||
{
|
||||
if (!cJSON_IsObject(m)) {
|
||||
continue;
|
||||
}
|
||||
if (!cJSON_IsArray(targets) || cJSON_GetArraySize(targets) == 0) {
|
||||
rel_bump_ver(); // a broadcast state change: drivers that miss it resync from the digest
|
||||
}
|
||||
esp_err_t e = only_binary_keys(m) ? push_binary(m, targets) : push_json(m, targets);
|
||||
if (e != ESP_OK) {
|
||||
ret = e;
|
||||
}
|
||||
}
|
||||
store_unlock();
|
||||
return ret;
|
||||
}
|
||||
|
||||
esp_err_t engine_send_presets(const cJSON *ids, bool save, const char *def, const cJSON *targets, int *sent)
|
||||
{
|
||||
cJSON *msg = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(msg, "v", "1");
|
||||
cJSON *presets = cJSON_AddObjectToObject(msg, "presets");
|
||||
int count = 0;
|
||||
store_lock();
|
||||
const cJSON *id;
|
||||
cJSON_ArrayForEach(id, ids)
|
||||
{
|
||||
char key[24];
|
||||
if (cJSON_IsNumber(id)) {
|
||||
snprintf(key, sizeof(key), "%d", (int)id->valuedouble);
|
||||
} else if (cJSON_IsString(id)) {
|
||||
snprintf(key, sizeof(key), "%s", id->valuestring);
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
cJSON *p = preset_payload(key);
|
||||
if (!p) {
|
||||
continue;
|
||||
}
|
||||
cJSON_AddItemToObject(presets, key, p);
|
||||
count++;
|
||||
}
|
||||
if (sent) {
|
||||
*sent = count;
|
||||
}
|
||||
esp_err_t ret = ESP_ERR_NOT_FOUND;
|
||||
if (count) {
|
||||
if (save) {
|
||||
cJSON_AddTrueToObject(msg, "save");
|
||||
}
|
||||
if (!cJSON_IsArray(targets) || cJSON_GetArraySize(targets) == 0) {
|
||||
rel_bump_ver();
|
||||
}
|
||||
ret = push_binary(msg, targets);
|
||||
// The startup preset needs the driver names (the driver checks it is addressed); targeted sends only
|
||||
if (ret == ESP_OK && def && cJSON_GetObjectItem(presets, def) && cJSON_IsArray(targets)) {
|
||||
cJSON *names = cJSON_CreateArray();
|
||||
const cJSON *t;
|
||||
cJSON_ArrayForEach(t, targets)
|
||||
{
|
||||
uint8_t mac[6];
|
||||
const char *n = cJSON_IsString(t) && parse_mac(t->valuestring, mac) ? device_name_for(mac) : NULL;
|
||||
if (n) {
|
||||
cJSON_AddItemToArray(names, cJSON_CreateString(n));
|
||||
}
|
||||
}
|
||||
if (cJSON_GetArraySize(names)) {
|
||||
cJSON *d = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(d, "v", "1");
|
||||
cJSON_AddStringToObject(d, "default", def);
|
||||
cJSON_AddItemToObject(d, "targets", names);
|
||||
names = NULL;
|
||||
ret = push_json(d, targets);
|
||||
cJSON_Delete(d);
|
||||
}
|
||||
cJSON_Delete(names);
|
||||
}
|
||||
}
|
||||
store_unlock();
|
||||
cJSON_Delete(msg);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ sequencer */
|
||||
|
||||
typedef struct {
|
||||
bool used;
|
||||
char seq[16];
|
||||
char zone[16];
|
||||
int step;
|
||||
int rounds;
|
||||
int64_t deadline_us;
|
||||
} runner_t;
|
||||
|
||||
static runner_t s_run[MAX_RUNNERS];
|
||||
static TaskHandle_t s_task;
|
||||
|
||||
static void set_active(const char *seq_id, bool on)
|
||||
{
|
||||
cJSON *rec = cJSON_GetObjectItem(store_coll("sequence"), seq_id);
|
||||
if (!rec) {
|
||||
return;
|
||||
}
|
||||
cJSON_DeleteItemFromObject(rec, "active");
|
||||
cJSON_AddBoolToObject(rec, "active", on);
|
||||
store_save("sequence");
|
||||
}
|
||||
|
||||
static void runner_free(runner_t *r)
|
||||
{
|
||||
r->used = false;
|
||||
set_active(r->seq, false);
|
||||
}
|
||||
|
||||
static void runner_stop_zone(const char *zone_id)
|
||||
{
|
||||
for (int i = 0; i < MAX_RUNNERS; i++) {
|
||||
if (s_run[i].used && strcmp(s_run[i].zone, zone_id) == 0) {
|
||||
runner_free(&s_run[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static const cJSON *steps_of(const char *seq_id)
|
||||
{
|
||||
cJSON *rec = cJSON_GetObjectItem(store_coll("sequence"), seq_id);
|
||||
cJSON *steps = cJSON_GetObjectItem(rec, "steps");
|
||||
return cJSON_IsArray(steps) && cJSON_GetArraySize(steps) ? steps : NULL;
|
||||
}
|
||||
|
||||
static int64_t step_duration_us(const cJSON *step)
|
||||
{
|
||||
double d = 1.0;
|
||||
const cJSON *v = cJSON_GetObjectItem(step, "duration_s");
|
||||
if (cJSON_IsNumber(v)) {
|
||||
d = v->valuedouble;
|
||||
}
|
||||
d = d < 0.5 ? 0.5 : (d > 600 ? 600 : d);
|
||||
return (int64_t)(d * 1e6);
|
||||
}
|
||||
|
||||
// Play step r->step and move the deadline on from the previous deadline (no drift)
|
||||
static void run_step(runner_t *r, bool first)
|
||||
{
|
||||
const cJSON *steps = steps_of(r->seq);
|
||||
const cJSON *step = steps ? cJSON_GetArrayItem(steps, r->step) : NULL;
|
||||
if (!step) {
|
||||
runner_free(r);
|
||||
return;
|
||||
}
|
||||
const cJSON *pid = cJSON_GetObjectItem(step, "preset_id");
|
||||
char key[24] = "";
|
||||
if (cJSON_IsString(pid)) {
|
||||
snprintf(key, sizeof(key), "%s", pid->valuestring);
|
||||
} else if (cJSON_IsNumber(pid)) {
|
||||
snprintf(key, sizeof(key), "%d", (int)pid->valuedouble);
|
||||
}
|
||||
play_locked(r->zone, key);
|
||||
r->deadline_us = (first ? esp_timer_get_time() : r->deadline_us) + step_duration_us(step);
|
||||
}
|
||||
|
||||
static void runner_advance(runner_t *r)
|
||||
{
|
||||
cJSON *rec = cJSON_GetObjectItem(store_coll("sequence"), r->seq);
|
||||
const cJSON *steps = steps_of(r->seq);
|
||||
if (!rec || !steps) {
|
||||
runner_free(r);
|
||||
return;
|
||||
}
|
||||
if (++r->step >= cJSON_GetArraySize(steps)) {
|
||||
r->step = 0;
|
||||
r->rounds++;
|
||||
const cJSON *loop = cJSON_GetObjectItem(rec, "loop");
|
||||
const cJSON *rc = cJSON_GetObjectItem(rec, "repeat_count");
|
||||
int repeat = cJSON_IsNumber(rc) ? (int)rc->valuedouble : 0;
|
||||
if (!cJSON_IsTrue(loop) || (repeat > 0 && r->rounds >= repeat)) {
|
||||
runner_free(r);
|
||||
return;
|
||||
}
|
||||
}
|
||||
run_step(r, false);
|
||||
}
|
||||
|
||||
static void seq_task(void *arg)
|
||||
{
|
||||
for (;;) {
|
||||
int64_t next = INT64_MAX;
|
||||
store_lock();
|
||||
int64_t now = esp_timer_get_time();
|
||||
for (int i = 0; i < MAX_RUNNERS; i++) {
|
||||
runner_t *r = &s_run[i];
|
||||
if (r->used && now >= r->deadline_us) {
|
||||
runner_advance(r);
|
||||
}
|
||||
if (r->used && r->deadline_us < next) {
|
||||
next = r->deadline_us;
|
||||
}
|
||||
}
|
||||
store_unlock();
|
||||
TickType_t wait = portMAX_DELAY;
|
||||
if (next != INT64_MAX) {
|
||||
int64_t us = next - esp_timer_get_time();
|
||||
wait = us <= 0 ? 0 : pdMS_TO_TICKS((us + 999) / 1000);
|
||||
}
|
||||
ulTaskNotifyTake(pdTRUE, wait);
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t engine_seq_play(const char *seq_id)
|
||||
{
|
||||
store_lock();
|
||||
cJSON *rec = cJSON_GetObjectItem(store_coll("sequence"), seq_id);
|
||||
cJSON *z = cJSON_GetObjectItem(rec, "zone_id");
|
||||
char zone[16] = "";
|
||||
if (cJSON_IsString(z)) {
|
||||
snprintf(zone, sizeof(zone), "%s", z->valuestring);
|
||||
} else if (cJSON_IsNumber(z)) {
|
||||
snprintf(zone, sizeof(zone), "%d", (int)z->valuedouble);
|
||||
}
|
||||
esp_err_t ret = ESP_ERR_NOT_FOUND;
|
||||
if (rec && zone[0] && steps_of(seq_id) && zone_names(zone)) {
|
||||
runner_stop_zone(zone);
|
||||
runner_t *slot = NULL;
|
||||
for (int i = 0; i < MAX_RUNNERS && !slot; i++) {
|
||||
slot = s_run[i].used ? NULL : &s_run[i];
|
||||
}
|
||||
if (!slot) {
|
||||
ret = ESP_ERR_NO_MEM;
|
||||
} else {
|
||||
memset(slot, 0, sizeof(*slot));
|
||||
slot->used = true;
|
||||
snprintf(slot->seq, sizeof(slot->seq), "%s", seq_id);
|
||||
snprintf(slot->zone, sizeof(slot->zone), "%s", zone);
|
||||
set_active(seq_id, true);
|
||||
run_step(slot, true);
|
||||
ret = ESP_OK;
|
||||
}
|
||||
}
|
||||
store_unlock();
|
||||
if (s_task) {
|
||||
xTaskNotifyGive(s_task);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
esp_err_t engine_seq_stop(const char *seq_id)
|
||||
{
|
||||
esp_err_t ret = ESP_ERR_NOT_FOUND;
|
||||
store_lock();
|
||||
for (int i = 0; i < MAX_RUNNERS; i++) {
|
||||
if (s_run[i].used && strcmp(s_run[i].seq, seq_id) == 0) {
|
||||
runner_free(&s_run[i]);
|
||||
ret = ESP_OK;
|
||||
}
|
||||
}
|
||||
set_active(seq_id, false);
|
||||
store_unlock();
|
||||
return ret;
|
||||
}
|
||||
|
||||
static esp_err_t scene_each(const char *scene_id, bool play)
|
||||
{
|
||||
store_lock();
|
||||
cJSON *scene = cJSON_GetObjectItem(store_coll("scene"), scene_id);
|
||||
cJSON *seqs = cJSON_GetObjectItem(scene, "sequences");
|
||||
esp_err_t ret = cJSON_IsArray(seqs) ? ESP_OK : ESP_ERR_NOT_FOUND;
|
||||
const cJSON *id;
|
||||
cJSON_ArrayForEach(id, seqs)
|
||||
{
|
||||
char key[16];
|
||||
if (cJSON_IsNumber(id)) {
|
||||
snprintf(key, sizeof(key), "%d", (int)id->valuedouble);
|
||||
} else if (cJSON_IsString(id)) {
|
||||
snprintf(key, sizeof(key), "%s", id->valuestring);
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
play ? engine_seq_play(key) : engine_seq_stop(key);
|
||||
}
|
||||
store_unlock();
|
||||
return ret;
|
||||
}
|
||||
|
||||
esp_err_t engine_scene_play(const char *scene_id) { return scene_each(scene_id, true); }
|
||||
esp_err_t engine_scene_stop(const char *scene_id) { return scene_each(scene_id, false); }
|
||||
|
||||
cJSON *engine_status(void)
|
||||
{
|
||||
cJSON *o = cJSON_CreateObject(), *zones = cJSON_AddObjectToObject(o, "zones");
|
||||
store_lock();
|
||||
for (int i = 0; i < MAX_RUNNERS; i++) {
|
||||
if (s_run[i].used) {
|
||||
cJSON *z = cJSON_AddObjectToObject(zones, s_run[i].zone);
|
||||
cJSON_AddStringToObject(z, "sequence_id", s_run[i].seq);
|
||||
cJSON_AddNumberToObject(z, "step", s_run[i].step);
|
||||
cJSON_AddNumberToObject(z, "round", s_run[i].rounds);
|
||||
}
|
||||
}
|
||||
store_unlock();
|
||||
return o;
|
||||
}
|
||||
|
||||
static void resume_task(void *arg)
|
||||
{
|
||||
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||
store_lock();
|
||||
const cJSON *rec;
|
||||
cJSON_ArrayForEach(rec, store_coll("sequence"))
|
||||
{
|
||||
if (cJSON_IsTrue(cJSON_GetObjectItem(rec, "active"))) {
|
||||
char key[16];
|
||||
snprintf(key, sizeof(key), "%s", rec->string);
|
||||
engine_seq_play(key);
|
||||
}
|
||||
}
|
||||
store_unlock();
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
/* A driver reported a stale state version: replay what its zone is playing, then commit the version */
|
||||
static const char *device_name_for(const uint8_t mac[6])
|
||||
{
|
||||
char hex[13];
|
||||
snprintf(hex, sizeof(hex), "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
||||
const cJSON *d;
|
||||
cJSON_ArrayForEach(d, store_coll("device"))
|
||||
{
|
||||
const cJSON *addr = cJSON_GetObjectItem(d, "address"), *name = cJSON_GetObjectItem(d, "name");
|
||||
if (cJSON_IsString(name) && (strcasecmp(d->string, hex) == 0 || (cJSON_IsString(addr) && strcasecmp(addr->valuestring, hex) == 0))) {
|
||||
return name->valuestring;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Unicast helpers: acked and retransmitted by the link */
|
||||
static esp_err_t send_cmd(const uint8_t mac[6], const uint8_t *env, size_t len, bool commit)
|
||||
{
|
||||
uint8_t wire[REL_FRAG_MAX];
|
||||
if (len + 2 > sizeof(wire)) {
|
||||
return ESP_ERR_INVALID_SIZE;
|
||||
}
|
||||
wire[0] = 0x4C;
|
||||
wire[1] = 0x03; // CMD
|
||||
memcpy(wire + 2, env, len);
|
||||
return rel_send(mac, wire, len + 2, commit, 1);
|
||||
}
|
||||
|
||||
// GROUPS packet: the ids of every zone whose driver names include `name`
|
||||
static void send_groups(const uint8_t mac[6], const char *name)
|
||||
{
|
||||
uint8_t pkt[REL_FRAG_MAX];
|
||||
size_t off = 3;
|
||||
int count = 0;
|
||||
const cJSON *z;
|
||||
cJSON_ArrayForEach(z, store_coll("zone"))
|
||||
{
|
||||
const cJSON *names = cJSON_GetObjectItem(z, "names");
|
||||
size_t gl = strlen(z->string);
|
||||
if (cJSON_IsArray(names) && name_seen(names, cJSON_GetArraySize(names), name) && off + 1 + gl <= sizeof(pkt) &&
|
||||
gl < 16) {
|
||||
pkt[off++] = gl;
|
||||
memcpy(pkt + off, z->string, gl);
|
||||
off += gl;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
pkt[0] = 0x4C;
|
||||
pkt[1] = 0x02; // GROUPS
|
||||
pkt[2] = count;
|
||||
rel_send(mac, pkt, off, false, 1);
|
||||
}
|
||||
|
||||
static bool hex_mac(const char *s, uint8_t mac[6])
|
||||
{
|
||||
return parse_mac(s, mac);
|
||||
}
|
||||
|
||||
// Re-send group membership to every registered ESP-NOW driver (zones or devices changed)
|
||||
void engine_groups_changed(void)
|
||||
{
|
||||
store_lock();
|
||||
const cJSON *d;
|
||||
cJSON_ArrayForEach(d, store_coll("device"))
|
||||
{
|
||||
const cJSON *name = cJSON_GetObjectItem(d, "name"), *addr = cJSON_GetObjectItem(d, "address");
|
||||
const cJSON *tr = cJSON_GetObjectItem(d, "transport");
|
||||
uint8_t mac[6];
|
||||
const char *hex = cJSON_IsString(addr) ? addr->valuestring : d->string;
|
||||
if (cJSON_IsString(name) && cJSON_IsString(tr) && !strcmp(tr->valuestring, "espnow") && hex_mac(hex, mac)) {
|
||||
send_groups(mac, name->valuestring);
|
||||
}
|
||||
}
|
||||
store_unlock();
|
||||
}
|
||||
|
||||
// A driver said hello at boot: register it, then tell it which zones it belongs to
|
||||
static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len)
|
||||
{
|
||||
char name[48] = "";
|
||||
if (pkt[0] == '{') {
|
||||
cJSON *j = cJSON_ParseWithLength((const char *)pkt, len);
|
||||
const cJSON *n = cJSON_GetObjectItem(j, "name");
|
||||
if (cJSON_IsString(n)) {
|
||||
snprintf(name, sizeof(name), "%s", n->valuestring);
|
||||
}
|
||||
cJSON_Delete(j);
|
||||
} else if (len > 3 && pkt[2] > 0 && 3 + pkt[2] <= len) { // 4C 01 <len><name> ...
|
||||
snprintf(name, sizeof(name), "%.*s", pkt[2] < sizeof(name) - 1 ? pkt[2] : (int)sizeof(name) - 1, pkt + 3);
|
||||
}
|
||||
if (!name[0]) {
|
||||
return;
|
||||
}
|
||||
char hex[13];
|
||||
snprintf(hex, sizeof(hex), "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
||||
store_lock();
|
||||
cJSON *devs = store_coll("device");
|
||||
cJSON *rec = cJSON_GetObjectItem(devs, hex);
|
||||
const cJSON *old = cJSON_GetObjectItem(rec, "name");
|
||||
if (!rec) {
|
||||
rec = cJSON_AddObjectToObject(devs, hex);
|
||||
cJSON_AddStringToObject(rec, "id", hex);
|
||||
cJSON_AddStringToObject(rec, "name", name);
|
||||
cJSON_AddStringToObject(rec, "type", "led");
|
||||
cJSON_AddStringToObject(rec, "transport", "espnow");
|
||||
cJSON_AddStringToObject(rec, "address", hex);
|
||||
store_save("device");
|
||||
ESP_LOGI(TAG, "new driver %s (%s)", name, hex);
|
||||
} else if (!cJSON_IsString(old) || strcmp(old->valuestring, name) != 0) {
|
||||
cJSON_ReplaceItemInObject(rec, "name", cJSON_CreateString(name));
|
||||
store_save("device");
|
||||
}
|
||||
send_groups(mac, name);
|
||||
store_unlock();
|
||||
}
|
||||
|
||||
/* A driver reported a stale state version: replay what its zone is playing, then commit the version */
|
||||
static void resync_driver(const uint8_t mac[6])
|
||||
{
|
||||
uint8_t frame[ENV_FRAME_MAX];
|
||||
store_lock();
|
||||
const char *name = device_name_for(mac);
|
||||
if (name) {
|
||||
send_groups(mac, name); // membership first, in case the driver lost it
|
||||
}
|
||||
const zone_cur_t *best = NULL;
|
||||
for (int i = 0; name && i < 16; i++) {
|
||||
const cJSON *names = s_cur[i].zone[0] ? zone_names(s_cur[i].zone) : NULL;
|
||||
if (names && name_seen(names, cJSON_GetArraySize(names), name) &&
|
||||
(!best || (int16_t)(s_cur[i].ver - best->ver) > 0)) {
|
||||
best = &s_cur[i];
|
||||
}
|
||||
}
|
||||
bool sent = false;
|
||||
if (best) {
|
||||
if (strcmp(best->preset, "off") != 0) {
|
||||
cJSON *payload = preset_payload(best->preset);
|
||||
env_blob_t pb;
|
||||
env_blob_init(&pb);
|
||||
if (payload && env_add_preset(&pb, best->preset, payload)) {
|
||||
send_cmd(mac, frame, env_frame(frame, -1, &pb, NULL), false);
|
||||
}
|
||||
cJSON_Delete(payload);
|
||||
}
|
||||
env_blob_t sb;
|
||||
env_blob_init(&sb);
|
||||
if (env_add_select(&sb, name, best->preset, -1)) {
|
||||
sent = send_cmd(mac, frame, env_frame(frame, -1, NULL, &sb), true) == ESP_OK;
|
||||
}
|
||||
}
|
||||
if (!sent) { // nothing to replay: an empty envelope still lets the driver adopt the version
|
||||
send_cmd(mac, frame, env_frame(frame, -1, NULL, NULL), true);
|
||||
}
|
||||
store_unlock();
|
||||
}
|
||||
|
||||
esp_err_t engine_init(void)
|
||||
{
|
||||
rel_set_resync_cb(resync_driver);
|
||||
rel_set_announce_cb(on_announce);
|
||||
if (xTaskCreate(seq_task, "sequencer", 6144, NULL, 4, &s_task) != pdPASS) {
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
xTaskCreate(resume_task, "seq_resume", 4096, NULL, 3, NULL);
|
||||
return ESP_OK;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
#include "cJSON.h"
|
||||
#include "esp_err.h"
|
||||
|
||||
// Zone play/stop, preset push/send and the sequencer. Drivers run the patterns
|
||||
// themselves; this builds preset + select frames and hands them to ESP-NOW.
|
||||
|
||||
// Start the sequencer task; sequences marked active resume after a short delay
|
||||
esp_err_t engine_init(void);
|
||||
|
||||
// Select a preset on every driver named in the zone (broadcast, sent twice)
|
||||
esp_err_t engine_play(const char *zone_id, const char *preset_id);
|
||||
// Turn the zone's drivers off and stop its sequence
|
||||
esp_err_t engine_stop(const char *zone_id);
|
||||
|
||||
// POST /presets/push: v1 messages for targets (MAC strings), or broadcast when targets is NULL
|
||||
esp_err_t engine_push(const cJSON *messages, const cJSON *targets);
|
||||
// POST /presets/send: presets from the current profile by id
|
||||
esp_err_t engine_send_presets(const cJSON *ids, bool save, const char *def, const cJSON *targets, int *sent);
|
||||
|
||||
esp_err_t engine_seq_play(const char *seq_id);
|
||||
esp_err_t engine_seq_stop(const char *seq_id);
|
||||
esp_err_t engine_scene_play(const char *scene_id);
|
||||
esp_err_t engine_scene_stop(const char *scene_id);
|
||||
|
||||
// Caller owns the result
|
||||
cJSON *engine_status(void);
|
||||
|
||||
// Zones or devices changed: re-send group membership to every registered ESP-NOW driver
|
||||
void engine_groups_changed(void);
|
||||
@@ -0,0 +1,187 @@
|
||||
#include "envelope.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
void env_blob_init(env_blob_t *b)
|
||||
{
|
||||
b->data[0] = 0;
|
||||
b->len = 1;
|
||||
}
|
||||
|
||||
static bool put(env_blob_t *b, const void *src, size_t n)
|
||||
{
|
||||
if (b->len + n > ENV_BLOB_MAX) {
|
||||
return false;
|
||||
}
|
||||
memcpy(b->data + b->len, src, n);
|
||||
b->len += n;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool put_u8(env_blob_t *b, unsigned v)
|
||||
{
|
||||
uint8_t x = v;
|
||||
return put(b, &x, 1);
|
||||
}
|
||||
|
||||
static bool put_le16(env_blob_t *b, unsigned v)
|
||||
{
|
||||
uint8_t x[2] = { v & 255, (v >> 8) & 255 };
|
||||
return put(b, x, 2);
|
||||
}
|
||||
|
||||
// Python truthiness of a JSON value
|
||||
static bool truthy(const cJSON *v)
|
||||
{
|
||||
if (!v || cJSON_IsNull(v) || cJSON_IsFalse(v)) {
|
||||
return false;
|
||||
}
|
||||
if (cJSON_IsNumber(v)) {
|
||||
return v->valuedouble != 0;
|
||||
}
|
||||
if (cJSON_IsString(v)) {
|
||||
return v->valuestring[0] != 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static const cJSON *get2(const cJSON *o, const char *a, const char *b)
|
||||
{
|
||||
const cJSON *v = cJSON_GetObjectItem(o, a);
|
||||
return truthy(v) ? v : cJSON_GetObjectItem(o, b);
|
||||
}
|
||||
|
||||
static int clamp(double v, int lo, int hi)
|
||||
{
|
||||
int i = (int)v;
|
||||
return i < lo ? lo : (i > hi ? hi : i);
|
||||
}
|
||||
|
||||
static int num_or(const cJSON *v, int dflt)
|
||||
{
|
||||
return cJSON_IsNumber(v) ? (int)v->valuedouble : (cJSON_IsBool(v) ? cJSON_IsTrue(v) : dflt);
|
||||
}
|
||||
|
||||
// Same rule as the Python packer: 6+ hex digits or an [r,g,b] list; anything else is skipped
|
||||
static bool color_rgb(const cJSON *c, uint8_t rgb[3])
|
||||
{
|
||||
if (cJSON_IsString(c)) {
|
||||
const char *s = c->valuestring;
|
||||
while (*s == ' ') {
|
||||
s++;
|
||||
}
|
||||
while (*s == '#') {
|
||||
s++;
|
||||
}
|
||||
if (strlen(s) < 6) {
|
||||
return false;
|
||||
}
|
||||
char full[7];
|
||||
memcpy(full, s, 6);
|
||||
full[6] = 0;
|
||||
char *end;
|
||||
unsigned long v = strtoul(full, &end, 16);
|
||||
if (*end) {
|
||||
return false;
|
||||
}
|
||||
rgb[0] = v >> 16;
|
||||
rgb[1] = v >> 8;
|
||||
rgb[2] = v;
|
||||
return true;
|
||||
}
|
||||
if (cJSON_IsArray(c) && cJSON_GetArraySize(c) >= 3) {
|
||||
for (int i = 0; i < 3; i++) {
|
||||
rgb[i] = (uint8_t)num_or(cJSON_GetArrayItem(c, i), 0);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool env_add_preset(env_blob_t *b, const char *name, const cJSON *p)
|
||||
{
|
||||
size_t save_len = b->len;
|
||||
uint8_t save_count = b->data[0];
|
||||
|
||||
const cJSON *pat = get2(p, "p", "pattern");
|
||||
const char *pattern = cJSON_IsString(pat) ? pat->valuestring : "off";
|
||||
const cJSON *cols = get2(p, "c", "colors");
|
||||
int ncol = cJSON_IsArray(cols) ? cJSON_GetArraySize(cols) : 0;
|
||||
size_t nl = strlen(name), pl = strlen(pattern);
|
||||
if (nl > 250 || pl > 250 || ncol > 255) {
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t rgbs[255][3];
|
||||
int nvalid = 0;
|
||||
for (int i = 0; i < ncol; i++) {
|
||||
if (color_rgb(cJSON_GetArrayItem(cols, i), rgbs[nvalid])) {
|
||||
nvalid++;
|
||||
}
|
||||
}
|
||||
bool ok = put_u8(b, nl) && put(b, name, nl) && put_u8(b, pl) && put(b, pattern, pl) && put_u8(b, nvalid);
|
||||
for (int i = 0; ok && i < nvalid; i++) {
|
||||
ok = put(b, rgbs[i], 3);
|
||||
}
|
||||
const cJSON *d = get2(p, "d", "delay"), *br = get2(p, "b", "brightness");
|
||||
const cJSON *a = cJSON_GetObjectItem(p, "a");
|
||||
if (!a) {
|
||||
a = cJSON_GetObjectItem(p, "auto");
|
||||
}
|
||||
int auto_ = a ? truthy(a) : 1;
|
||||
ok = ok && put_le16(b, clamp(num_or(d, 100), 0, 65535)) && put_u8(b, clamp(num_or(br, 127), 0, 255)) &&
|
||||
put_u8(b, auto_);
|
||||
for (int i = 1; ok && i <= 6; i++) {
|
||||
char key[4] = { 'n', '0' + i, 0 };
|
||||
ok = put_le16(b, (uint16_t)(int16_t)clamp(num_or(cJSON_GetObjectItem(p, key), 0), -32768, 32767));
|
||||
}
|
||||
if (!ok) {
|
||||
b->len = save_len;
|
||||
b->data[0] = save_count;
|
||||
return false;
|
||||
}
|
||||
b->data[0]++;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool env_add_select(env_blob_t *b, const char *device, const char *preset, int step)
|
||||
{
|
||||
size_t save_len = b->len;
|
||||
size_t dl = strlen(device), pl = strlen(preset);
|
||||
if (dl > 250 || pl > 250 || (step > 65535)) {
|
||||
return false;
|
||||
}
|
||||
bool ok = put_u8(b, dl) && put(b, device, dl) && put_u8(b, pl) && put(b, preset, pl) && put_u8(b, step >= 0);
|
||||
if (ok && step >= 0) {
|
||||
ok = put_le16(b, step);
|
||||
}
|
||||
if (!ok) {
|
||||
b->len = save_len;
|
||||
return false;
|
||||
}
|
||||
b->data[0]++;
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t env_frame(uint8_t *out, int brightness, const env_blob_t *presets, const env_blob_t *select)
|
||||
{
|
||||
size_t lp = presets && presets->data[0] ? presets->len : 0;
|
||||
size_t ls = select && select->data[0] ? select->len : 0;
|
||||
int wire = 255;
|
||||
if (brightness >= 0) {
|
||||
wire = brightness > 255 ? 127 : (brightness * 127 + 127) / 255; // 0-127 scales to 0-255
|
||||
}
|
||||
out[0] = 2;
|
||||
out[1] = wire;
|
||||
out[2] = lp;
|
||||
out[3] = ls;
|
||||
out[4] = 0;
|
||||
if (lp) {
|
||||
memcpy(out + 5, presets->data, lp);
|
||||
}
|
||||
if (ls) {
|
||||
memcpy(out + 5 + lp, select->data, ls);
|
||||
}
|
||||
return 5 + lp + ls;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include "cJSON.h"
|
||||
|
||||
// Native binary (v2) driver envelope, byte-compatible with
|
||||
// src/util/binary_envelope.py. Presets and select entries go in separate
|
||||
// frames so each frame is 5 + blob <= ENV_FRAME_MAX (one ESP-NOW payload).
|
||||
#define ENV_FRAME_MAX 224 // + 4C 04 <group> wrapper must fit REL_FRAG_MAX
|
||||
#define ENV_BLOB_MAX (ENV_FRAME_MAX - 5)
|
||||
|
||||
typedef struct {
|
||||
uint8_t data[ENV_BLOB_MAX + 1]; // data[0] is the entry count
|
||||
size_t len;
|
||||
} env_blob_t;
|
||||
|
||||
void env_blob_init(env_blob_t *b);
|
||||
|
||||
// Append one preset (short keys p,c,d,b,a,n1..n6 or long pattern/colors/...); false if it does not fit
|
||||
bool env_add_preset(env_blob_t *b, const char *name, const cJSON *preset);
|
||||
// Append one select entry; step < 0 means none
|
||||
bool env_add_select(env_blob_t *b, const char *device, const char *preset, int step);
|
||||
|
||||
// Frame with either a presets blob or a select blob (the other empty);
|
||||
// brightness < 0 leaves device brightness unchanged. Returns frame length.
|
||||
size_t env_frame(uint8_t *out, int brightness, const env_blob_t *presets, const env_blob_t *select);
|
||||
@@ -0,0 +1,231 @@
|
||||
#include "espnow_tx.h"
|
||||
|
||||
#include <string.h>
|
||||
#include "esp_check.h"
|
||||
#include "esp_event.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_netif.h"
|
||||
#include "esp_now.h"
|
||||
#include "esp_rom_sys.h"
|
||||
#include "esp_random.h"
|
||||
#include "esp_timer.h"
|
||||
#include "bench.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/queue.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include "freertos/task.h"
|
||||
|
||||
#define BULK_MAX 250
|
||||
#define BULK_RETRIES 3
|
||||
#define BULK_QUEUE_LEN 32
|
||||
|
||||
static const char *TAG = "espnow_tx";
|
||||
static const uint8_t BROADCAST[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
|
||||
|
||||
typedef struct {
|
||||
uint8_t mac[6];
|
||||
bool broadcast;
|
||||
uint8_t len;
|
||||
uint8_t data[BULK_MAX];
|
||||
} bulk_t;
|
||||
|
||||
static QueueHandle_t s_bulk_q;
|
||||
static SemaphoreHandle_t s_bulk_done;
|
||||
static volatile esp_now_send_status_t s_bulk_status;
|
||||
static volatile bool s_bulk_inflight;
|
||||
static volatile int64_t s_last_beat_us;
|
||||
static esp_timer_handle_t s_copy_timer;
|
||||
static beat_frame_t s_pending;
|
||||
static int s_copies_left;
|
||||
static uint16_t s_beat_idx;
|
||||
static uint8_t s_cur_peer[6];
|
||||
static bool s_have_peer;
|
||||
static espnow_stats_t s_stats;
|
||||
static volatile int s_loss_pct;
|
||||
static volatile bool s_loss_beats = true;
|
||||
|
||||
bool espnow_tx_drop(void)
|
||||
{
|
||||
return s_loss_pct > 0 && (int)(esp_random() % 100) < s_loss_pct;
|
||||
}
|
||||
|
||||
void espnow_tx_set_loss(int percent, bool include_beats)
|
||||
{
|
||||
s_loss_pct = percent < 0 ? 0 : (percent > 100 ? 100 : percent);
|
||||
s_loss_beats = include_beats;
|
||||
}
|
||||
|
||||
int espnow_tx_loss(bool *include_beats)
|
||||
{
|
||||
if (include_beats) {
|
||||
*include_beats = s_loss_beats;
|
||||
}
|
||||
return s_loss_pct;
|
||||
}
|
||||
|
||||
static void IRAM_ATTR send_cb(const esp_now_send_info_t *info, esp_now_send_status_t status)
|
||||
{
|
||||
(void)info;
|
||||
if (s_bulk_inflight) {
|
||||
s_bulk_status = status;
|
||||
BaseType_t woken = pdFALSE;
|
||||
xSemaphoreGiveFromISR(s_bulk_done, &woken);
|
||||
portYIELD_FROM_ISR(woken);
|
||||
}
|
||||
}
|
||||
|
||||
// Each copy carries a fire_in_ms reduced by the time already spent, so every
|
||||
// copy points at the same instant.
|
||||
static void send_beat_copy(void *arg)
|
||||
{
|
||||
(void)arg;
|
||||
int sent = CONFIG_BEAT_TX_COPIES - s_copies_left;
|
||||
int gap_ms = (sent * CONFIG_BEAT_TX_GAP_US) / 1000;
|
||||
int fire = CONFIG_BEAT_LEAD_MS - gap_ms;
|
||||
s_pending.fire_in_ms = fire < 0 ? 0 : (fire > 255 ? 255 : fire);
|
||||
|
||||
if (s_loss_beats && espnow_tx_drop()) {
|
||||
s_stats.sim_dropped++; // lossy-link test: this copy never reaches the radio
|
||||
} else if (esp_now_send(BROADCAST, (const uint8_t *)&s_pending, sizeof(s_pending)) != ESP_OK) {
|
||||
s_stats.beat_send_fail++;
|
||||
}
|
||||
s_last_beat_us = esp_timer_get_time();
|
||||
if (--s_copies_left > 0) {
|
||||
esp_timer_start_once(s_copy_timer, CONFIG_BEAT_TX_GAP_US);
|
||||
}
|
||||
}
|
||||
|
||||
void espnow_tx_beat(float bpm, bool downbeat, int bar)
|
||||
{
|
||||
if (bpm < 30.0f) {
|
||||
return;
|
||||
}
|
||||
esp_timer_stop(s_copy_timer); // a still-pending copy belongs to the previous beat
|
||||
s_pending.magic = BEAT_FRAME_MAGIC;
|
||||
s_pending.type = BEAT_FRAME_TYPE;
|
||||
s_pending.flags = (downbeat ? BEAT_FLAG_DOWNBEAT : 0) | ((bar & 7) << BEAT_FLAG_BAR_SHIFT);
|
||||
s_pending.beat_idx = ++s_beat_idx;
|
||||
s_pending.period_ms = (uint16_t)(60000.0f / bpm);
|
||||
s_copies_left = CONFIG_BEAT_TX_COPIES;
|
||||
s_stats.beats_sent++;
|
||||
bench_on_beat_tx(s_pending.beat_idx, esp_timer_get_time(), CONFIG_BEAT_LEAD_MS);
|
||||
send_beat_copy(NULL);
|
||||
}
|
||||
|
||||
// Runs in the audio task straight from the detector: no queue, no allocation.
|
||||
static void on_beat(const beat_info_t *info, float bpm, bool downbeat)
|
||||
{
|
||||
if (bench_running()) {
|
||||
return; // the bench generator owns the beat stream while it runs
|
||||
}
|
||||
espnow_tx_beat(bpm, downbeat, info->bar_sure ? info->bar_beat : 0);
|
||||
}
|
||||
|
||||
static esp_err_t select_peer(const uint8_t *mac)
|
||||
{
|
||||
if (s_have_peer && memcmp(s_cur_peer, mac, 6) == 0) {
|
||||
return ESP_OK;
|
||||
}
|
||||
// ESP-NOW holds 20 peers and there can be more drivers, so keep one
|
||||
// rotating unicast peer plus the broadcast peer.
|
||||
if (s_have_peer) {
|
||||
esp_now_del_peer(s_cur_peer);
|
||||
s_have_peer = false;
|
||||
}
|
||||
esp_now_peer_info_t p = { .channel = 0, .ifidx = WIFI_IF_STA, .encrypt = false };
|
||||
memcpy(p.peer_addr, mac, 6);
|
||||
ESP_RETURN_ON_ERROR(esp_now_add_peer(&p), TAG, "add peer");
|
||||
memcpy(s_cur_peer, mac, 6);
|
||||
s_have_peer = true;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void bulk_task(void *arg)
|
||||
{
|
||||
bulk_t b;
|
||||
for (;;) {
|
||||
xQueueReceive(s_bulk_q, &b, portMAX_DELAY);
|
||||
|
||||
// Keep the channel clear around beats
|
||||
int64_t wait_us = CONFIG_BULK_HOLDOFF_US - (esp_timer_get_time() - s_last_beat_us);
|
||||
if (wait_us > 0) {
|
||||
esp_rom_delay_us(wait_us);
|
||||
}
|
||||
|
||||
const uint8_t *dst = b.broadcast ? BROADCAST : b.mac;
|
||||
if (!b.broadcast && select_peer(b.mac) != ESP_OK) {
|
||||
s_stats.bulk_failed++;
|
||||
continue;
|
||||
}
|
||||
int tries = b.broadcast ? 1 : BULK_RETRIES;
|
||||
bool ok = false;
|
||||
for (int t = 0; t < tries && !ok; t++) {
|
||||
if (t) {
|
||||
s_stats.bulk_retries++;
|
||||
vTaskDelay(pdMS_TO_TICKS(5 << t));
|
||||
}
|
||||
xSemaphoreTake(s_bulk_done, 0);
|
||||
s_bulk_inflight = true;
|
||||
if (espnow_tx_drop()) {
|
||||
s_stats.sim_dropped++; // lossy-link test: pretend the radio sent it
|
||||
ok = true;
|
||||
} else if (esp_now_send(dst, b.data, b.len) == ESP_OK &&
|
||||
xSemaphoreTake(s_bulk_done, pdMS_TO_TICKS(30)) == pdTRUE) {
|
||||
ok = s_bulk_status == ESP_NOW_SEND_SUCCESS || b.broadcast;
|
||||
}
|
||||
s_bulk_inflight = false;
|
||||
}
|
||||
s_stats.bulk_sent += ok;
|
||||
s_stats.bulk_failed += !ok;
|
||||
vTaskDelay(pdMS_TO_TICKS(3)); // inter-frame gap
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t espnow_tx_send(const uint8_t *mac, const void *data, size_t len)
|
||||
{
|
||||
if (len == 0 || len > BULK_MAX) {
|
||||
return ESP_ERR_INVALID_SIZE;
|
||||
}
|
||||
bulk_t b = { .broadcast = mac == NULL, .len = len };
|
||||
if (mac) {
|
||||
memcpy(b.mac, mac, 6);
|
||||
}
|
||||
memcpy(b.data, data, len);
|
||||
return xQueueSend(s_bulk_q, &b, 0) == pdTRUE ? ESP_OK : ESP_ERR_NO_MEM;
|
||||
}
|
||||
|
||||
void espnow_tx_stats(espnow_stats_t *out)
|
||||
{
|
||||
*out = s_stats;
|
||||
}
|
||||
|
||||
esp_err_t espnow_tx_init(void)
|
||||
{
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_RETURN_ON_ERROR(esp_wifi_init(&cfg), TAG, "wifi init");
|
||||
ESP_RETURN_ON_ERROR(esp_wifi_set_storage(WIFI_STORAGE_RAM), TAG, "storage");
|
||||
ESP_RETURN_ON_ERROR(esp_wifi_set_mode(WIFI_MODE_STA), TAG, "mode");
|
||||
ESP_RETURN_ON_ERROR(esp_wifi_start(), TAG, "start");
|
||||
ESP_RETURN_ON_ERROR(esp_wifi_set_ps(WIFI_PS_NONE), TAG, "ps");
|
||||
ESP_RETURN_ON_ERROR(esp_wifi_set_max_tx_power(80), TAG, "tx power"); // 20 dBm
|
||||
ESP_RETURN_ON_ERROR(esp_wifi_set_channel(CONFIG_ESPNOW_CHANNEL, WIFI_SECOND_CHAN_NONE), TAG, "channel");
|
||||
|
||||
ESP_RETURN_ON_ERROR(esp_now_init(), TAG, "espnow init");
|
||||
ESP_RETURN_ON_ERROR(esp_now_register_send_cb(send_cb), TAG, "send cb");
|
||||
esp_now_peer_info_t bc = { .channel = 0, .ifidx = WIFI_IF_STA, .encrypt = false };
|
||||
memcpy(bc.peer_addr, BROADCAST, 6);
|
||||
ESP_RETURN_ON_ERROR(esp_now_add_peer(&bc), TAG, "broadcast peer");
|
||||
|
||||
s_bulk_q = xQueueCreate(BULK_QUEUE_LEN, sizeof(bulk_t));
|
||||
s_bulk_done = xSemaphoreCreateBinary();
|
||||
ESP_RETURN_ON_FALSE(s_bulk_q && s_bulk_done, ESP_ERR_NO_MEM, TAG, "alloc");
|
||||
const esp_timer_create_args_t ta = { .callback = send_beat_copy, .name = "beat_copy",
|
||||
.dispatch_method = ESP_TIMER_TASK };
|
||||
ESP_RETURN_ON_ERROR(esp_timer_create(&ta, &s_copy_timer), TAG, "timer");
|
||||
xTaskCreate(bulk_task, "espnow_bulk", 4096, NULL, 5, NULL);
|
||||
|
||||
beat_set_callback(on_beat);
|
||||
ESP_LOGI(TAG, "ESP-NOW up on channel %d, %d beat copies", CONFIG_ESPNOW_CHANNEL, CONFIG_BEAT_TX_COPIES);
|
||||
return ESP_OK;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include "esp_err.h"
|
||||
#include "beat.h"
|
||||
|
||||
// Beat frame, broadcast. Little endian, 8 bytes.
|
||||
#define BEAT_FRAME_MAGIC 0x4C // 0x4C wire protocol, message type 0x25
|
||||
#define BEAT_FRAME_TYPE 0x25
|
||||
#define BEAT_FLAG_DOWNBEAT 0x01
|
||||
#define BEAT_FLAG_BAR_SHIFT 1 // bits 1-3: bar position 0..7 (0 = unknown)
|
||||
|
||||
typedef struct __attribute__((packed)) {
|
||||
uint8_t magic;
|
||||
uint8_t type;
|
||||
uint8_t flags;
|
||||
uint16_t beat_idx; // same for every copy of one beat
|
||||
uint16_t period_ms; // beat period, drivers free-run on it
|
||||
uint8_t fire_in_ms; // drivers fire this long after receipt
|
||||
} beat_frame_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t beats_sent;
|
||||
uint32_t beat_send_fail;
|
||||
uint32_t bulk_sent;
|
||||
uint32_t bulk_retries;
|
||||
uint32_t bulk_failed;
|
||||
uint32_t sim_dropped; // frames discarded by the lossy-link test mode
|
||||
} espnow_stats_t;
|
||||
|
||||
// Start Wi-Fi (no AP) on the configured channel and ESP-NOW; hooks beat_set_callback
|
||||
esp_err_t espnow_tx_init(void);
|
||||
|
||||
// Queue a bulk frame (<= 240 bytes). mac NULL broadcasts. Unicast frames are
|
||||
// retried; they never go out within the hold-off window after a beat.
|
||||
esp_err_t espnow_tx_send(const uint8_t *mac, const void *data, size_t len);
|
||||
|
||||
void espnow_tx_stats(espnow_stats_t *out);
|
||||
|
||||
// Send one beat now (also used by the bench generator). bar 0 = unknown.
|
||||
void espnow_tx_beat(float bpm, bool downbeat, int bar);
|
||||
|
||||
// Lossy-link test mode: discard this percentage of outgoing frames and of
|
||||
// received acks/echoes. include_beats = false leaves beat copies alone.
|
||||
void espnow_tx_set_loss(int percent, bool include_beats);
|
||||
int espnow_tx_loss(bool *include_beats);
|
||||
bool espnow_tx_drop(void);
|
||||
@@ -0,0 +1,2 @@
|
||||
dependencies:
|
||||
joltwallet/littlefs: "^1.19.0"
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
/*
|
||||
* v2 controller: W5500 Ethernet, INMP441 beat detection, ESP-NOW master.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_check.h"
|
||||
#include "esp_event.h"
|
||||
#include "esp_netif.h"
|
||||
#include "esp_eth.h"
|
||||
#include "esp_mac.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "driver/gpio.h"
|
||||
#include "driver/spi_master.h"
|
||||
#include "esp_http_server.h"
|
||||
#include "esp_timer.h"
|
||||
#include "esp_system.h"
|
||||
#include "mic.h"
|
||||
#include "beat.h"
|
||||
#include "espnow_tx.h"
|
||||
#include "store.h"
|
||||
#include "api.h"
|
||||
#include "engine.h"
|
||||
#include "rel.h"
|
||||
#include "web.h"
|
||||
|
||||
static const char *TAG = "eth";
|
||||
|
||||
static httpd_handle_t s_server = NULL;
|
||||
static esp_netif_t *s_eth_netif = NULL;
|
||||
|
||||
static esp_err_t status_get_handler(httpd_req_t *req)
|
||||
{
|
||||
beat_info_t bi;
|
||||
espnow_stats_t es;
|
||||
rel_stats_t rs;
|
||||
beat_get_info(&bi);
|
||||
espnow_tx_stats(&es);
|
||||
rel_stats(&rs);
|
||||
char buf[512];
|
||||
int n = snprintf(buf, sizeof(buf),
|
||||
"{\"uptime_s\":%lld,\"free_heap\":%lu,\"bpm\":%.1f,\"beats\":%lu,"
|
||||
"\"espnow\":{\"beats_sent\":%lu,\"beat_send_fail\":%lu,\"bulk_sent\":%lu,"
|
||||
"\"bulk_retries\":%lu,\"bulk_failed\":%lu,\"sim_dropped\":%lu},"
|
||||
"\"link\":{\"ver\":%u,\"acked\":%lu,\"ack_timeouts\":%lu,\"retransmits\":%lu,\"resyncs\":%lu,\"digests\":%lu}}",
|
||||
(long long)(esp_timer_get_time() / 1000000), (unsigned long)esp_get_free_heap_size(),
|
||||
bi.bpm, (unsigned long)bi.beat_count, (unsigned long)es.beats_sent,
|
||||
(unsigned long)es.beat_send_fail, (unsigned long)es.bulk_sent,
|
||||
(unsigned long)es.bulk_retries, (unsigned long)es.bulk_failed, (unsigned long)es.sim_dropped, rel_ver(),
|
||||
(unsigned long)rs.acked, (unsigned long)rs.ack_timeouts, (unsigned long)rs.retransmits,
|
||||
(unsigned long)rs.resyncs, (unsigned long)rs.digests);
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
return httpd_resp_send(req, buf, n);
|
||||
}
|
||||
|
||||
static void start_webserver(void)
|
||||
{
|
||||
if (s_server) {
|
||||
return;
|
||||
}
|
||||
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
|
||||
config.uri_match_fn = httpd_uri_match_wildcard;
|
||||
config.max_uri_handlers = 64;
|
||||
config.stack_size = 8192;
|
||||
config.lru_purge_enable = true;
|
||||
if (httpd_start(&s_server, &config) != ESP_OK) {
|
||||
ESP_LOGE(TAG, "HTTP server start failed");
|
||||
return;
|
||||
}
|
||||
const httpd_uri_t status_uri = { .uri = "/status", .method = HTTP_GET, .handler = status_get_handler };
|
||||
httpd_register_uri_handler(s_server, &status_uri);
|
||||
web_register(s_server);
|
||||
api_register(s_server);
|
||||
ESP_LOGI(TAG, "HTTP server started on port %d", config.server_port);
|
||||
}
|
||||
|
||||
static void eth_event_handler(void *arg, esp_event_base_t event_base,
|
||||
int32_t event_id, void *event_data)
|
||||
{
|
||||
esp_eth_handle_t eth_handle = *(esp_eth_handle_t *)event_data;
|
||||
uint8_t mac[6] = {0};
|
||||
|
||||
switch (event_id) {
|
||||
case ETHERNET_EVENT_CONNECTED: {
|
||||
eth_speed_t speed;
|
||||
eth_duplex_t duplex;
|
||||
esp_eth_ioctl(eth_handle, ETH_CMD_G_MAC_ADDR, mac);
|
||||
esp_eth_ioctl(eth_handle, ETH_CMD_G_SPEED, &speed);
|
||||
esp_eth_ioctl(eth_handle, ETH_CMD_G_DUPLEX_MODE, &duplex);
|
||||
ESP_LOGI(TAG, "Ethernet Link Up, MAC " MACSTR, MAC2STR(mac));
|
||||
ESP_LOGI(TAG, "%s Mbps %s Duplex",
|
||||
speed == ETH_SPEED_100M ? "100" : "10",
|
||||
duplex == ETH_DUPLEX_FULL ? "Full" : "Half");
|
||||
break;
|
||||
}
|
||||
case ETHERNET_EVENT_DISCONNECTED:
|
||||
ESP_LOGI(TAG, "Ethernet Link Down");
|
||||
break;
|
||||
case ETHERNET_EVENT_START:
|
||||
ESP_LOGI(TAG, "Ethernet Started");
|
||||
break;
|
||||
case ETHERNET_EVENT_STOP:
|
||||
ESP_LOGI(TAG, "Ethernet Stopped");
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static void got_ip_event_handler(void *arg, esp_event_base_t event_base,
|
||||
int32_t event_id, void *event_data)
|
||||
{
|
||||
ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
|
||||
const esp_netif_ip_info_t *ip = &event->ip_info;
|
||||
|
||||
ESP_LOGI(TAG, "Got IP: " IPSTR, IP2STR(&ip->ip));
|
||||
ESP_LOGI(TAG, "Mask: " IPSTR, IP2STR(&ip->netmask));
|
||||
ESP_LOGI(TAG, "GW: " IPSTR, IP2STR(&ip->gw));
|
||||
|
||||
// Server binds to all interfaces, so it keeps working across lease changes
|
||||
start_webserver();
|
||||
}
|
||||
|
||||
static esp_err_t w5500_init(esp_eth_handle_t *eth_handle_out)
|
||||
{
|
||||
esp_err_t ret = ESP_OK;
|
||||
esp_eth_mac_t *mac = NULL;
|
||||
esp_eth_phy_t *phy = NULL;
|
||||
esp_eth_handle_t eth_handle = NULL;
|
||||
|
||||
// INT pin uses a GPIO ISR
|
||||
ESP_RETURN_ON_ERROR(gpio_install_isr_service(0), TAG, "GPIO ISR service install failed");
|
||||
|
||||
spi_bus_config_t buscfg = {
|
||||
.miso_io_num = CONFIG_W5500_MISO_GPIO,
|
||||
.mosi_io_num = CONFIG_W5500_MOSI_GPIO,
|
||||
.sclk_io_num = CONFIG_W5500_SCLK_GPIO,
|
||||
.quadwp_io_num = -1,
|
||||
.quadhd_io_num = -1,
|
||||
};
|
||||
ESP_RETURN_ON_ERROR(spi_bus_initialize(CONFIG_W5500_SPI_HOST, &buscfg, SPI_DMA_CH_AUTO),
|
||||
TAG, "SPI bus init failed");
|
||||
|
||||
spi_device_interface_config_t spi_devcfg = {
|
||||
.mode = 0,
|
||||
.clock_speed_hz = CONFIG_W5500_SPI_CLOCK_MHZ * 1000 * 1000,
|
||||
.queue_size = 20,
|
||||
.spics_io_num = CONFIG_W5500_CS_GPIO,
|
||||
};
|
||||
|
||||
eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(CONFIG_W5500_SPI_HOST, &spi_devcfg);
|
||||
w5500_config.int_gpio_num = CONFIG_W5500_INT_GPIO;
|
||||
if (CONFIG_W5500_INT_GPIO < 0) {
|
||||
w5500_config.poll_period_ms = CONFIG_W5500_POLL_PERIOD_MS;
|
||||
}
|
||||
|
||||
eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG();
|
||||
eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG();
|
||||
phy_config.reset_gpio_num = CONFIG_W5500_RST_GPIO;
|
||||
|
||||
mac = esp_eth_mac_new_w5500(&w5500_config, &mac_config);
|
||||
phy = esp_eth_phy_new_w5500(&phy_config);
|
||||
ESP_GOTO_ON_FALSE(mac && phy, ESP_FAIL, err, TAG, "W5500 MAC/PHY create failed");
|
||||
|
||||
esp_eth_config_t eth_config = ETH_DEFAULT_CONFIG(mac, phy);
|
||||
ESP_GOTO_ON_ERROR(esp_eth_driver_install(ð_config, ð_handle), err, TAG,
|
||||
"Driver install failed (check W5500 wiring/power)");
|
||||
|
||||
// The W5500 has no factory MAC; use the ESP32's Ethernet MAC from eFuse
|
||||
uint8_t eth_mac[6];
|
||||
ESP_GOTO_ON_ERROR(esp_read_mac(eth_mac, ESP_MAC_ETH), err, TAG, "Read MAC failed");
|
||||
ESP_GOTO_ON_ERROR(esp_eth_ioctl(eth_handle, ETH_CMD_S_MAC_ADDR, eth_mac), err, TAG, "Set MAC failed");
|
||||
|
||||
*eth_handle_out = eth_handle;
|
||||
return ESP_OK;
|
||||
|
||||
err:
|
||||
if (eth_handle) {
|
||||
esp_eth_driver_uninstall(eth_handle);
|
||||
}
|
||||
if (mac) {
|
||||
mac->del(mac);
|
||||
}
|
||||
if (phy) {
|
||||
phy->del(phy);
|
||||
}
|
||||
spi_bus_free(CONFIG_W5500_SPI_HOST);
|
||||
return ret;
|
||||
}
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
esp_err_t ret = nvs_flash_init();
|
||||
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
ret = nvs_flash_init();
|
||||
}
|
||||
ESP_ERROR_CHECK(ret);
|
||||
|
||||
ESP_ERROR_CHECK(store_init());
|
||||
ESP_ERROR_CHECK(esp_netif_init());
|
||||
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
||||
|
||||
esp_eth_handle_t eth_handle = NULL;
|
||||
ESP_ERROR_CHECK(w5500_init(ð_handle));
|
||||
|
||||
esp_netif_config_t netif_cfg = ESP_NETIF_DEFAULT_ETH();
|
||||
s_eth_netif = esp_netif_new(&netif_cfg);
|
||||
ESP_ERROR_CHECK(esp_netif_attach(s_eth_netif, esp_eth_new_netif_glue(eth_handle)));
|
||||
|
||||
ESP_ERROR_CHECK(esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, ð_event_handler, NULL));
|
||||
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &got_ip_event_handler, NULL));
|
||||
|
||||
ESP_ERROR_CHECK(esp_eth_start(eth_handle));
|
||||
ESP_ERROR_CHECK(espnow_tx_init());
|
||||
ESP_ERROR_CHECK(rel_init());
|
||||
ESP_ERROR_CHECK(engine_init());
|
||||
ESP_ERROR_CHECK(mic_start());
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
/*
|
||||
* INMP441 I2S microphone: level meter plus a 16-bit PCM feed for streaming.
|
||||
* Reads both I2S slots and uses whichever one the mic is driving (L/R pin to
|
||||
* GND = left, to 3V3 = right), keeping a running RMS/peak for the last block.
|
||||
* Every block also goes to the beat detector.
|
||||
*/
|
||||
#include <math.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/stream_buffer.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_check.h"
|
||||
#include "driver/i2s_std.h"
|
||||
#include "driver/gpio.h"
|
||||
#include "mic.h"
|
||||
#include "beat.h"
|
||||
|
||||
#define MIC_BLOCK_SAMPLES (MIC_SAMPLE_RATE / 50) // 20 ms per read, keeps stream latency low
|
||||
#define LEVEL_BLOCKS 5 // 100 ms per level reading
|
||||
#define FULL_SCALE_24BIT 8388608.0f
|
||||
#define DBFS_FLOOR -120.0f
|
||||
#define INMP441_SPL_OFFSET 120.0f // 94 dB SPL - (-26 dBFS)
|
||||
|
||||
static const char *TAG = "mic";
|
||||
|
||||
static i2s_chan_handle_t s_rx_chan;
|
||||
static portMUX_TYPE s_level_lock = portMUX_INITIALIZER_UNLOCKED;
|
||||
// 16-bit PCM for the HTTP stream; only fed while a listener is attached
|
||||
#define STREAM_BUF_BYTES MIC_SAMPLE_RATE // 0.5 s of 16-bit mono
|
||||
static StreamBufferHandle_t s_stream_buf;
|
||||
static volatile bool s_stream_active;
|
||||
|
||||
static mic_level_t s_level = { DBFS_FLOOR, DBFS_FLOOR, DBFS_FLOOR + INMP441_SPL_OFFSET };
|
||||
|
||||
static float to_dbfs(float x)
|
||||
{
|
||||
return x > 0.0f ? fmaxf(20.0f * log10f(x), DBFS_FLOOR) : DBFS_FLOOR;
|
||||
}
|
||||
|
||||
static void mic_task(void *arg)
|
||||
{
|
||||
static int32_t buf[MIC_BLOCK_SAMPLES * 2]; // interleaved L/R
|
||||
static int16_t pcm[MIC_BLOCK_SAMPLES];
|
||||
static float filtered[MIC_BLOCK_SAMPLES];
|
||||
// One-pole high-pass to strip the INMP441's DC offset
|
||||
float hp_prev_in = 0.0f, hp_prev_out = 0.0f;
|
||||
// Level is accumulated over several short blocks so the meter stays steady
|
||||
double level_sum_sq = 0.0;
|
||||
float level_peak = 0.0f;
|
||||
size_t level_frames = 0, level_blocks = 0;
|
||||
int64_t log_count = 0;
|
||||
|
||||
while (true) {
|
||||
size_t bytes_read = 0;
|
||||
if (i2s_channel_read(s_rx_chan, buf, sizeof(buf), &bytes_read, portMAX_DELAY) != ESP_OK) {
|
||||
continue;
|
||||
}
|
||||
size_t frames = bytes_read / (2 * sizeof(int32_t));
|
||||
if (frames == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The unused slot is tri-stated and reads as 0; pick the busier one
|
||||
int32_t raw_min = INT32_MAX, raw_max = INT32_MIN;
|
||||
size_t nonzero[2] = {0, 0};
|
||||
for (size_t i = 0; i < frames; i++) {
|
||||
for (int ch = 0; ch < 2; ch++) {
|
||||
int32_t v = buf[i * 2 + ch];
|
||||
nonzero[ch] += (v != 0);
|
||||
raw_min = v < raw_min ? v : raw_min;
|
||||
raw_max = v > raw_max ? v : raw_max;
|
||||
}
|
||||
}
|
||||
int ch = nonzero[1] > nonzero[0] ? 1 : 0;
|
||||
|
||||
for (size_t i = 0; i < frames; i++) {
|
||||
// 24-bit sample sits in the top bits of the 32-bit slot
|
||||
float x = (float)(buf[i * 2 + ch] >> 8) / FULL_SCALE_24BIT;
|
||||
float y = x - hp_prev_in + 0.995f * hp_prev_out;
|
||||
hp_prev_in = x;
|
||||
hp_prev_out = y;
|
||||
filtered[i] = y;
|
||||
level_sum_sq += (double)y * y;
|
||||
level_peak = fmaxf(level_peak, fabsf(y));
|
||||
pcm[i] = (int16_t)fmaxf(fminf(y * CONFIG_MIC_STREAM_GAIN * 32767.0f, 32767.0f), -32768.0f);
|
||||
}
|
||||
level_frames += frames;
|
||||
beat_feed(filtered, frames);
|
||||
|
||||
if (s_stream_active) {
|
||||
// Drop audio rather than block capture if the listener falls behind
|
||||
xStreamBufferSend(s_stream_buf, pcm, frames * sizeof(int16_t), 0);
|
||||
}
|
||||
|
||||
if (++level_blocks < LEVEL_BLOCKS) {
|
||||
continue;
|
||||
}
|
||||
|
||||
mic_level_t level;
|
||||
level.rms_dbfs = to_dbfs(sqrtf((float)(level_sum_sq / level_frames)));
|
||||
level.peak_dbfs = to_dbfs(level_peak);
|
||||
level.spl_db = level.rms_dbfs + INMP441_SPL_OFFSET;
|
||||
level_sum_sq = 0.0;
|
||||
level_peak = 0.0f;
|
||||
level_frames = level_blocks = 0;
|
||||
|
||||
portENTER_CRITICAL(&s_level_lock);
|
||||
s_level = level;
|
||||
portEXIT_CRITICAL(&s_level_lock);
|
||||
|
||||
if (++log_count % 50 == 0) { // every 5 s
|
||||
ESP_LOGI(TAG, "%s slot: RMS %.1f dBFS, peak %.1f dBFS, ~%.0f dB SPL",
|
||||
ch ? "right" : "left", level.rms_dbfs, level.peak_dbfs, level.spl_db);
|
||||
ESP_LOGI(TAG, "raw min %ld max %ld, nonzero L %u R %u of %u",
|
||||
(long)raw_min, (long)raw_max, (unsigned)nonzero[0], (unsigned)nonzero[1], (unsigned)frames);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t mic_start(void)
|
||||
{
|
||||
s_stream_buf = xStreamBufferCreate(STREAM_BUF_BYTES, 1);
|
||||
ESP_RETURN_ON_FALSE(s_stream_buf, ESP_ERR_NO_MEM, TAG, "Stream buffer alloc failed");
|
||||
|
||||
i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER);
|
||||
ESP_RETURN_ON_ERROR(i2s_new_channel(&chan_cfg, NULL, &s_rx_chan), TAG, "I2S channel create failed");
|
||||
|
||||
i2s_std_config_t std_cfg = {
|
||||
.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(MIC_SAMPLE_RATE),
|
||||
.slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO),
|
||||
.gpio_cfg = {
|
||||
.mclk = I2S_GPIO_UNUSED,
|
||||
.bclk = CONFIG_MIC_SCK_GPIO,
|
||||
.ws = CONFIG_MIC_WS_GPIO,
|
||||
.dout = I2S_GPIO_UNUSED,
|
||||
.din = CONFIG_MIC_SD_GPIO,
|
||||
},
|
||||
};
|
||||
|
||||
ESP_RETURN_ON_ERROR(i2s_channel_init_std_mode(s_rx_chan, &std_cfg), TAG, "I2S std mode init failed");
|
||||
// SD tri-states outside the mic's slot; the datasheet asks for a pull-down
|
||||
gpio_pullup_dis(CONFIG_MIC_SD_GPIO);
|
||||
gpio_pulldown_en(CONFIG_MIC_SD_GPIO);
|
||||
ESP_RETURN_ON_ERROR(i2s_channel_enable(s_rx_chan), TAG, "I2S enable failed");
|
||||
|
||||
ESP_RETURN_ON_ERROR(beat_start(MIC_SAMPLE_RATE), TAG, "Beat detector start failed");
|
||||
if (xTaskCreate(mic_task, "mic", 6144, NULL, 5, NULL) != pdPASS) {
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
ESP_LOGI(TAG, "INMP441 started at %d Hz", MIC_SAMPLE_RATE);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void mic_get_level(mic_level_t *out)
|
||||
{
|
||||
portENTER_CRITICAL(&s_level_lock);
|
||||
*out = s_level;
|
||||
portEXIT_CRITICAL(&s_level_lock);
|
||||
}
|
||||
|
||||
esp_err_t mic_stream_open(void)
|
||||
{
|
||||
if (s_stream_active) {
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
xStreamBufferReset(s_stream_buf);
|
||||
s_stream_active = true;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
size_t mic_stream_read(void *buf, size_t len, TickType_t timeout)
|
||||
{
|
||||
return xStreamBufferReceive(s_stream_buf, buf, len, timeout);
|
||||
}
|
||||
|
||||
void mic_stream_close(void)
|
||||
{
|
||||
s_stream_active = false;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include "esp_err.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
|
||||
#define MIC_SAMPLE_RATE 16000
|
||||
|
||||
typedef struct {
|
||||
float rms_dbfs; // RMS level over the last block, dB relative to full scale
|
||||
float peak_dbfs; // Peak sample in the last block, dBFS
|
||||
float spl_db; // Approximate dB SPL (INMP441: -26 dBFS @ 94 dB SPL)
|
||||
} mic_level_t;
|
||||
|
||||
// Start the INMP441 I2S capture and the level-measuring task
|
||||
esp_err_t mic_start(void);
|
||||
|
||||
// Latest level reading; returns -120 dBFS until the first block arrives
|
||||
void mic_get_level(mic_level_t *out);
|
||||
|
||||
// Single-listener 16-bit mono PCM stream at MIC_SAMPLE_RATE.
|
||||
// Returns ESP_ERR_INVALID_STATE if someone is already listening.
|
||||
esp_err_t mic_stream_open(void);
|
||||
size_t mic_stream_read(void *buf, size_t len, TickType_t timeout);
|
||||
void mic_stream_close(void);
|
||||
+350
@@ -0,0 +1,350 @@
|
||||
#include "rel.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "esp_check.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_now.h"
|
||||
#include "esp_random.h"
|
||||
#include "esp_timer.h"
|
||||
#include "bench.h"
|
||||
#include "espnow_tx.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/queue.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include "freertos/task.h"
|
||||
|
||||
// Reliable-link frames live inside the existing 0x4C wire protocol as extra message types
|
||||
#define WIRE_MAGIC 0x4C
|
||||
#define M_ANNOUNCE 0x01
|
||||
#define M_DATA 0x20
|
||||
#define M_ACK 0x21
|
||||
#define M_DIGEST 0x22
|
||||
#define M_RESYNC 0x23
|
||||
#define M_ECHO 0x24
|
||||
#define F_ACK 1
|
||||
#define F_COMMIT 2
|
||||
#define HDR 9
|
||||
|
||||
#define MAX_PENDING 32
|
||||
#define MAX_TRIES 4
|
||||
#define FIRST_RETRY_MS 60
|
||||
#define DIGEST_PERIOD_US 1500000
|
||||
#define MAX_PEERS 32
|
||||
|
||||
static const char *TAG = "rel";
|
||||
|
||||
typedef struct {
|
||||
bool used;
|
||||
uint8_t mac[6];
|
||||
uint16_t seq;
|
||||
uint8_t cnt, flags, tries;
|
||||
uint32_t mask;
|
||||
uint16_t ver;
|
||||
uint8_t *msg;
|
||||
size_t len;
|
||||
int64_t next_us;
|
||||
} pend_t;
|
||||
|
||||
typedef struct {
|
||||
uint8_t mac[6];
|
||||
uint8_t len;
|
||||
uint8_t data[96];
|
||||
} rx_t;
|
||||
|
||||
typedef struct {
|
||||
bool used;
|
||||
uint8_t mac[6];
|
||||
int64_t last_ack_us;
|
||||
int fails;
|
||||
} peer_t;
|
||||
|
||||
static pend_t s_pend[MAX_PENDING];
|
||||
static peer_t s_peer[MAX_PEERS];
|
||||
static SemaphoreHandle_t s_lock;
|
||||
static QueueHandle_t s_rx;
|
||||
static uint16_t s_seq;
|
||||
static volatile uint16_t s_ver;
|
||||
static rel_stats_t s_stats;
|
||||
static rel_resync_cb_t s_resync_cb;
|
||||
|
||||
static uint32_t full_mask(int cnt)
|
||||
{
|
||||
return cnt >= 32 ? 0xFFFFFFFFu : ((1u << cnt) - 1);
|
||||
}
|
||||
|
||||
static peer_t *peer_get(const uint8_t *mac, bool create)
|
||||
{
|
||||
peer_t *free_slot = NULL;
|
||||
for (int i = 0; i < MAX_PEERS; i++) {
|
||||
if (s_peer[i].used && memcmp(s_peer[i].mac, mac, 6) == 0) {
|
||||
return &s_peer[i];
|
||||
}
|
||||
if (!s_peer[i].used && !free_slot) {
|
||||
free_slot = &s_peer[i];
|
||||
}
|
||||
}
|
||||
if (create && free_slot) {
|
||||
memset(free_slot, 0, sizeof(*free_slot));
|
||||
free_slot->used = true;
|
||||
free_slot->last_ack_us = -1;
|
||||
memcpy(free_slot->mac, mac, 6);
|
||||
}
|
||||
return create ? free_slot : NULL;
|
||||
}
|
||||
|
||||
static esp_err_t send_frag(const uint8_t *mac, uint8_t flags, uint16_t seq, uint16_t ver, const uint8_t *msg,
|
||||
size_t len, int idx, int cnt)
|
||||
{
|
||||
uint8_t frame[HDR + REL_FRAG_MAX];
|
||||
size_t off = (size_t)idx * REL_FRAG_MAX;
|
||||
size_t n = len - off > REL_FRAG_MAX ? REL_FRAG_MAX : len - off;
|
||||
frame[0] = WIRE_MAGIC;
|
||||
frame[1] = M_DATA;
|
||||
frame[2] = flags;
|
||||
frame[3] = seq & 255;
|
||||
frame[4] = seq >> 8;
|
||||
frame[5] = ver & 255;
|
||||
frame[6] = ver >> 8;
|
||||
frame[7] = idx;
|
||||
frame[8] = cnt;
|
||||
memcpy(frame + HDR, msg + off, n);
|
||||
return espnow_tx_send(mac, frame, HDR + n);
|
||||
}
|
||||
|
||||
esp_err_t rel_send(const uint8_t *mac, const void *data, size_t len, bool commit, int repeat)
|
||||
{
|
||||
if (len == 0) {
|
||||
return ESP_ERR_INVALID_SIZE;
|
||||
}
|
||||
int cnt = (len + REL_FRAG_MAX - 1) / REL_FRAG_MAX;
|
||||
if (cnt > REL_MAX_FRAGS) {
|
||||
return ESP_ERR_INVALID_SIZE;
|
||||
}
|
||||
uint8_t flags = (mac ? F_ACK : 0) | (commit ? F_COMMIT : 0);
|
||||
uint16_t ver = s_ver;
|
||||
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
uint16_t seq = ++s_seq;
|
||||
pend_t *slot = NULL;
|
||||
if (mac) {
|
||||
for (int i = 0; i < MAX_PENDING && !slot; i++) {
|
||||
slot = s_pend[i].used ? NULL : &s_pend[i];
|
||||
}
|
||||
if (!slot) {
|
||||
xSemaphoreGive(s_lock);
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
uint8_t *copy = malloc(len);
|
||||
if (!copy) {
|
||||
xSemaphoreGive(s_lock);
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
memcpy(copy, data, len);
|
||||
memset(slot, 0, sizeof(*slot));
|
||||
slot->used = true;
|
||||
memcpy(slot->mac, mac, 6);
|
||||
slot->seq = seq;
|
||||
slot->cnt = cnt;
|
||||
slot->flags = flags;
|
||||
slot->ver = ver;
|
||||
slot->msg = copy;
|
||||
slot->len = len;
|
||||
slot->next_us = esp_timer_get_time() + FIRST_RETRY_MS * 1000;
|
||||
}
|
||||
xSemaphoreGive(s_lock);
|
||||
|
||||
esp_err_t ret = ESP_OK;
|
||||
for (int r = 0; r < (mac ? 1 : (repeat < 1 ? 1 : repeat)) && ret == ESP_OK; r++) {
|
||||
for (int i = 0; i < cnt && ret == ESP_OK; i++) {
|
||||
ret = send_frag(mac, flags, seq, ver, data, len, i, cnt);
|
||||
}
|
||||
}
|
||||
if (ret != ESP_OK && slot) { // queue full: caller retries the whole message under a new sequence
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
free(slot->msg);
|
||||
slot->used = false;
|
||||
xSemaphoreGive(s_lock);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
void rel_bump_ver(void)
|
||||
{
|
||||
uint16_t v = s_ver + 1;
|
||||
s_ver = v ? v : 1; // 0 means "no state" to drivers
|
||||
}
|
||||
|
||||
uint16_t rel_ver(void)
|
||||
{
|
||||
return s_ver;
|
||||
}
|
||||
|
||||
void rel_set_resync_cb(rel_resync_cb_t cb)
|
||||
{
|
||||
s_resync_cb = cb;
|
||||
}
|
||||
|
||||
void rel_stats(rel_stats_t *out)
|
||||
{
|
||||
*out = s_stats;
|
||||
}
|
||||
|
||||
int rel_peer_status(const uint8_t mac[6], int *fails)
|
||||
{
|
||||
int age = -1;
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
peer_t *p = peer_get(mac, false);
|
||||
if (p) {
|
||||
age = p->last_ack_us < 0 ? -1 : (int)((esp_timer_get_time() - p->last_ack_us) / 1000);
|
||||
if (fails) {
|
||||
*fails = p->fails;
|
||||
}
|
||||
} else if (fails) {
|
||||
*fails = 0;
|
||||
}
|
||||
xSemaphoreGive(s_lock);
|
||||
return age;
|
||||
}
|
||||
|
||||
static rel_announce_cb_t s_announce_cb;
|
||||
|
||||
void rel_set_announce_cb(rel_announce_cb_t cb)
|
||||
{
|
||||
s_announce_cb = cb;
|
||||
}
|
||||
|
||||
static void recv_cb(const esp_now_recv_info_t *info, const uint8_t *data, int len)
|
||||
{
|
||||
int64_t now = esp_timer_get_time(); // before anything else: echoes are timing measurements
|
||||
if (len < 3 || len > (int)sizeof(((rx_t *)0)->data)) {
|
||||
return;
|
||||
}
|
||||
// A driver's boot hello is either a 0x4C ANNOUNCE or a small JSON object; everything else we
|
||||
// care about is a link reply inside 0x4C
|
||||
bool announce = (data[0] == WIRE_MAGIC && data[1] == M_ANNOUNCE) || data[0] == '{';
|
||||
bool reply = data[0] == WIRE_MAGIC && (data[1] == M_ACK || data[1] == M_RESYNC || data[1] == M_ECHO);
|
||||
if (!announce && !reply) {
|
||||
return;
|
||||
}
|
||||
if (reply && espnow_tx_drop()) { // lossy-link test: this reply never arrived
|
||||
return;
|
||||
}
|
||||
if (reply && data[1] == M_ECHO) {
|
||||
bench_on_echo(info->src_addr, data[2] | (data[3] << 8), now);
|
||||
return;
|
||||
}
|
||||
rx_t rx = { .len = len };
|
||||
memcpy(rx.mac, info->src_addr, 6);
|
||||
memcpy(rx.data, data, len);
|
||||
xQueueSend(s_rx, &rx, 0); // dropping an ack only costs a retransmit
|
||||
}
|
||||
|
||||
static void handle_rx(const rx_t *rx)
|
||||
{
|
||||
if (rx->data[0] == '{' || rx->data[1] == M_ANNOUNCE) {
|
||||
if (s_announce_cb) {
|
||||
s_announce_cb(rx->mac, rx->data, rx->len);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (rx->data[1] == M_RESYNC) {
|
||||
s_stats.resyncs++;
|
||||
if (s_resync_cb) {
|
||||
s_resync_cb(rx->mac);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (rx->len < 10) { // [4C][21][0][seq u16][cnt][mask u32]
|
||||
return;
|
||||
}
|
||||
uint16_t seq = rx->data[3] | (rx->data[4] << 8);
|
||||
uint32_t mask = rx->data[6] | (rx->data[7] << 8) | (rx->data[8] << 16) | ((uint32_t)rx->data[9] << 24);
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
for (int i = 0; i < MAX_PENDING; i++) {
|
||||
pend_t *p = &s_pend[i];
|
||||
if (p->used && p->seq == seq && memcmp(p->mac, rx->mac, 6) == 0) {
|
||||
p->mask |= mask;
|
||||
if ((p->mask & full_mask(p->cnt)) == full_mask(p->cnt)) {
|
||||
peer_t *pe = peer_get(p->mac, true);
|
||||
if (pe) {
|
||||
pe->last_ack_us = esp_timer_get_time();
|
||||
pe->fails = 0;
|
||||
}
|
||||
s_stats.acked++;
|
||||
free(p->msg);
|
||||
p->used = false;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
xSemaphoreGive(s_lock);
|
||||
}
|
||||
|
||||
static void retry_pending(void)
|
||||
{
|
||||
int64_t now = esp_timer_get_time();
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
for (int i = 0; i < MAX_PENDING; i++) {
|
||||
pend_t *p = &s_pend[i];
|
||||
if (!p->used || now < p->next_us) {
|
||||
continue;
|
||||
}
|
||||
if (p->tries >= MAX_TRIES) {
|
||||
peer_t *pe = peer_get(p->mac, true);
|
||||
if (pe) {
|
||||
pe->fails++;
|
||||
}
|
||||
s_stats.ack_timeouts++;
|
||||
free(p->msg);
|
||||
p->used = false;
|
||||
continue;
|
||||
}
|
||||
for (int f = 0; f < p->cnt; f++) {
|
||||
if (!(p->mask & (1u << f))) {
|
||||
if (send_frag(p->mac, p->flags, p->seq, p->ver, p->msg, p->len, f, p->cnt) != ESP_OK) {
|
||||
break; // queue full; try again next round
|
||||
}
|
||||
s_stats.retransmits++;
|
||||
}
|
||||
}
|
||||
p->tries++;
|
||||
p->next_us = now + ((int64_t)(FIRST_RETRY_MS << p->tries)) * 1000;
|
||||
}
|
||||
xSemaphoreGive(s_lock);
|
||||
}
|
||||
|
||||
static void rel_task(void *arg)
|
||||
{
|
||||
int64_t next_digest = 0;
|
||||
for (;;) {
|
||||
rx_t rx;
|
||||
if (xQueueReceive(s_rx, &rx, pdMS_TO_TICKS(20)) == pdTRUE) {
|
||||
handle_rx(&rx);
|
||||
continue; // drain before retrying
|
||||
}
|
||||
retry_pending();
|
||||
int64_t now = esp_timer_get_time();
|
||||
if (now >= next_digest) {
|
||||
uint16_t v = s_ver;
|
||||
uint8_t d[4] = { WIRE_MAGIC, M_DIGEST, v & 255, v >> 8 };
|
||||
if (espnow_tx_send(NULL, d, sizeof(d)) == ESP_OK) {
|
||||
s_stats.digests++;
|
||||
}
|
||||
next_digest = now + DIGEST_PERIOD_US;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t rel_init(void)
|
||||
{
|
||||
s_lock = xSemaphoreCreateMutex();
|
||||
s_rx = xQueueCreate(16, sizeof(rx_t));
|
||||
ESP_RETURN_ON_FALSE(s_lock && s_rx, ESP_ERR_NO_MEM, TAG, "alloc");
|
||||
s_seq = esp_random() & 0xFFFF; // drivers remember recent (mac, seq); a restart must not reuse them
|
||||
s_ver = (esp_random() % 0x7FFE) + 1; // new epoch per boot, so a rebooted controller never matches stale drivers
|
||||
ESP_RETURN_ON_ERROR(esp_now_register_recv_cb(recv_cb), TAG, "recv cb");
|
||||
xTaskCreate(rel_task, "rel", 4096, NULL, 6, NULL);
|
||||
ESP_LOGI(TAG, "reliable link up, state version %u", s_ver);
|
||||
return ESP_OK;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "esp_err.h"
|
||||
|
||||
// Reliable bulk link on top of espnow_tx. Wire format is documented in
|
||||
// led-driver/src/espnow_rx.py:
|
||||
// All frames are 0x4C wire packets with extra message types (see led-driver/src/espnow_rx.py):
|
||||
// data [4C][20][flags][seq u16][ver u16][idx][cnt] + fragment of an inner packet (<= 9 + 238)
|
||||
// ack [4C][21][0][seq u16][cnt][mask u32] (driver -> us)
|
||||
// digest [4C][22][ver u16] (broadcast)
|
||||
// resync [4C][23][ver u16] (driver -> us)
|
||||
// echo [4C][24][beat_idx u16] (driver -> us, bench)
|
||||
#define REL_FRAG_MAX 238 // inner packet bytes per frame; 4C 03/04 wrappers plus an envelope fit in one
|
||||
#define REL_MAX_FRAGS 32
|
||||
|
||||
typedef struct {
|
||||
uint32_t acked;
|
||||
uint32_t ack_timeouts;
|
||||
uint32_t retransmits;
|
||||
uint32_t resyncs;
|
||||
uint32_t digests;
|
||||
} rel_stats_t;
|
||||
|
||||
typedef void (*rel_resync_cb_t)(const uint8_t mac[6]);
|
||||
|
||||
esp_err_t rel_init(void);
|
||||
|
||||
// Send a message of any size up to REL_MAX_FRAGS * REL_FRAG_MAX.
|
||||
// mac == NULL broadcasts it `repeat` times with one sequence number (no acks);
|
||||
// otherwise it is unicast, acknowledged by the driver and retransmitted until
|
||||
// acked or given up on. commit makes the driver adopt the current state version.
|
||||
esp_err_t rel_send(const uint8_t *mac, const void *data, size_t len, bool commit, int repeat);
|
||||
|
||||
// A broadcast state change happened: advance the version drivers compare in digests
|
||||
void rel_bump_ver(void);
|
||||
uint16_t rel_ver(void);
|
||||
|
||||
void rel_set_resync_cb(rel_resync_cb_t cb);
|
||||
|
||||
// A driver announced itself at boot: a 0x4C ANNOUNCE packet or its JSON hello (called from the rel task)
|
||||
typedef void (*rel_announce_cb_t)(const uint8_t mac[6], const uint8_t *pkt, int len);
|
||||
void rel_set_announce_cb(rel_announce_cb_t cb);
|
||||
void rel_stats(rel_stats_t *out);
|
||||
|
||||
// Milliseconds since the driver last acked; -1 if never. fails = consecutive unacked messages
|
||||
int rel_peer_status(const uint8_t mac[6], int *fails);
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
#include "store.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "esp_check.h"
|
||||
#include "esp_littlefs.h"
|
||||
#include "esp_log.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/semphr.h"
|
||||
|
||||
static const char *TAG = "store";
|
||||
|
||||
static const char *const NAMES[] = {
|
||||
"device", "zone", "preset", "profile", "palette", "pattern",
|
||||
"sequence", "scene", "group", "output", "settings",
|
||||
};
|
||||
#define N_COLL (sizeof(NAMES) / sizeof(NAMES[0]))
|
||||
|
||||
static cJSON *s_coll[N_COLL];
|
||||
static SemaphoreHandle_t s_lock;
|
||||
|
||||
static int index_of(const char *name)
|
||||
{
|
||||
for (size_t i = 0; i < N_COLL; i++) {
|
||||
if (strcmp(NAMES[i], name) == 0) {
|
||||
return (int)i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
static esp_err_t mount(const char *label, const char *base)
|
||||
{
|
||||
esp_vfs_littlefs_conf_t conf = {
|
||||
.base_path = base,
|
||||
.partition_label = label,
|
||||
.format_if_mount_failed = true,
|
||||
};
|
||||
return esp_vfs_littlefs_register(&conf);
|
||||
}
|
||||
|
||||
static cJSON *load_file(const char *name)
|
||||
{
|
||||
char path[48];
|
||||
snprintf(path, sizeof(path), "/db/%s.json", name);
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (!f) {
|
||||
return cJSON_CreateObject();
|
||||
}
|
||||
fseek(f, 0, SEEK_END);
|
||||
long n = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
char *buf = malloc(n + 1);
|
||||
cJSON *obj = NULL;
|
||||
if (buf) {
|
||||
buf[fread(buf, 1, n, f)] = 0;
|
||||
obj = cJSON_Parse(buf);
|
||||
free(buf);
|
||||
}
|
||||
fclose(f);
|
||||
if (!cJSON_IsObject(obj)) {
|
||||
ESP_LOGW(TAG, "%s: unreadable, starting empty", path);
|
||||
cJSON_Delete(obj);
|
||||
obj = cJSON_CreateObject();
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
esp_err_t store_init(void)
|
||||
{
|
||||
s_lock = xSemaphoreCreateRecursiveMutex();
|
||||
ESP_RETURN_ON_FALSE(s_lock, ESP_ERR_NO_MEM, TAG, "mutex");
|
||||
ESP_RETURN_ON_ERROR(mount("www", "/www"), TAG, "mount www");
|
||||
ESP_RETURN_ON_ERROR(mount("db", "/db"), TAG, "mount db");
|
||||
for (size_t i = 0; i < N_COLL; i++) {
|
||||
s_coll[i] = load_file(NAMES[i]);
|
||||
ESP_LOGI(TAG, "%s: %d records", NAMES[i], cJSON_GetArraySize(s_coll[i]));
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
bool store_known(const char *name)
|
||||
{
|
||||
return index_of(name) >= 0;
|
||||
}
|
||||
|
||||
cJSON *store_coll(const char *name)
|
||||
{
|
||||
int i = index_of(name);
|
||||
return i < 0 ? NULL : s_coll[i];
|
||||
}
|
||||
|
||||
esp_err_t store_save(const char *name)
|
||||
{
|
||||
int i = index_of(name);
|
||||
ESP_RETURN_ON_FALSE(i >= 0, ESP_ERR_NOT_FOUND, TAG, "unknown collection");
|
||||
char *json = cJSON_PrintUnformatted(s_coll[i]);
|
||||
ESP_RETURN_ON_FALSE(json, ESP_ERR_NO_MEM, TAG, "print");
|
||||
|
||||
char tmp[48], path[48];
|
||||
snprintf(tmp, sizeof(tmp), "/db/%s.tmp", name);
|
||||
snprintf(path, sizeof(path), "/db/%s.json", name);
|
||||
FILE *f = fopen(tmp, "wb");
|
||||
esp_err_t ret = ESP_FAIL;
|
||||
if (f) {
|
||||
size_t len = strlen(json);
|
||||
bool ok = fwrite(json, 1, len, f) == len;
|
||||
ok = fclose(f) == 0 && ok;
|
||||
if (ok) {
|
||||
remove(path); // littlefs rename-over is not guaranteed on every version
|
||||
ok = rename(tmp, path) == 0;
|
||||
}
|
||||
ret = ok ? ESP_OK : ESP_FAIL;
|
||||
}
|
||||
free(json);
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "saving %s failed", name);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
esp_err_t store_replace(const char *name, cJSON *obj)
|
||||
{
|
||||
int i = index_of(name);
|
||||
if (i < 0 || !cJSON_IsObject(obj)) {
|
||||
cJSON_Delete(obj);
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
cJSON_Delete(s_coll[i]);
|
||||
s_coll[i] = obj;
|
||||
return store_save(name);
|
||||
}
|
||||
|
||||
void store_next_id(const char *name, char *buf, size_t len)
|
||||
{
|
||||
long max = 0;
|
||||
cJSON *c = store_coll(name), *it;
|
||||
cJSON_ArrayForEach(it, c)
|
||||
{
|
||||
char *end;
|
||||
long v = strtol(it->string, &end, 10);
|
||||
if (*end == 0 && v > max) {
|
||||
max = v;
|
||||
}
|
||||
}
|
||||
snprintf(buf, len, "%ld", max + 1);
|
||||
}
|
||||
|
||||
cJSON *store_settings(void)
|
||||
{
|
||||
return store_coll("settings");
|
||||
}
|
||||
|
||||
void store_lock(void)
|
||||
{
|
||||
xSemaphoreTakeRecursive(s_lock, portMAX_DELAY);
|
||||
}
|
||||
|
||||
void store_unlock(void)
|
||||
{
|
||||
xSemaphoreGiveRecursive(s_lock);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
#include "cJSON.h"
|
||||
#include "esp_err.h"
|
||||
|
||||
// JSON "database": one file per collection under /db, each an object of
|
||||
// id -> record, mirroring the Pi's db/*.json. Collections stay in memory and
|
||||
// are written back (via a temp file and rename) whenever they change.
|
||||
|
||||
// Mount the www and db partitions and load every collection
|
||||
esp_err_t store_init(void);
|
||||
|
||||
// Borrowed pointer to the collection object (id -> record); never NULL for a known name
|
||||
cJSON *store_coll(const char *name);
|
||||
bool store_known(const char *name);
|
||||
|
||||
// Replace a whole collection with a parsed object (takes ownership) and persist it
|
||||
esp_err_t store_replace(const char *name, cJSON *obj);
|
||||
esp_err_t store_save(const char *name);
|
||||
|
||||
// Next numeric string id for a collection ("1" when empty); writes into buf
|
||||
void store_next_id(const char *name, char *buf, size_t len);
|
||||
|
||||
// Settings are one flat object (the "settings" collection itself)
|
||||
cJSON *store_settings(void);
|
||||
|
||||
// Recursive lock around every read or write of the collections (HTTP handlers and the sequencer)
|
||||
void store_lock(void);
|
||||
void store_unlock(void);
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
#include "web.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "esp_log.h"
|
||||
|
||||
static const char *TAG = "web";
|
||||
|
||||
#define CHUNK 2048
|
||||
|
||||
static const struct {
|
||||
const char *ext;
|
||||
const char *type;
|
||||
} MIME[] = {
|
||||
{ ".html", "text/html; charset=utf-8" },
|
||||
{ ".js", "application/javascript; charset=utf-8" },
|
||||
{ ".css", "text/css; charset=utf-8" },
|
||||
{ ".json", "application/json" },
|
||||
{ ".svg", "image/svg+xml" },
|
||||
{ ".png", "image/png" },
|
||||
{ ".ico", "image/x-icon" },
|
||||
{ ".woff2", "font/woff2" },
|
||||
};
|
||||
|
||||
static const char *mime_for(const char *path)
|
||||
{
|
||||
const char *dot = strrchr(path, '.');
|
||||
for (size_t i = 0; dot && i < sizeof(MIME) / sizeof(MIME[0]); i++) {
|
||||
if (strcmp(dot, MIME[i].ext) == 0) {
|
||||
return MIME[i].type;
|
||||
}
|
||||
}
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
// path is the URL-relative name, e.g. "static/zones.js"; the file on flash is "/www/<path>.gz"
|
||||
static esp_err_t send_gz(httpd_req_t *req, const char *path, bool immutable)
|
||||
{
|
||||
char fs[128];
|
||||
if (strstr(path, "..") || snprintf(fs, sizeof(fs), "/www/%s.gz", path) >= (int)sizeof(fs)) {
|
||||
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "bad path");
|
||||
}
|
||||
FILE *f = fopen(fs, "rb");
|
||||
if (!f) {
|
||||
return httpd_resp_send_404(req);
|
||||
}
|
||||
httpd_resp_set_type(req, mime_for(path));
|
||||
httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
|
||||
httpd_resp_set_hdr(req, "Cache-Control", immutable ? "public, max-age=86400" : "no-cache");
|
||||
|
||||
char *buf = malloc(CHUNK);
|
||||
if (!buf) {
|
||||
fclose(f);
|
||||
return httpd_resp_send_500(req);
|
||||
}
|
||||
esp_err_t ret = ESP_OK;
|
||||
size_t n;
|
||||
while (ret == ESP_OK && (n = fread(buf, 1, CHUNK, f)) > 0) {
|
||||
ret = httpd_resp_send_chunk(req, buf, n);
|
||||
}
|
||||
if (ret == ESP_OK) {
|
||||
ret = httpd_resp_send_chunk(req, NULL, 0);
|
||||
}
|
||||
free(buf);
|
||||
fclose(f);
|
||||
return ret;
|
||||
}
|
||||
|
||||
esp_err_t web_send_page(httpd_req_t *req, const char *name)
|
||||
{
|
||||
return send_gz(req, name, false);
|
||||
}
|
||||
|
||||
static esp_err_t index_handler(httpd_req_t *req)
|
||||
{
|
||||
return send_gz(req, "index.html", false);
|
||||
}
|
||||
|
||||
static esp_err_t static_handler(httpd_req_t *req)
|
||||
{
|
||||
char path[96];
|
||||
const char *uri = req->uri + 1; // drop the leading '/'
|
||||
size_t n = strcspn(uri, "?");
|
||||
if (n >= sizeof(path)) {
|
||||
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "uri too long");
|
||||
}
|
||||
memcpy(path, uri, n);
|
||||
path[n] = 0;
|
||||
return send_gz(req, path, true);
|
||||
}
|
||||
|
||||
static esp_err_t favicon_handler(httpd_req_t *req)
|
||||
{
|
||||
httpd_resp_set_status(req, "204 No Content");
|
||||
return httpd_resp_send(req, NULL, 0);
|
||||
}
|
||||
|
||||
esp_err_t web_register(httpd_handle_t server)
|
||||
{
|
||||
const httpd_uri_t uris[] = {
|
||||
{ .uri = "/", .method = HTTP_GET, .handler = index_handler },
|
||||
{ .uri = "/static/*", .method = HTTP_GET, .handler = static_handler },
|
||||
{ .uri = "/favicon.ico", .method = HTTP_GET, .handler = favicon_handler },
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(uris) / sizeof(uris[0]); i++) {
|
||||
esp_err_t err = httpd_register_uri_handler(server, &uris[i]);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "register %s: %s", uris[i].uri, esp_err_to_name(err));
|
||||
return err;
|
||||
}
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include "esp_err.h"
|
||||
#include "esp_http_server.h"
|
||||
|
||||
// Register /, /settings/page, /static/* and /favicon.ico. Files come from the
|
||||
// www partition, stored as <path>.gz and sent with Content-Encoding: gzip.
|
||||
esp_err_t web_register(httpd_handle_t server);
|
||||
|
||||
// Send one of the top-level pages (e.g. "settings.html")
|
||||
esp_err_t web_send_page(httpd_req_t *req, const char *name);
|
||||
@@ -0,0 +1,8 @@
|
||||
# Name, Type, SubType, Offset, Size
|
||||
nvs, data, nvs, 0x9000, 0x6000
|
||||
otadata, data, ota, 0xf000, 0x2000
|
||||
phy_init, data, phy, 0x11000, 0x1000
|
||||
ota_0, app, ota_0, 0x20000, 0x200000
|
||||
ota_1, app, ota_1, 0x220000,0x200000
|
||||
www, data, littlefs,0x420000,0x100000
|
||||
db, data, littlefs,0x520000,0x100000
|
||||
|
@@ -0,0 +1,18 @@
|
||||
CONFIG_IDF_TARGET="esp32s3"
|
||||
# XIAO ESP32S3 USB-C is wired to the native USB Serial/JTAG
|
||||
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y
|
||||
CONFIG_ETH_USE_SPI_ETHERNET=y
|
||||
CONFIG_ETH_SPI_ETHERNET_W5500=y
|
||||
# XIAO ESP32S3 Plus: 16 MB flash and 8 MB octal PSRAM (ESP32-S3R8)
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y
|
||||
CONFIG_SPIRAM=y
|
||||
CONFIG_SPIRAM_MODE_OCT=y
|
||||
CONFIG_SPIRAM_SPEED_80M=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
||||
CONFIG_PARTITION_TABLE_FILENAME="partitions.csv"
|
||||
CONFIG_COMPILER_OPTIMIZATION_SIZE=y
|
||||
CONFIG_FREERTOS_HZ=1000
|
||||
CONFIG_ESP_WIFI_ESPNOW_MAX_ENCRYPT_NUM=7
|
||||
CONFIG_ESPNOW_CHANNEL=5
|
||||
CONFIG_BEAT_TEST_GPIO=4
|
||||
@@ -0,0 +1,8 @@
|
||||
import sys
|
||||
sys.path.insert(0, "../../src")
|
||||
from util.binary_envelope import pack_binary_envelope_v2
|
||||
p = {"p":"chase","c":["#ff0000","#0f8"],"d":120,"b":200,"a":False,"n1":5,"n2":-3,"n3":0,"n4":7,"n5":0,"n6":300}
|
||||
p2 = {"pattern":"on","colors":["#102030"],"delay":0,"brightness":0,"auto":True}
|
||||
a = pack_binary_envelope_v2(presets={"7":p,"8":p2}, brightness_0_255=128).hex()
|
||||
b = pack_binary_envelope_v2(select={"mirror":["7"],"roof":["8",12]}).hex()
|
||||
print(a); print(b)
|
||||
@@ -0,0 +1,27 @@
|
||||
// Host test: pack a preset and a select with envelope.c and print hex
|
||||
#include <stdio.h>
|
||||
#include "../main/envelope.h"
|
||||
|
||||
static void hex(const uint8_t *b, size_t n)
|
||||
{
|
||||
for (size_t i = 0; i < n; i++) printf("%02x", b[i]);
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
const char *json =
|
||||
"{\"p\":\"chase\",\"c\":[\"#ff0000\",\"#0f8\"],\"d\":120,\"b\":200,\"a\":false,\"n1\":5,\"n2\":-3,\"n3\":0,\"n4\":7,\"n5\":0,\"n6\":300}";
|
||||
const char *json2 = "{\"pattern\":\"on\",\"colors\":[\"#102030\"],\"delay\":0,\"brightness\":0,\"auto\":true}";
|
||||
cJSON *p = cJSON_Parse(json), *p2 = cJSON_Parse(json2);
|
||||
env_blob_t pb, sb;
|
||||
uint8_t out[256];
|
||||
env_blob_init(&pb); env_blob_init(&sb);
|
||||
env_add_preset(&pb, "7", p);
|
||||
env_add_preset(&pb, "8", p2);
|
||||
env_add_select(&sb, "mirror", "7", -1);
|
||||
env_add_select(&sb, "roof", "8", 12);
|
||||
hex(out, env_frame(out, 128, &pb, NULL));
|
||||
hex(out, env_frame(out, -1, NULL, &sb));
|
||||
return 0;
|
||||
}
|
||||
Executable
+97
@@ -0,0 +1,97 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Beat latency from a logic analyzer capture.
|
||||
|
||||
Reads a CSV with a time column and two digital channels: the controller beat
|
||||
marker (CONFIG_BEAT_TEST_GPIO, toggles when the first copy of a beat goes out)
|
||||
and the driver beat marker (`beat_pin`, toggles when the driver fires). For
|
||||
every controller edge it finds the next driver edge and reports the delay minus
|
||||
the deliberate lead (CONFIG_BEAT_LEAD_MS, default 30 ms).
|
||||
|
||||
Works with Saleae ("Time [s],Channel 0,Channel 1") and sigrok CSV exports, or
|
||||
any CSV whose first column is time and whose other columns are 0/1 levels.
|
||||
|
||||
analyze_edges.py capture.csv --ctrl 0 --drv 1
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import statistics
|
||||
import sys
|
||||
|
||||
|
||||
def read(path, time_scale):
|
||||
times, rows = [], []
|
||||
with open(path, newline="") as f:
|
||||
for row in csv.reader(f):
|
||||
if not row or row[0].lstrip().startswith((";", "#")):
|
||||
continue
|
||||
try:
|
||||
t = float(row[0]) * time_scale
|
||||
levels = [int(float(c)) for c in row[1:]]
|
||||
except ValueError:
|
||||
continue # header line
|
||||
times.append(t)
|
||||
rows.append(levels)
|
||||
return times, rows
|
||||
|
||||
|
||||
def edges(times, rows, ch):
|
||||
out, prev = [], None
|
||||
for t, r in zip(times, rows):
|
||||
v = r[ch]
|
||||
if prev is not None and v != prev:
|
||||
out.append(t)
|
||||
prev = v
|
||||
return out
|
||||
|
||||
|
||||
def analyze(ctrl, drv, lead_s, window_s):
|
||||
deltas, missed, j = [], 0, 0
|
||||
for i, t in enumerate(ctrl):
|
||||
nxt = ctrl[i + 1] if i + 1 < len(ctrl) else float("inf")
|
||||
while j < len(drv) and drv[j] < t:
|
||||
j += 1
|
||||
if j < len(drv) and drv[j] - t <= min(window_s, nxt - t):
|
||||
deltas.append(drv[j] - t - lead_s)
|
||||
j += 1
|
||||
else:
|
||||
missed += 1
|
||||
return deltas, missed
|
||||
|
||||
|
||||
def pct(sorted_vals, p):
|
||||
if not sorted_vals:
|
||||
return float("nan")
|
||||
k = min(len(sorted_vals) - 1, int(round(p / 100 * (len(sorted_vals) - 1))))
|
||||
return sorted_vals[k]
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("csv")
|
||||
ap.add_argument("--ctrl", type=int, default=0, help="column index of the controller marker (0 = first channel)")
|
||||
ap.add_argument("--drv", type=int, default=1, help="column index of the driver marker")
|
||||
ap.add_argument("--lead-ms", type=float, default=30.0, help="deliberate lead to subtract (CONFIG_BEAT_LEAD_MS)")
|
||||
ap.add_argument("--window-ms", type=float, default=200.0, help="longest delay still counted as the same beat")
|
||||
ap.add_argument("--time-unit", choices=("s", "ms", "us", "ns"), default="s", help="unit of the time column")
|
||||
a = ap.parse_args(argv)
|
||||
|
||||
scale = {"s": 1.0, "ms": 1e-3, "us": 1e-6, "ns": 1e-9}[a.time_unit]
|
||||
times, rows = read(a.csv, scale)
|
||||
if not times:
|
||||
sys.exit("no samples read")
|
||||
ctrl, drv = edges(times, rows, a.ctrl), edges(times, rows, a.drv)
|
||||
deltas, missed = analyze(ctrl, drv, a.lead_ms / 1000, a.window_ms / 1000)
|
||||
ms = sorted(d * 1000 for d in deltas)
|
||||
print(f"controller edges: {len(ctrl)} driver edges: {len(drv)} matched: {len(ms)} unmatched: {missed}")
|
||||
if not ms:
|
||||
sys.exit("no matched edges: check channel numbers and --time-unit")
|
||||
print(f"delay beyond the {a.lead_ms:g} ms lead (ms): min {ms[0]:.2f} mean {statistics.mean(ms):.2f} "
|
||||
f"median {pct(ms, 50):.2f} p95 {pct(ms, 95):.2f} max {ms[-1]:.2f}")
|
||||
if len(ms) > 1:
|
||||
print(f"jitter (std dev): {statistics.stdev(ms):.2f} ms")
|
||||
if a.lead_ms and ms[0] < -1:
|
||||
print("note: negative delays mean the lead is larger than the real one; check --lead-ms", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env bash
|
||||
# Minify and gzip the web UI into v2/www_dist for the `www` LittleFS partition.
|
||||
# Usage: tools/build_web.sh (needs node/npx; WWW_MAX = partition size in bytes)
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
SRC=../src
|
||||
OUT=www_dist
|
||||
MAX=${WWW_MAX:-1048576}
|
||||
rm -rf "$OUT"; mkdir -p "$OUT/static"
|
||||
|
||||
# Legacy files the v2 UI does not load
|
||||
SKIP=" app.js main.js rgb-slider.js styles.css "
|
||||
|
||||
for f in "$SRC"/static/*; do
|
||||
[[ -f $f ]] || continue
|
||||
b=$(basename "$f"); [[ $SKIP == *" $b "* ]] && continue
|
||||
case $b in
|
||||
*.min.js) cp "$f" "$OUT/static/$b" ;;
|
||||
*.js|*.css) npx --yes esbuild@0.25.0 "$f" --minify --target=es2019 --legal-comments=none \
|
||||
--outfile="$OUT/static/$b" --log-level=warning ;;
|
||||
*) cp "$f" "$OUT/static/$b" ;;
|
||||
esac
|
||||
done
|
||||
for p in index settings; do
|
||||
npx --yes html-minifier-terser@7.2.0 --collapse-whitespace --remove-comments \
|
||||
--minify-css true --minify-js true -o "$OUT/$p.html" "$SRC/templates/$p.html"
|
||||
done
|
||||
|
||||
# Ship only the .gz copies; the server sends Content-Encoding: gzip
|
||||
find "$OUT" -type f -exec gzip -9 -n -f {} \;
|
||||
find "$OUT" -name '*.gz' -exec gzip -t {} \;
|
||||
|
||||
total=$(find "$OUT" -name '*.gz' -printf '%s\n' | paste -sd+ | bc)
|
||||
echo "www_dist: $(find "$OUT" -name '*.gz' | wc -l) files, $total bytes (limit $MAX)"
|
||||
(( total <= MAX )) || { echo "ERROR: web UI exceeds www partition" >&2; exit 1; }
|
||||
Executable
+149
@@ -0,0 +1,149 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Beat latency over USB, no logic analyzer.
|
||||
|
||||
Starts the controller's synthetic beat generator, reads one timestamped line
|
||||
from each board's USB serial port, and works out how long the driver took to
|
||||
fire after the controller sent each beat.
|
||||
|
||||
controller prints BT <beat_idx> <esp_timer_us> (just before the first copy goes out)
|
||||
driver prints FIRE <beat_idx> <ticks_us> (when the beat triggers a pattern step)
|
||||
|
||||
The two boards have unrelated clocks and USB adds a variable delay of its own.
|
||||
Each board's clock is mapped onto the PC clock with the *fastest* USB deliveries
|
||||
(lower envelope of host-time minus board-time, fitted per 5 s window, so crystal
|
||||
drift is removed). Differences between the two mapped clocks are then the latency.
|
||||
What remains is the gap between the two USB paths' minimum delays (about a
|
||||
millisecond at worst) plus noise; the report prints the residual USB jitter so
|
||||
you can judge it. The driver needs "usb_log": true in settings.json.
|
||||
|
||||
usb_latency.py --ctrl-port /dev/ttyACM0 --drv-port /dev/ttyACM1 --url http://10.1.1.180
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
import serial
|
||||
|
||||
TICKS_PERIOD_US = 1 << 30 # MicroPython ticks_us wraps here
|
||||
|
||||
|
||||
class Reader(threading.Thread):
|
||||
def __init__(self, port, pattern):
|
||||
super().__init__(daemon=True)
|
||||
self.ser = serial.Serial(port, 115200, timeout=0.05)
|
||||
self.pattern = re.compile(pattern)
|
||||
self.events = [] # (idx, device_us, host_s)
|
||||
self.running = True
|
||||
self.buf = b""
|
||||
|
||||
def run(self):
|
||||
while self.running:
|
||||
try:
|
||||
chunk = self.ser.read(4096)
|
||||
except serial.SerialException:
|
||||
break
|
||||
if not chunk:
|
||||
continue
|
||||
now = time.perf_counter() # one stamp per USB chunk
|
||||
self.buf += chunk
|
||||
*lines, self.buf = self.buf.split(b"\n")
|
||||
for ln in lines:
|
||||
m = self.pattern.search(ln.decode(errors="replace"))
|
||||
if m:
|
||||
self.events.append((int(m.group(1)), int(m.group(2)), now))
|
||||
|
||||
|
||||
def unwrap(events, period=None):
|
||||
"""Make device timestamps monotonic (handles the driver's wrapping tick counter)."""
|
||||
out, add, prev = [], 0, None
|
||||
for idx, us, host in events:
|
||||
if period and prev is not None and us + add < prev - period // 2:
|
||||
add += period
|
||||
out.append((idx, (us + add) / 1e6, host))
|
||||
prev = us + add
|
||||
return out
|
||||
|
||||
|
||||
def fit_clock(events, window_s=5.0):
|
||||
"""Map device seconds to host seconds using the fastest deliveries. Returns (a, b, residuals)."""
|
||||
pts = [(d, h - d) for _, d, h in events] # (device time, host minus device)
|
||||
t0 = pts[0][0]
|
||||
mins = {}
|
||||
for d, off in pts:
|
||||
k = int((d - t0) // window_s)
|
||||
if k not in mins or off < mins[k][1]:
|
||||
mins[k] = (d, off)
|
||||
xs, ys = zip(*mins.values()) if len(mins) > 1 else (zip(*mins.values()))
|
||||
xs, ys = list(xs), list(ys)
|
||||
if len(xs) < 2:
|
||||
b, a = 0.0, ys[0]
|
||||
else:
|
||||
mx, my = statistics.mean(xs), statistics.mean(ys)
|
||||
den = sum((x - mx) ** 2 for x in xs) or 1.0
|
||||
b = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / den
|
||||
a = my - b * mx
|
||||
lowest = min(off - (a + b * d) for d, off in pts)
|
||||
a += lowest # shift so the fastest delivery sits exactly on the line
|
||||
resid = sorted((off - (a + b * d)) * 1000 for d, off in pts)
|
||||
return a, b, resid
|
||||
|
||||
|
||||
def pct(vals, p):
|
||||
return vals[min(len(vals) - 1, int(round(p / 100 * (len(vals) - 1))))]
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--ctrl-port", default="/dev/ttyACM0")
|
||||
ap.add_argument("--drv-port", default="/dev/ttyACM1")
|
||||
ap.add_argument("--url", default="http://10.1.1.180")
|
||||
ap.add_argument("--bpm", type=float, default=120)
|
||||
ap.add_argument("--beats", type=int, default=200)
|
||||
ap.add_argument("--lead-ms", type=float, default=30.0, help="CONFIG_BEAT_LEAD_MS")
|
||||
ap.add_argument("--no-start", action="store_true", help="do not start the generator (it is already running)")
|
||||
a = ap.parse_args()
|
||||
|
||||
rc = Reader(a.ctrl_port, r"\bBT (\d+) (\d+)")
|
||||
rd = Reader(a.drv_port, r"\bFIRE (\d+) (\d+)")
|
||||
rc.start(); rd.start()
|
||||
time.sleep(0.5)
|
||||
if not a.no_start:
|
||||
req = urllib.request.Request(a.url + "/test/beats", data=json.dumps({"bpm": a.bpm, "count": a.beats}).encode(),
|
||||
method="POST")
|
||||
urllib.request.urlopen(req, timeout=10).read()
|
||||
wait = a.beats * 60.0 / a.bpm + 4
|
||||
print(f"running {a.beats} beats at {a.bpm:g} BPM, about {wait:.0f} s ...")
|
||||
time.sleep(wait)
|
||||
rc.running = rd.running = False
|
||||
time.sleep(0.2)
|
||||
|
||||
ctrl, drv = unwrap(rc.events), unwrap(rd.events, TICKS_PERIOD_US)
|
||||
if len(ctrl) < 5 or len(drv) < 5:
|
||||
raise SystemExit(f"too few events: controller {len(ctrl)}, driver {len(drv)} "
|
||||
"(driver needs usb_log:true; check ports)")
|
||||
ca, cb, cres = fit_clock(ctrl)
|
||||
da, db, dres = fit_clock(drv)
|
||||
c_host = {i: d + ca + cb * d for i, d, _ in ctrl}
|
||||
lat = []
|
||||
for i, d, _ in drv:
|
||||
if i in c_host:
|
||||
lat.append((d + da + db * d - c_host[i]) * 1000 - a.lead_ms)
|
||||
lat.sort()
|
||||
print(f"controller events {len(ctrl)}, driver events {len(drv)}, matched {len(lat)}")
|
||||
print(f"clock drift: controller {cb*1e6:+.1f} ppm, driver {db*1e6:+.1f} ppm (relative to the PC)")
|
||||
print(f"USB delivery jitter above the fastest (ms), p50/p95/max: controller {pct(cres,50):.2f}/{pct(cres,95):.2f}/{cres[-1]:.2f} "
|
||||
f"driver {pct(dres,50):.2f}/{pct(dres,95):.2f}/{dres[-1]:.2f}")
|
||||
if not lat:
|
||||
raise SystemExit("no beat index matched on both ports")
|
||||
print(f"delay beyond the {a.lead_ms:g} ms lead (ms): min {lat[0]:.2f} mean {statistics.mean(lat):.2f} "
|
||||
f"median {pct(lat,50):.2f} p95 {pct(lat,95):.2f} max {lat[-1]:.2f} std {statistics.pstdev(lat):.2f}")
|
||||
print("accuracy: systematic error about +/-1 ms (difference of the two USB paths' fastest delivery); "
|
||||
"use the logic analyzer if you need better")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user