Compare commits

..
Author SHA1 Message Date
J. Nick Koston 0bb86f8094 Merge remote-tracking branch 'origin/dev' into HEAD 2026-11-14 08:37:40 -06:00
J. Nick Koston bf9e2b7a54 Merge branch 'dev' into binary-sensor-click-callback 2026-11-01 13:03:51 -10:00
J. Nick Koston fd000ead9f Merge dev 2026-11-01 11:52:49 -10:00
J. Nick Koston 42956e0173 [binary_sensor] Read the click configs once and share the test callback
Pair each click key with its detector class in one table, add the define
and create the detectors in one pass, register every test callback
through one helper, and point the skill at the in-tree example instead
of copying it.
2026-10-31 08:33:28 -10:00
J. Nick Koston 7edd1a8ea7 Merge branch 'binary-sensor-click-callback-tests' into binary-sensor-click-callback
# Conflicts:
#	tests/components/binary_sensor/click_trigger_test.cpp
2026-10-31 08:15:50 -10:00
J. Nick Koston 35e03009e6 [binary_sensor] Test that a double click resets its times
A short second press after a double click would otherwise pair with the
first release and the next gap.
2026-10-31 08:14:30 -10:00
J. Nick Koston df69028380 [binary_sensor] Test a press published by double click actions
Pin that the double click times reset before the actions run, so a
press an action publishes on the same sensor is kept.
2026-10-31 08:13:31 -10:00
J. Nick Koston 46c0cd859f Merge branch 'binary-sensor-click-callback-tests' into binary-sensor-click-callback
# Conflicts:
#	tests/components/binary_sensor/click_trigger_test.cpp
2026-10-31 07:54:21 -10:00
J. Nick Koston 419660bb67 [binary_sensor] Fix clang-tidy in the click test and hold the press after a double click 2026-10-31 07:54:11 -10:00
J. Nick Koston 22ba443107 [binary_sensor] Fix clang-tidy in the click test and hold the press after a double click 2026-10-31 07:54:08 -10:00
pre-commit-ci-lite[bot] 4015cea895 apply automatic formatting fixes 2026-10-31 17:51:49 +00:00
J. Nick Koston d4a8b149a9 [binary_sensor] Name the click detectors and build them as callback entries
Rename the state objects to ClickDetector and DoubleClickDetector with
check(), write the detector id as ::id through ApplyCall so a trigger id
named like the callback parameter cannot hide it, build both automations
from _CALLBACK_AUTOMATIONS, share one schema helper, and document the
stateful filter pattern in the automations skill.
2026-10-31 07:46:59 -10:00
J. Nick Koston 97732c9a25 [binary_sensor] Build on_click and on_double_click as callback automations
The click timing moves into small ClickState and DoubleClickState objects
that a generated state callback asks, so an automation whose actions are
all inline runs as one function with no Trigger or Automation object.
ClickTrigger and DoubleClickTrigger are removed; only codegen used them.
2026-10-31 07:40:40 -10:00
J. Nick Koston e3bb14be43 [binary_sensor] Add tests for the click and double click triggers
Pin the click and double click timing with a C++ unit test, and the
generated trigger code with a codegen test.
2026-10-31 07:38:50 -10:00
722 changed files with 4901 additions and 30261 deletions

No files matched your search

+9 -2
View File
@@ -123,10 +123,17 @@ Both live in `esphome/core/helpers.h` and accept `std::function`, lambdas and fo
their templatized `add()` method. `LazyCallbackManager` is a drop-in replacement for `CallbackManager` that defers allocation until the first
callback is added. Prefer it for entity-level callbacks where most instances have no subscribers.
A filter that keeps state between calls (timing, edges) still needs no Trigger class: give each automation a
small object with constant initializers, created from its `CONF_TRIGGER_ID` before the automations are built,
and let `when` ask it, e.g. `ApplyCall("{}->check(state, {}, {})", ((CONF_TRIGGER_ID, ...), ...))`. An `ID`
value in an `ApplyCall` is written as `::id`, so a callback parameter cannot hide it. `on_click` in
`esphome/components/binary_sensor/__init__.py` is the in-tree example; once a second component needs this,
move the object creation into `CallbackAutomation`.
## Triggers: Trigger class method
Use `build_automation()` with a `Trigger<Ts...>` subclass only when the forwarder needs **mutable state
beyond a single `Automation*` pointer** (e.g. edge detection tracking previous state, timing logic).
Use `build_automation()` with a `Trigger<Ts...>` subclass only when the state must be set up from the
parent (in the constructor or in `setup()`), or the trigger needs its own timers.
**Python:**
```python
+5 -36
View File
@@ -47,15 +47,6 @@ driven, what the logs show, and the same flow on a `dev` build when a quirk coul
piped, or lines land minutes late. Bound every long command with `timeout` (coreutils) or
`perl -e 'alarm shift; exec @ARGV' <seconds> <command>` on macOS without it. Save an exit code with `rc=$?`
right after the command: in `echo "$(date +%T) rc=$?"` the command substitution runs first and `$?` reads 0.
8. **Give builds a private PlatformIO directory when sessions may use different Pythons.** ESPHome stamps the
PlatformIO core directory with the Python version that last built, and a build from another version wipes and
reinstalls the shared packages under every other build. Set `PLATFORMIO_CORE_DIR=<scratch>/pio` on every
compile and upload (`scripts/pio_build.sh` does). Old releases and framework A/B builds need one too
(see `reference/boards.md`).
9. **One ESP-IDF or LibreTiny build at a time on a shared machine.** Concurrent builds race over tool caches. Wrap
compiles in a lock (`BUILD_LOCK` for `scripts/pio_build.sh`, for example a script that holds a `mkdir` lock).
10. **Check that the stimulus ran.** A load or soak run where most requests failed was not loaded, and a capture
that stopped early covers nothing; check the driver's own counters before reading the device's verdict.
## Workflow
@@ -90,17 +81,7 @@ driven, what the logs show, and the same flow on a `dev` build when a quirk coul
> Automated testing results
```
Then one short sentence saying what was tested (builds and SHAs, board, what was driven), and on the next line a
bold result, one of **Test result: PASS**, **Test result: FAIL**, **Test result: PASS WITH CAVEATS** or
**Test result: UNCLEAR**, followed by one sentence with the key numbers (for example "the device closed none of 32
streams, dev closed 12 of 16"). FAIL means a regression or a fix that does not work. PASS WITH CAVEATS means it works
but something about the change itself needs a look; name the caveat in that sentence. A limit of the test (the
original crash did not reproduce) or a device or network quirk the tooling reported correctly is not a caveat on
the change; say it as a separate note. UNCLEAR means the run could not decide; say what is
missing. A reader must not have to dig through the table or guess. Side findings that do not change the result (a
bug already on `dev`, a one-off oddity) go in the bullets, marked as separate from the result.
Then a results table
Then one short sentence saying what was tested (builds and SHAs, board, what was driven), a results table
(build SHA, board and framework, what was driven, counts, result, plus the `dev` control row), short bullets
for the findings, and the setup and exact flow in a collapsed `<details>` block. Answer any question asked on
the PR directly in the comment. No credentials, SSIDs, IP addresses, port names or other bench details.
@@ -137,13 +118,8 @@ ESP-IDF OTA image: `.esphome/build/<name>/build/firmware.ota.bin`. LibreTiny OTA
and then; retry up to three times.
- `api_button.py HOST KEY list|press NAME [...]`: list a device's template buttons or press them over the API; the
recipes drive their test configs with it.
- `apiconn.py`: `connect(host, tries, port, on_stop)` (API connect and login with retries, `API_KEY` from the env),
`log_text()` (an API log line without ANSI codes), `stop_event()` (an Event set when the connection ends),
`ble_connect()` (wait for an advert, connect through a proxy without a cache like Home Assistant) and
`enable_notify()` (start notify and write the CCCD), imported by the API drivers.
- `pio_build.sh compile|upload NAME YAML [DEVICE] [esphome options]`: build or upload YAML as `-s name NAME` from
`TREE` with a private PlatformIO directory, an import check and an optional `BUILD_LOCK`; logs to `NAME-*.log`.
- `resolve.sh NAME [TRIES]`: the address of `NAME.local` once it resolves and answers a ping.
- `apiconn.py`: `connect(host, tries)` (API connect and login with retries, `API_KEY` from the env) and `log_text()`
(an API log line without ANSI codes), imported by the newer API drivers.
- `wifisave_hammer.sh KIND DUT_PORT DUT_YAML DUT_TREE CLIENT_PORT CLIENT_YAML CLIENT_TREE [SETTLE]`:
the fallback AP plus captive portal hammer end to end (compile, flash, capture, counts) with the
templates below. KIND is `esp`, `pico`, `bw15` or `bk`. It ends with `RESULT PASS` (exit 0),
@@ -158,7 +134,7 @@ recorder, dump saver and decoder, cover cycle driver), `online_image/`
(host driver, Zephyr driver probe), `rtsp_server/` (protocol client, raw rate reader, measurement set,
API image grab), `cse7766/` (API observer with ping), `zephyr_coredump/` (reader flow, decode with the
Zephyr tools), `libretiny_prefs/` (rtc preference harness header), `libretiny_crash/` (BK72xx crash probe header,
capture decoder, RTL8720C ROM dump versus report matcher), `api_outgoing/` (wake cycle and Wi-Fi drop timing readers), `ld2450/` (zone number driver, loopback harness driver with number and binary sensor states and TX frame summarizer, frame stream harness with presence hold and link loss drivers, BT MAC driver), `api/` (raw plaintext native API client for user defined actions, store_yaml recovery client over Noise or plaintext, `overflow/` API overflow buffer counters with a sensor config generator), `http_request/` (update manifest server, update state driver, request test server, action case driver, concurrency, reboot, update check and OTA drivers, `ota_auth/` OTA request cases with basic auth), `modem/` (button and sensor driver over the plaintext API, also used for the BLE MIDI boards, AT commands for the UART passthrough), `dfrobot_sen0395/` (API driver and case runner), `homeassistant_light/` (direct bulb driver, held-report case driver), `usb_audio/` (URL player), `speaker_media_player/` (API player driver, pipeline task case runner), `web_server/` (SSE client, request mix, SSE and HTTPD case runners, per-session `/events` listing check with its config, `/events` head, multi-client, stall, Wi-Fi drop and churn modes with their config, head comparer and runner, `async_bump/` ESPAsyncWebServer bump flows and ESP8266 web OTA cases), `mqtt/` (`ha_discovery/`, `disable/`, `retained_burst/` and `reconnect/` runners; broker config with TLS, client-certificate and WebSocket listeners, test CA with server and client certificates, transport case runner, flash-and-drive runner, CLI TLS check without a board, MAC suffix runner with per-variant configs for two boards, `shutdown/` shutdown message runner and matcher), `udp/` (datagram recorder, `udp.write` payload checker and case driver), `entity_icons/` (icon and device class readback over the API, MQTT discovery, web_server and dump_config, with a comparer), `uart_sim/` (API driver and flash, capture and drive runner for the simulated UART sensors), `remote_base/` (loopback runner and API log decoder per sent frame), `xiaomi_ble/` (frame and header generator with the expected counts, injecting, advertising and receiving configs, counter and runner), `ble_terminate/` (proxy and peer configs, connect and disconnect driver, peer disconnect matcher, runner), `i2c_slave/` (D1 mini slave and BK7238 master configs), `wpa3_ap/` (PMF AP with join and leave logging, BK7238 and CB3S DUTs, runner and summary), `wisp_ap/` (WISP upstream with AP buttons, WISP and ALWAYS_ON DUTs, client, runner and per phase summary), `wifi_restart/` (WPA3 mixed WISP upstream, static IP DUTs with syslog, runner and summary), `ota_timing/` (OTA upload timer with deflate, raw and TCP modes, API build check, A/B runner and median summary, `inflate_bench/` on-device inflate benchmark with stream generator, configs and syslog runner), `gpio_hold/` (ISR pin hold self test with ESP32 and S3 configs), `ble_event_inject/` (GAP and GATTC event injector header and proxy package), `light_sleep_wake/` (LEDC wave and edge timer for light sleep wakeup on a C3, external wave generator and per-call edge detail probe for peripheral power-down on the P4), `manual_ip/` (station and AP manual IP configs, DNS probe and runners), `web_handlers/` (late handler, web_server, captive_portal and prometheus variants, web OTA runner), `bk72xx_flash/` (flash readback with retries, per partition diff of two dumps), `ble_server_security/` (secure GATT server and pairing client configs, driver, summary and runner), `prometheus/` (datetime metrics configs and driver), `zephyr_ble_server/` (nRF52 server, looping ESP32 client and UF2 flash and count runner), `ble_adv_triggers/` (advertiser with six raw frames, ESP32 and BK72xx receivers with eleven triggers, runner and checker), `sun/` (longitude sweep package, runner and checker), `sensor_filters/` (every filter shape with a fixed input sequence, per-board packages and runner), `led_driver_sniff/` (SPI slave capture header with selftest, config generator, window comparer and runner), `hub_input_sim/` (keypad, wiegand and rdm6300 simulation on a D1 mini, API log runner), `value_range/` (on_value_range sequence with a restart, runner), `ezo_fake_bus/` (fake EZO I2C bus and step config, runner), `twai_self/` (TWAI self-reception header, on_frame config and counter runner), `ota_automations/` (OTA automation package for both OTA platforms, four case runner, repeated web upload runner and per case summary), `output_button/` (pad edge timer header, button package and runner), `homeassistant_button/` (raw plaintext API client for action calls and wizard inputs, package and runner), `uart_button/` (UART0 loopback package, API driver with TX and RX counts, runner), `interval/` (plain and delayed interval package, timing summary and runner), `smp_udp_ota/` (SMP reset fault injector, OTA runner, per mode result check, MCUboot swap limit, running image check and slot blanking UF2, ThreaLine truncated
capture decoder, RTL8720C ROM dump versus report matcher), `api_outgoing/` (wake cycle and Wi-Fi drop timing readers), `ld2450/` (zone number driver, loopback harness driver with number and binary sensor states and TX frame summarizer, frame stream harness with presence hold and link loss drivers, BT MAC driver), `api/` (raw plaintext native API client for user defined actions, store_yaml recovery client over Noise or plaintext), `http_request/` (update manifest server, update state driver, request test server, action case driver, concurrency, reboot, update check and OTA drivers, `ota_auth/` OTA request cases with basic auth), `modem/` (button and sensor driver over the plaintext API, also used for the BLE MIDI boards, AT commands for the UART passthrough), `dfrobot_sen0395/` (API driver and case runner), `homeassistant_light/` (direct bulb driver, held-report case driver), `usb_audio/` (URL player), `speaker_media_player/` (API player driver, pipeline task case runner), `web_server/` (SSE client, request mix, SSE and HTTPD case runners), `mqtt/` (`ha_discovery/`, `disable/`, `retained_burst/` and `reconnect/` runners; broker config with TLS, client-certificate and WebSocket listeners, test CA with server and client certificates, transport case runner, flash-and-drive runner, CLI TLS check without a board, MAC suffix runner with per-variant configs for two boards, `shutdown/` shutdown message runner and matcher), `udp/` (datagram recorder, `udp.write` payload checker and case driver), `entity_icons/` (icon and device class readback over the API, MQTT discovery, web_server and dump_config, with a comparer), `uart_sim/` (API driver and flash, capture and drive runner for the simulated UART sensors), `remote_base/` (loopback runner and API log decoder per sent frame), `xiaomi_ble/` (frame and header generator with the expected counts, injecting, advertising and receiving configs, counter and runner), `ble_terminate/` (proxy and peer configs, connect and disconnect driver, peer disconnect matcher, runner), `i2c_slave/` (D1 mini slave and BK7238 master configs), `wpa3_ap/` (PMF AP with join and leave logging, BK7238 and CB3S DUTs, runner and summary), `wisp_ap/` (WISP upstream with AP buttons, WISP and ALWAYS_ON DUTs, client, runner and per phase summary), `wifi_restart/` (WPA3 mixed WISP upstream, static IP DUTs with syslog, runner and summary), `ota_timing/` (OTA upload timer with deflate, raw and TCP modes, API build check, A/B runner and median summary, `inflate_bench/` on-device inflate benchmark with stream generator, configs and syslog runner), `gpio_hold/` (ISR pin hold self test with ESP32 and S3 configs), `ble_event_inject/` (GAP and GATTC event injector header and proxy package), `light_sleep_wake/` (LEDC wave and edge timer for light sleep wakeup on a C3, external wave generator and per-call edge detail probe for peripheral power-down on the P4), `manual_ip/` (station and AP manual IP configs, DNS probe and runners), `web_handlers/` (late handler, web_server, captive_portal and prometheus variants, web OTA runner), `bk72xx_flash/` (flash readback with retries, per partition diff of two dumps), `ble_server_security/` (secure GATT server and pairing client configs, driver, summary and runner), `prometheus/` (datetime metrics configs and driver), `zephyr_ble_server/` (nRF52 server, looping ESP32 client and UF2 flash and count runner), `ble_adv_triggers/` (advertiser with six raw frames, ESP32 and BK72xx receivers with eleven triggers, runner and checker), `sun/` (longitude sweep package, runner and checker), `sensor_filters/` (every filter shape with a fixed input sequence, per-board packages and runner), `led_driver_sniff/` (SPI slave capture header with selftest, config generator, window comparer and runner), `hub_input_sim/` (keypad, wiegand and rdm6300 simulation on a D1 mini, API log runner), `value_range/` (on_value_range sequence with a restart, runner), `ezo_fake_bus/` (fake EZO I2C bus and step config, runner), `twai_self/` (TWAI self-reception header, on_frame config and counter runner), `ota_automations/` (OTA automation package for both OTA platforms, four case runner, repeated web upload runner and per case summary), `output_button/` (pad edge timer header, button package and runner), `homeassistant_button/` (raw plaintext API client for action calls and wizard inputs, package and runner), `uart_button/` (UART0 loopback package, API driver with TX and RX counts, runner), `interval/` (plain and delayed interval package, timing summary and runner), `smp_udp_ota/` (SMP reset fault injector, OTA runner, per mode result check, MCUboot swap limit, running image check and slot blanking UF2, Thread device config), `ld2420_sim/` (fake LD2420 answering the hub's commands on a UART0 loopback, API state recorder, two-build comparer and runner), `nrf52_tcp_probe/` (TCP and UDP socket probe config, build and log check, API check over Thread), `rs485_frame/` (simulated DLE/STX/ETX bus device, frame and Line truncated
## Templates in `$SKILL/templates`
@@ -167,8 +143,6 @@ capture decoder, RTL8720C ROM dump versus report matcher), `api_outgoing/` (wake
- `client-wifisave.yaml` (package): joins that AP, posts N bogus `/wifisave` requests, then the real
credentials from `!secret`. `example-client.yaml` is the per-run file. `bogus_saves: "1"` gives a
plain provisioning check.
- `diagnostics.yaml` (package): DEBUG logs, esphome OTA, uptime, free heap, reset reason and a 200 ms counter
for soak and load tests.
- Per-topic device configs, each described in `reference/recipes/<component>.md`: `online-image-dut.yaml`,
`usb-cdc-acm-dongle-dut.yaml`, `nrf52-preferences-dut.yaml`, `rtsp-waveshare-s3-eth-dut.yaml`,
`waveshare-s3-eth-camdiag.yaml`, `s31-cse7766-dut.yaml`, `nrf52-coredump-crash-dut.yaml`,
@@ -185,8 +159,7 @@ capture decoder, RTL8720C ROM dump versus report matcher), `api_outgoing/` (wake
action package with per-board files and an OTA flash variant), `led_wire/` (DUT config and header that reads the
LED strip pads back with RMT RX and an SPI slave), `uart_sim/` (simulator header, common package, per-build parts and run files) and `remote_base/` (common
package, transmit script, per-board templates and the ESP8266 software sender), `i2c_fake/` (fake I2C device
headers with their test configs, see `fake_i2c.md`), `network_dns/` (DNS loss diagnostics for
`network: priority`, see `network_dns.md`).
headers with their test configs, see `fake_i2c.md`).
- `microphone_http_stream/`: base config, fake counter and USB microphone variants and the multi-reader client,
described in `reference/recipes/microphone_http_stream.md`.
@@ -223,10 +196,6 @@ comment quotes the exact commits. Fetch `origin dev` before computing a merge ba
the shared `~/.platformio/platforms/libretiny`, so every later build on the machine uses the patched copy. Patch
through the ESPHome side (a linker `-Wl,-wrap,<symbol>` or a define) instead, and if it happened, restore the
directory from a clean copy of the same release.
- Copying a .uf2 to a mounted bootloader drive (`RPI-RP2`, `ITSY840BOOT`) from a terminal on macOS can fail with
"Operation not permitted" (the Removable Volumes privacy permission), and picotool then sees no device. Flash through
the serial path instead (`esphome upload --device <port>`: the 1200 baud touch on RP2, serial DFU on Adafruit nRF52
boards) or by OTA; a board that only shows the drive needs the file dragged in Finder.
- `wc -l` pads its count on macOS, so `tail -n +$n0` needs `$((n0+0))` or an arithmetic expansion.
- `api:` reboots a board after 15 min without a client: `reboot_timeout: 0s` on `api:` and `mqtt:` for
soak tests.
@@ -5,15 +5,13 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
## ESP8266 (D1 mini, NodeMCU, CH340 or CP2102)
- Opening the port usually resets the board through DTR, but not always, and on a CH340 even with `--released`, so
the first boot (or `Connection lost`) in a capture can be that reset; `serial_capture.py --reset` pulses RTS to
capture from boot. 74880 baud shows the ROM boot messages (`rst cause`, `boot mode`).
- Opening the port usually resets the board through DTR, but not always; `serial_capture.py --reset`
pulses RTS to capture from boot. 74880 baud shows the ROM boot messages (`rst cause`, `boot mode`).
- UART0 can be looped back onto itself (`USC0(0) |= (1 << UCLBE)` in an `on_boot` lambda) so a UART
component is testable without its device: frames written with `uart.write` arrive on RX. Log over the
API with `logger: baud_rate: 0`, since the serial port carries the component's bytes.
- `esphome logs` on some CH340s emits thousands of duplicated garbage lines right after the RTS reset;
a plain pyserial capture at 115200 is reliable. A CH340 can also give garbage at 921600 baud;
`logger: baud_rate: 460800` with `serial_capture.py --baud 460800` carries long `dump: raw` frames cleanly.
a plain pyserial capture at 115200 is reliable.
- A failed esptool write can wedge the adapter (`termios` error 22, or an open that hangs) until replug.
- The preference sector survives a reflash: a provisioned API key or saved Wi-Fi credentials stay
active. `esptool erase_flash` gives a clean device.
@@ -31,13 +29,6 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
interrupt handler; `Software Watchdog` with `pm_send_nullfunc` means the loop was busy too long. Code that takes
interrupt locks needs a load run to show either (`scripts/esp8266_lock_load/`, see recipes/one_wire.md).
- `GPI` bits 16 to 31 are strapping bits (mask with 0xFFFF). GPIO16 has no interrupt; read `GP16O` for an output.
- Cover positions and other restored entity state live in RTC memory by default, so they survive `erase_flash`
and a dev build's state carries into the next build's first boot. Set `esp8266: restore_from_flash: true` on A/B
configs that erase between builds.
- The ROM `rijndaelKeySetupEnc` at 0x40009300 builds a correct 128-bit schedule (FIPS-197 A.1 words match) but does not
return the round count, so the SDK's `aes_encrypt` loops on garbage rounds and the board Soft WDT resets in
`rijndaelEncrypt`. Do not `--defsym` it over the libcrypto copy; a wrapper in the SDK signature (returns -1 unless
128 bits, calls the ROM, returns 10) passed the FIPS vectors and a WPA2 soft AP join.
## ESP32 classic devkit
@@ -59,8 +50,6 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
- An ESP32 whose bootloader has no app rollback is protected only by `safe_mode` after a bad OTA. Before sending a
change to such a device that nobody can reach by hand, boot the same code on a devkit first and keep a fallback
image of the merge base built.
- On modules where GPIO16 and GPIO17 are taken by the module itself (PSRAM on WROVER modules, for example), a
`uart:` bus on those pins boot-loops with a watchdog reset during setup. Use GPIO21 and GPIO22.
## ESP32-S3, C3, C6, H2 with native USB
@@ -83,27 +72,6 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
- A board left in the ROM bootloader after an upload (BOOT held, or the USB JTAG reset landing in download mode
again) starts its app without a replug through `esptool --port <port> --after watchdog-reset chip-id`; flash a
minimal Wi-Fi plus API image first when recovering from a crash-looping one.
- On macOS a software reboot of an ESP32-C3 does not drop its USB JTAG serial port: pyserial keeps reading and gets
no error, so a client that watches for a port reset misses it. Count ESPHome's `Running through setup()` line
instead.
- W5500 SPI Ethernet with IPv6 on (seen on an ESP32-S3, #22676): every `safe_reboot()` (OTA, restart button)
aborts while an API client is subscribed to logs. `mdns_free()` leaves the IPv6 group inside `tcpip_api_call`, the
W5500 driver logs "IPv6 multicast is always filtered in by W5500", the logger sends that line to the API inline,
and the nested `LwIPLock` in `setsockopt(TCP_NODELAY)` releases the core lock it did not take, so `udp_recv`
asserts. No crash with IPv6 off, with no log subscriber (a connected client that does not subscribe is fine), or
on RMII Ethernet. Reading the crash record afterwards: `recipes/crash_report.md`.
- `usb_serial_jtag` holds a `NO_LIGHT_SLEEP` power lock by itself, so a light sleep soak on a native USB board logs
to UART0 instead (see `recipes/light_sleep_gpio_wake.md`).
- The Waveshare ESP32-P4-WIFI6 needs `engineering_sample: true`. Its Wi-Fi is an ESP32-C6 over SDIO through
`esp32_hosted`; a test with no network logs over UART0 to the CH343 console.
- ESP32-S3: GPIO43/44 cannot be used to cross-wire two UARTs: the UART0 IOMUX TX is lost when another UART takes the
pad as RX. TX17/RX16 and TX16/RX17 work. A task woken by `vTaskDelay` runs about 0.5 ms after the tick, on dev too.
## ESP32-C2 (ESP8684, 26 MHz crystal)
- Boards with a 26 MHz crystal print the ROM banner (`ESP-ROM:esp8684`) at 74880 baud; at 115200 it is garbage.
- ESP-IDF builds need `esp32: framework: sdkconfig_options: {CONFIG_XTAL_FREQ_26: y}`, or the app console runs at
the wrong baud rate (the upload log warns `Crystal frequency mismatch`).
## RP2040 / RP2350 (Pico W, Pico 2 W)
@@ -131,27 +99,6 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
each RD_REQ with one byte from a 256-byte register file, so any read length works (used for BME280/BMP280 in
esphome#22236). The ESP32-S3 I2C slave v2 driver is not usable for register emulation: answering from a task or
straight from the interrupt both gave shifted multi-byte reads.
- RP2350 PIO instruction memory survives a reflash (the 1200 baud touch and the UF2 reboot), so a program loaded by
the previous firmware can hide a missing `pio_add_program`. Clear it from an `on_boot` priority 1000 lambda
(`pio1->instr_mem[i] = 0` for i < 32) to start from power-on state; `scripts/pio_probe/pio-common.yaml` does.
- `RP2Preferences::reset()` erases the flash sector but not the RAM copy the preferences load from, so the LibreTiny
`on_boot` wipe-once pattern still boots with the old saved Wi-Fi credentials. Use a fallback AP config with
`networks:` and a fresh `name:` per build instead.
- WIZnet W5100S-EVB-Pico (RP2040, `rp2: board: wiznet_5100s_evb_pico`): W5100S on SPI with CLK 18, MOSI 19, MISO 16,
CS 17, INT 21, RST 20 (`ethernet: type: W5100`). ESPHome firmware gives it no USB CDC port; reach it over Ethernet,
OTA by address, and flash it over USB only through BOOTSEL and the UF2 drive. Keep `interrupt_pin` in every build:
without it OTA starves and never completes (`recipes/arduino_pico.md`), which strands the board until a USB flash.
The W5100S answers ICMP in hardware, so a ping reply says nothing about the RP2040; probe TCP instead (OTA port
2040, API 6053, HTTP 80). In safe mode only 2040 answers.
- Through a Pico W `bluetooth_proxy`, about 1 to 2 in 5 BLE connects fail with 0x3E (`connect err=62` in the
client) on every build; retry.
- arduino-pico framework bumps and the RPAsyncTCP SSE stall: see `recipes/arduino_pico.md`.
- USB CDC sends nothing until the host asserts DTR; a client that opens with DTR low (`improvcli.py` without
`--keep-dtr`) sees silence.
- Powering a breakout from the Pico: use 3V3(OUT), pin 36. Pin 37 is 3V3_EN, which switches the Pico off when pulled
low.
- W5100S-EVB-Pico with its USB attached shows a CDC port (`2e8a:1027`) while it runs ESPHome, so `esphome upload
--device <that port>` (picotool) flashes it with or without `interrupt_pin`.
## BW15 kit (RTL8720CF, LibreTiny rtl87xx)
@@ -193,14 +140,6 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
- Wrong-MD5 OTA test without changing firmware: monkeypatch `espota2.hashlib.md5` so only the image checksum (data
over 64 KB) returns a wrong hexdigest. Give each build its own `name:` and read `device_info().name` after a
restart to see which image booted.
- Logger UART: `DEFAULT` is UART2 (the kit's USB serial). `hardware_uart: UART1` hangs after the boot banner and
never joins Wi-Fi, on dev too. `UART0` moves both ESPHome and `lt_log` output off the kit's port. LibreTiny's own
`LT_I` lines need `framework: loglevel: info` (the default is warn).
- A config with no Wi-Fi network and no `ap:` resets about 10 s into setup when it has `web_server:` (dev too):
`web_server` setup blocks with no interface up, and no crash record is left. VERBOSE logs show the last
`Setup <component>` line.
- A BW15 kit whose CH340 drops off the bus at "Initializing WIFI" on every boot (a boot loop on any image) is short of
USB power: use another hub port or a powered hub. Read the results over API logs between resets meanwhile.
## BK7238, WB3S, CB3S (BK7231N) (LibreTiny bk72xx, CH340, RTS on CEN)
@@ -252,9 +191,6 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
... !=`) and the old image stays.
- Power save: on the BK7238, `power_save_mode: light` with LibreTiny 1.14.0 gives ping times of 3 to 6 s because
the BDK sets a listen interval of 30 beacons when `CFG_LOW_VOLTAGE_PS` is 1 (esphome#19491).
- LibreTiny's builder adds `-D'delay(ms)=delayMilliseconds(ms)'`, so `esphome::delay` is really
`esphome::delayMilliseconds` on BK72xx and a YAML lambda calling `delay()` fails to compile on dev. In a header use
`(esphome::micros)()` to dodge the `main.cpp` function-like macros.
## BW12 and other AmebaZ boards (RTL8710BX, LibreTiny rtl87xx)
@@ -329,10 +265,6 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
partition even when the upgrade state is still `UPG_STATE_DOWNLOAD_ING` (esphome#22111).
- Without serial access to recover, never send a corrupted image; wrong-MD5 and cut-upload tests with valid
images are safe.
- On the WL2H-U `logger: hardware_uart: DEFAULT` resolves to UART1, LibreTiny's log port for that board.
- Over a poor link (about 60 ms ping and 5 % loss) an ESPHome OTA takes anywhere from 50 to 445 s and a web `/update`
of a UF2 can abort early while ESPHome OTA still works. Treat such a board's results as crash or no crash only, and
settle questions about rates, heap after streams or OTA aborts on a BK7238 (same LibreTiny AsyncTCP).
## nRF52840
@@ -362,10 +294,6 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
the port open, and the logger warns `logger took a long time`. Print one line per `loop()` instead.
- Zephyr settings survive a reflash: key a `restore_value` global by a `run` substitution when a test needs
a never-saved value.
- `2fe3:0100` is Zephyr's default USB VID:PID, so `ports.py` labels any board running a Zephyr ESPHome build as an
nRF52840 Dongle. Tell an ItsyBitsy from a PCA10059 with a 1200 baud touch: the ItsyBitsy shows its `ITSY840BOOT`
UF2 volume, the PCA10059 its Nordic DFU port.
- nRF52 Zephyr builds use newlib; the nRF54LM20 builds use picolibc.
- Thread: nRF52 `openthread:` accepts only `tlv:`; the individual keys (network_key, channel, ...) are rejected at
validation. To list nearby networks with channel and PAN ID, call
`otThreadDiscover(InstanceLock::acquire().get_instance(), 0, 0xFFFF, false, false, cb, nullptr)` from an
@@ -419,16 +347,6 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
- BDK headers such as `power_save_pub.h` have no `extern "C"`; wrap them when including them from the Arduino
core's C++ files.
## Shared PlatformIO directory
- The stamp file is `.esphome.pio.stamp.json`; a mismatch deletes `packages`, `platforms` and `.cache`.
- Building an old release (2025.7.0, Arduino ESP32) against the shared directory swapped `tool-scons` for an older
version and broke it midway (`No module named 'SCons.SConf'`) for every PlatformIO build until a newer build
reinstalled it. Build old releases with their own `PLATFORMIO_CORE_DIR`.
- Two arduino-pico framework versions share the plain `framework-arduinopico` package directory, so an A/B swaps the
framework on every build; give each side its own `PLATFORMIO_CORE_DIR`.
- The general rule (a private directory whenever sessions may use different Pythons) is ground rule 8 in `SKILL.md`.
## LibreTiny crash and abort() facts (esphome#21596, #22288)
- `abort()` on dev: the BK7238 hangs for good (the main loop stops and the watchdog never fires once Wi-Fi is up;
@@ -508,45 +426,3 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
- LED0 P1.22, LED1 P1.25; BUTTON0 P1.26, BUTTON1 P1.09, BUTTON2 P1.08, BUTTON3 P0.05 (active low, pull-up). GPIO
P1 registers at 0x500D8200 (IN +0x00C, PIN_CNF +0x080), P0 at 0x5010A200.
- Binary sensor state changes are not logged at DEBUG; log the states or count `on_press` to see button presses.
- FICR INFO.PART reads 0x054BC20B; the build target is `nrf54lm20dk`.
- Zephyr `micros()` on nRF has 30.5 us resolution. Time short blocks with the DWT cycle counter instead; nRF54L idle
clears `DWT_CTRL`, so enable it again before each timed block.
- The nrf52 logger defaults to USB_CDC (the chip's own USB); set `logger: hardware_uart: UART0` to get the log on the
J-Link VCOM port.
- I2C (#22642): TWIM21 only takes pins on P1 or P3; P0 pins are rejected at config. BUTTON1 (P1.09) and BUTTON2
(P1.08) pads work as SDA and SCL. A bus with no pull-ups times out (-116) on every scan address, so setup takes
about 56 s. The JLinkExe `st` command reads VTref to check the I/O voltage.
## Seeed XIAO nRF54LM20A
- CMSIS-DAP probe (`2886:0068`) with one serial port that carries the console (uart20 on P1.11 and P1.10, #22599).
It ships with a Seeed demo.
- Flash with `esphome run` (pyOCD, MCUboot plus the signed app). A plain `esphome upload` flashed only the bare app
on #22599, and the board stayed dark.
- Reset: `<sdk-nrf python> -m pyocd reset -t nrf54lm20a -u <probe id>`.
- nPM1300 PMIC at 0x6B on P1.18 (SDA) and P1.17 (SCL) (#22661; `i2c:` builds on i2c21 at 100 kHz). Per the upstream
Zephyr board files, BUCK2 supplies VSYS_3V3, the nRF54 and the SAMD11 USB debugger: never switch it off (there is no
way back without a power cycle, and the probe dies with it). LDO1 feeds the IMU and microphone (3.3 V, LDO mode) and
is safe to toggle. BUCK1 and LDO2 are not described anywhere; leave them alone.
- nPM1300 power-on state: BUCK2 on at 3.3 V, BUCK1 off, LDO1 and LDO2 off in load switch mode (enabling one as is
passes VINLDO straight through), charger off, VBUS limit 100 mA, NTC select 10 k. Flows: `recipes/npm1300.md`.
## I2C and SPI breakouts
- GPIO switches on an I2C expander (XL9535 and others) write `value_or(false)` at setup even with
`restore_mode: DISABLED`, so test pin retention on a pin no switch uses.
- ADS1015: `sample_rate: 8` maps to 128 SPS at `12_BITS`.
- A bus held low (`Performing bus recovery`, no devices found) on a new breakout can be a bad header joint; reflow
it before blaming the driver.
## Harness tricks and old releases
- Protected members and methods can be reached from a test header listed in `esphome: includes:` with the explicit
instantiation access trick (`template struct Rob<Tag, &C::member>;`), even on `final` classes; declare the robbers at
global scope.
- API driven light effects that write template outputs every loop (about 5k writes/s) can lag API commands by seconds:
wait for the API state to show each command before reading results.
- Building ESPHome 2025.10.x (pioarduino ESP-IDF 5.4.2) from a path under `/tmp` on macOS fails with "Multiple ways to
build the same target" (the /tmp to /private/tmp alias); put the yaml, build and PLATFORMIO_CORE_DIR elsewhere. Its
IDF penv under Python 3.14 lacks the tools: install `-r packages/framework-espidf/tools/requirements/requirements.core.txt`,
then pin `idf-component-manager~=2.1.0 esp-idf-kconfig~=2.5.0` (newer ones reject interface_version 3).
@@ -4,7 +4,7 @@ Each flow names the pull requests it was used on, so their result tables show wh
One file per component, named after it:
- [`api.md`](api.md): noise handshake and OTA encryption on the ESP8266, outgoing connection wake timing on deep sleep and after a Wi-Fi drop, user defined action listing and execution with a raw plaintext client, store_yaml recovery over Noise or plaintext, rapid connect/disconnect stress (`connstress.py`)
- [`api.md`](api.md): noise handshake and OTA encryption on the ESP8266, outgoing connection wake timing on deep sleep and after a Wi-Fi drop, user defined action listing and execution with a raw plaintext client, store_yaml recovery over Noise or plaintext
- [`ble_midi.md`](ble_midi.md): BLE MIDI client against a fake ESP32 instrument, every packet shape and the send actions
- [`captive_portal.md`](captive_portal.md): fallback AP and /wifisave hammer
- [`cse7766.md`](cse7766.md): Sonoff S31 parser check over the API
@@ -18,12 +18,11 @@ One file per component, named after it:
- [`modem.md`](modem.md): PPPoS modem component boot check with no modem attached, loop blocking and disable timing, SIM7080G behaviour with no SIM and with no data plan through a raw UART passthrough
- [`mqtt.md`](mqtt.md): broker bench, QoS, reconnect, crash log over MQTT, WebSocket transports with a local and a public broker, TLS trust sources (own CA, client certificate, certificate bundle, no verification) with the CLI check, MAC suffix topics and will messages on two boards, shutdown message delivery on restart, disable and deep sleep
- [`nrf52.md`](nrf52.md): dongle board support, zephyr_ble_server connection slot under reordered callbacks, SMP over UDP OTA over Thread with reset faults, MCUboot swap limit and stuck slot recovery, TCP stack probe, sdk-nrf 3.4.1 build and USB notes
- [`npm1300.md`](npm1300.md): nPM1300 PMIC on the XIAO nRF54LM20A: probe build, every entity with a register dump and regulator toggles, power-on state and no-battery readings
- [`online_image.md`](online_image.md): stalled and malformed downloads, PNG, JPEG, BMP and QOI decode time per loop pass with large images and small buffers
- [`openthread.md`](openthread.md): border router on the S3 host plus H2 RCP
- [`ota.md`](ota.md): upload without a configuration and the refusal checks, overlap and lock, timeouts, deflate, upload timing A/B per build and board with deflate and raw, on-device inflate benchmark, OTA automations on two platforms
- [`rtsp_server.md`](rtsp_server.md): camera streaming on the Waveshare ESP32-S3-ETH
- [`scheduler.md`](scheduler.md): loop wake A/B, interval startup delay and control from lambdas, RP2 scheduler lock under IRQ and lwIP load
- [`scheduler.md`](scheduler.md): loop wake A/B, interval startup delay and control from lambdas
- [`udp.md`](udp.md): datagrams, multicast, sockets, `udp.write` payload shapes
- [`usb_cdc_acm.md`](usb_cdc_acm.md): nRF52840 dongle host driver
- [`wifi.md`](wifi.md): reboot_timeout with a fallback AP, DHCP lease cache, Easy Connect (DPP), WISP bridge with an ethernet upstream, reboots against a WPA2/WPA3 PMF access point, WISP and ALWAYS_ON AP switching, AP restarts with WPA3 mixed and LIGHT power save, soft AP clients with the BLE tracker scanning, ESP8266 power save after captive portal provisioning
@@ -37,8 +36,8 @@ One file per component, named after it:
- [`usb_audio.md`](usb_audio.md): USB audio speaker and microphone, the usb_host FIFO split, and Music Assistant playback through sendspin
- [`dfrobot_sen0395.md`](dfrobot_sen0395.md): SEN0395 mmWave command flow, module quirks and overlong lines through its error reply
- [`speaker.md`](speaker.md): media player pipeline tasks on the Connect AUX-2 with the `speaker` platform player
- [`web_server.md`](web_server.md): state SSE stress and the HTTPD task stack on web_server_idf, entity icon and device class readback, per-session `/events` listing, `/events` head, stall, Wi-Fi drop and churn checks
- [`uart_sim.md`](uart_sim.md): UART sensors simulated on a classic ESP32 with loopback and cross-wired UARTs, a Duco ventilation box model on a second UART
- [`web_server.md`](web_server.md): state SSE stress and the HTTPD task stack on web_server_idf, entity icon and device class readback
- [`uart_sim.md`](uart_sim.md): UART sensors simulated on a classic ESP32 with loopback and cross-wired UARTs
- [`gpio_expander.md`](gpio_expander.md): interrupt driven expander inputs, loop idle checks, testing a device out of reach
- [`led_strip.md`](led_strip.md): forcing a failed strip allocation, RMT symbols per chip, loop cost per strip
- [`remote_base.md`](remote_base.md): remote_receiver protocol decoding through a one-pin loopback on ESP32 and ESP8266, no IR hardware
@@ -64,11 +63,11 @@ One file per component, named after it:
- [`rs485_frame.md`](rs485_frame.md): DLE/STX/ETX bus on an ESP32-C3 with a cross-wired simulated bus device (frame cases, gate timing)
- [`hx711.md`](hx711.md): fake HX711 driven from the other core, every published value matched to the served conversion
- [`automation_trace.md`](automation_trace.md): automation codegen A/B, a marker trace of chains, conditions, loops and script modes over the API
- [`bluetooth_proxy.md`](bluetooth_proxy.md): held GATT link after a half-open API session, frozen Home Assistant stand-in, out-of-order GATT discovery responses injected on the proxy, GATT UUID forms (16 bit, 32-bit base, 128 bit) compared against an ESP32 proxy
- [`bluetooth_proxy.md`](bluetooth_proxy.md): held GATT link after a half-open API session, frozen Home Assistant stand-in, out-of-order GATT discovery responses injected on the proxy
- [`crash_report.md`](crash_report.md): crash buttons, fetching the previous boot's crash report over the API, per-chip abort facts
- [`https_idf.md`](https_idf.md): web_server_idf HTTPS test component, listener switch, stalled TLS clients, bad key
- [`mdns.md`](mdns.md): legacy unicast mDNS dump, hammer and latency straight to the device
- [`sim_buses.md`](sim_buses.md): PCF8574/HD44780, MAX7219, SPI spy, packet_interface and SN74HC165 simulators, status LED probe, fake Home Assistant, cg.static_buffer probes, a TRF7962A NFC reader chip behind a fake SPI bus
- [`sim_buses.md`](sim_buses.md): PCF8574/HD44780, MAX7219, SPI spy, packet_interface and SN74HC165 simulators, status LED probe, fake Home Assistant, cg.static_buffer probes
- [`sigma_delta.md`](sigma_delta.md): pulse density of the sigma_delta speaker pin read inside the ESP32-P4, rtttl note onset and release
- [`microphone_http_stream.md`](microphone_http_stream.md): raw PCM over HTTP with a counter fake mic or a USB mic, multi-reader client
- [`i2s_audio.md`](i2s_audio.md): I2S microphone fed by an I2S TX channel on the same S3 through three jumpers
@@ -84,8 +83,3 @@ One file per component, named after it:
- [`heap_alloc.md`](heap_alloc.md): operator new counting, and a ring of allocation callers decoded with addr2line to tell the first run after boot from repeats
- [`wled.md`](wled.md): WLED realtime sender on a board's own access point
- [`combination.md`](combination.md): combination sensor NaN behaviour from the last source
- [`improv.md`](improv.md): Improv serial with stray bytes, scan, bad and good passwords from a client that reads frames out of the log stream, Improv over BLE, per board notes
- [`arduino_pico.md`](arduino_pico.md): arduino-pico framework bump A/B: W5100S Ethernet soak, Pico W fallback AP client count, Pico W bluetooth_proxy GATT hold, web_server SSE stalls, `/events` churn crashes and never completed connects, W5100S OTA without `interrupt_pin`
- [`bluedroid_gattc_queue.md`](bluedroid_gattc_queue.md): queued MTU request and execute write recursion that overflows BTU_TASK, ble_client central against an ESP32-S3 peer
- [`serial_proxy.md`](serial_proxy.md): simulated serial device on a cross-wired UART, byte-exact client with read pauses, ASH tap ACK timing
- [`network_dns.md`](network_dns.md): network.priority Ethernet plus Wi-Fi losing lwIP DNS servers (#19805)
@@ -62,40 +62,3 @@ Results: https://github.com/esphome/esphome/pull/16445#issuecomment-6335435397
An API client that connects allocates about 15 times on ESP32: the connection object, then the list entities and
initial state batches growing the `DeferredBatch` vector. A log subscription adds more per line. Connect before a
heap measurement and subscribe to logs only afterwards (`heap_alloc.md`).
## Native API connect/disconnect stress (#14679, #14687, #14706)
`scripts/api/connstress.py HOST [ITERATIONS] [CONCURRENCY]` (aioesphomeapi; `API_KEY` env for a noise key) opens and
closes native API connections as fast as it can, 500 attempts with 4 at a time by default, and ends with
`RESULT PASS` or `RESULT FAIL`. It is the test that found the raw lwIP socket heap corruption, so run it for any change to
the socket layer, the scheduler or locking on RP2040/RP2350 and ESP8266, with a bounded serial capture on the device:
the client only sees resets, the crash is in the log.
- RP2040/RP2350 before #14687: crashed after 3 or 4 iterations (`malloc` from the lwIP accept IRQ while the main loop
was in `malloc`: double free in `~APIFrameHelper`, `_malloc_r` in `APIConnection()`); after: 500/500. #14679 first
added the lwIP locking between the lwIP callbacks and the main loop on RP2040.
- ESP8266 before #14706: crashed within about 50 iterations (`umm_malloc_core` LoadStoreError, use after free of a
closed PCB's callbacks); after: 490/500, the 10 failures are connection resets from overload, which is expected there.
- ESP32 (BSD sockets) passes 500/500 on both and is the control.
- Compare against dev on the same board; count reboots and decode crash addresses as well as the client's failures.
## API overflow buffer driven and counted on the device (#22771)
`scripts/api/overflow/`: `ovfwrap.hpp` wraps `APIOverflowBuffer::enqueue_iov` and `try_drain` with `-Wl,--wrap` and
counts calls and bytes; the `try_drain` symbol differs per platform (`...6socket11LWIPRawImplE` on ESP8266,
`...6socket13BSDSocketImplE` on ESP32 IDF), so pass it as a substitution and check `nm` shows both `__wrap_` symbols
(a wrong name silently drops the wrapper). ESP-IDF builds keep `nm` in the IDF tools cache
(`xtensa-esp-elf/*/xtensa-esp-elf/bin/`), not under the PlatformIO directory. `putbe-common.yaml` (60 sensors from `putbe-sensors.yaml`, which `gen_sensors.py` writes; four
800 char text sensors flooded every 50 ms, counters as sensors, plus two udp `entity_transport` links) and
`apitest.py HOST OUT` (2 KB receive buffer, 3 x 6 s `pause_reading`, validates every burst state and the final states;
`API_KEY` in the env). Result on #22771: 82 to 159 enqueues per run on a D1 mini and an ESP32, no drops.
`scripts/entity_transport/trcheck.py` compares remote entity values with the sender's published ones over the API on
both boards; it accepts late updates and checks floats by the formula the sender uses, so only values the sender never
published fail. Declare remote entities for both the base and the PR name of the peer so one image serves all four
pairings. Facts from that run:
- Xtensa GCC (lx106 and esp32) defines `__CHAR_UNSIGNED__`; macOS host builds use signed `char`, so a host harness
can miss a sign bug in byte handling.
- udp `packet_interface` with broadcast between a D1 mini and an ESP32 loses most hdlc acks; unicast `addresses:` still
resets the reliability session a few times a minute (dev and PR alike). A D1 mini's API can deliver states 5 to 11 s
late under that load.
@@ -1,42 +0,0 @@
# arduino-pico framework bumps (RP2040/RP2350)
Scripts: `scripts/rp2_web_ble/` (README there). Used for #22671 (6.1.1 to 6.3.2).
- Build PR and dev with a private `PLATFORMIO_CORE_DIR` (`scripts/pio_build.sh` does; see `reference/boards.md`).
Check the compile log line `framework-arduinopico @ 1.60302.0` per build.
- Wired Ethernet (W5100S EVB): 6.3.2 defines `LWIP_ASSERT_CORE_LOCKED()` as `async_context_lock_check` on the
Ethernet context (`cores/rp2040/lwip_wrap.cpp`), so unlocked lwIP calls panic there. Soak the API (200 ms template
counter, 1 s uptime, logs subscribed), load pages, OTA and reboot; the rp2 crash handler shows a panic as
`Crash (HardFault)` in the debug reset reason on the next boot.
- Fallback AP client count: `ap_clients_` is protected and `WiFiComponent` is final; read it from an
`esphome: includes:` header through an explicitly instantiated member pointer (`appeek.hpp`). Join raises it to 1.
- bluetooth_proxy on the Pico W: `rp2_ble_tracker:` + `bluetooth_proxy: active: true`. Drive with `gatthold.py`
against the ESP32-S3 server in `scripts/ble_notify/server.yaml`. UUID forms and the 0x3E connect failures are in
`bluetooth_proxy.md`. A "Failed to send notify data response" warning at each disconnect is normal.
- web_server SSE on the W5100S (dev 2a6a1a050e4, 6.1.1): every `/events` stream stops after 0.3 to 11 s (alone, with
the API, or with page loads alike), then the EVB closes it with a FIN 5.8 to 6.3 s after its last data segment, so
curl exits 0. The pcap shows every byte ACKed by the host, window 65535, no retransmits, nothing sent in the gap:
the device simply stops writing. The 5 s gap matches RPAsyncTCP `ASYNC_MAX_ACK_TIME` (likely `_pcb_busy` not
cleared, then `_onTimeout` closes). A new `/events`, GET / and the API keep working. Pico W: 60 s steady. On macOS
`tcpdump` runs without sudo once your account is in the bpf group. Tools: `sserun.sh HOST TAG SECS alone|api|pages
N` (pcap, netstat poll, API VERBOSE log, probes) and `pcapsum.py PCAP DEVICE_IP` (per connection last data, FIN/RST,
retx). Confirmed with counters patched into the build's `.piolibdeps` copy of RPAsyncTCP: every stall is one
`_sent()` underflow with `_tx_unacked_len` 0 and the pcb idle after `send()`; ESPAsyncWebServer 3.12.1 does not
help. The esphome-libs RPAsyncTCP fork (`esphome-1.3.2`, 8efb83c) streams 16 x 30 s with no stall. `stallctr.py PCAP
IP APILOG` lines the counters up with each stall.
- `H=<device ip> churn.sh TAG SECS` (4 loops of 0.2 to 1.5 s `/events` connections) crashes the rp2 web_server: dev on
the EVB, the fork build on the EVB and the Pico W. HardFault in `AsyncEventSource::send` from
`deferrable_send_state`, about one reboot every 10 to 20 s. Ten quick reboots put the board in safe mode (ping and
OTA port 2040 only); OTA a build to recover.
- **Never flash the W5100S EVB a build without `interrupt_pin`** unless you can reach BOOTSEL: arduino-pico then polls
the W5100 from an async_context timer that every lwIP call pushes back, so the esphome OTA read loop starves the
poller and OTA never completes (the device ACKs the hello, then never the features byte). Web and API still work.
The board has no USB CDC port with ESPHome firmware, so the only way back is BOOTSEL and the UF2 drive.
- `churnflow.sh` (in `rp2_web_ble/`) repeats `churn.sh` with heap and main loop checks and reflashes by OTA when a
round left the board in safe mode.
- `leakflow.sh` with `neverconn.py HOST N rst|head`: ESPAsyncWebServer 3.9.6 leaks about 175 B per `/events` client
that resets before the response head is ACKed (52 KB per 300); 3.12.1 stays flat.
- `/events` churn also hangs the BK7238 main loop or drops it off the network on dev; recover with a serial reset.
- The API has 3 sockets on these builds: connstress at concurrency 4 always shows some "dropped after hello" failures;
use 2 for a clean 500/500.
- IRQ context scheduler test for #22688: `scripts/rp2_sched_lock/`, described in `scheduler.md`.
@@ -1,47 +0,0 @@
# Bluedroid GATT client command queue
## Queued MTU request recursion overflows BTU_TASK (#17954, #22670)
Bluedroid's `bta_gattc_pop_command_to_send()` runs the head of `p_cmd_list` and removes it only after
`bta_gattc_sm_execute()` returns. When that head is an MTU request (or an execute write) whose send fails at once,
the failure path pops again with the same command still at the head, so it recurses until the BTU task stack
overflows. Every ESP-IDF release so far; PR #22670 fixes it in ESPHome with linker wraps
(`bluedroid_gattc_queue.c`).
Rig, `scripts/bluedroid_mtu_recursion/`:
- Peer: an ESP32-S3 with `btusrv.yaml` (`esp32_ble_server`, one readable and writable characteristic, advertising).
- Central: a classic ESP32 devkit with `btu-common.yaml` plus a per-build file like `btucli-example.yaml` (set
`peer_mac` to the peer's Bluetooth MAC, which is its Wi-Fi MAC + 2, and give each build its own name).
`CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK: y` makes the overflow panic at the write:
`Stack canary watchpoint triggered (BTU_TASK)`.
- Each connection: `on_connect` looks up the characteristic handle right away (a `ble_client` with no child nodes
releases services and cleans the GATT cache in the same SEARCH_CMPL event, so a lookup after a delay finds
nothing), waits 1.5 s, then suspends `BTU_TASK`, calls `esp_ble_gap_disconnect`, queues 4 reads and one MTU
request, waits 30 ms and resumes. The batch is the key: sent one at a time, the BTU task handles each request
before the next arrives and nothing waits in the queue. The reads fail and keep the command slot busy so the MTU
request is queued; when popped, `GATTC_ConfigureMTU` fails with "BT_GATT: connection not established".
`ble_client` reconnects on its own and the next round starts.
- `analyze.py CAPTURE` counts rounds, BTU canary crashes, boots, reconnects with and without a reboot and MTU 517.
- Decode with the IDF `xtensa-esp32-elf-addr2line -pfiaC`; the overflow shows the repeating
`pop_command_to_send (act.c:1739/1746) -> sm_execute -> cfg_mtu (act.c:1042)` frames.
Results on ESP-IDF 5.5.6: dev at 46844d3631 crashed 73 of 73 rounds in 5.5 min (every round, about 4.5 s per
reboot cycle); the PR at ad787163fd ran with no crash and reconnected without a reboot each time. Check the wraps are
linked with `nm firmware.elf | grep __wrap_GATTC_ConfigureMTU` (native ESP-IDF builds only; the define is
`USE_ESP32_BLE_BLUEDROID_GATTC_QUEUE`).
### Execute write variant
`btuxw-example.yaml` sets `exec_write: "true"`, which sends `esp_ble_gattc_execute_write(gattc_if, conn_id, true)`
in place of the MTU request. No prepare write is needed: Bluedroid does not check for prepared writes, and
`GATTC_ExecuteWrite` fails synchronously with the same "connection not established" error. The variant also sets
`CONFIG_BT_LOG_GATT_TRACE_LEVEL_API: y`, so each send logs `BT_GATT: GATTC_ExecuteWrite conn_id=... is_execute=1`,
and those lines are counted per round with awk between the `ROUND n start` lines. In a few rounds (about 3 to 14%)
the controller reports the disconnect before the command is popped. Those rounds log no execute send and never
crash, so count "rounds that reached the send", not all rounds. Most dev backtraces in this variant are cut off in
`vTaskSwitchContext` (the extra trace logging makes task switches more likely at the moment of overflow). Use the
complete ones to decode the `bta_gattc_execute (act.c:1352)` cycle.
Results: dev 46844d3631 had 81 rounds, 70 reached the send, and all 70 crashed. PR e51f0b8321 had 151
rounds, 147 reached the send with exactly one execute line each, and there were 0 crashes and 1 boot.
@@ -55,15 +55,3 @@ real device uses, decode an Android HCI snoop: a Read By Type response lists its
- Give the proxy an `api` encryption key (`API_KEY` for the scripts). A Home Assistant on the same network connected to
a plaintext test proxy and took over its Bluetooth subscription (`Subscription from Home Assistant ... replaces
aioesphomeapi`), dropping the test client's connection mid-run.
## GATT UUID forms through a proxy (#22679)
`scripts/gatt_uuid/`: `server.yaml` (the `ble_notify` server plus a service with 128 bit, 32-bit base and 16 bit
UUIDs on characteristics and descriptors, and 2901 and 2902; set the name with `-s name`), `gattlist.py PROXY PEER
OUT.json` (lists every UUID, reads, notifies 10 s, retries 0x3E), `cmp.py REF.json OTHER.json` (entry by entry diff,
exits 1 on a difference) and `run.sh NAME` (Pico W proxy from `rp2_web_ble/picow.yaml`, list, compare). Take the
reference from an ESP32 proxy (unset `API_KEY` for a plaintext API).
- On rp2 before #22679, BTstack truncated 32-bit base UUIDs with a nonzero low half to 16 bits (`5ec10001-...` came
out as `00000001-...`); a zero low half (5ec10000) came through intact.
- Connects through the Pico W proxy fail with 0x3E now and then (see `reference/boards.md`); the scripts retry.
@@ -24,11 +24,3 @@ put `scripts/` on `PYTHONPATH`):
- Quick crash reboots count toward BK72xx safe mode, so space out back-to-back crash tests on those boards.
- A device that keeps the previous crash replays it to every new log client until the next crash; that is one
record, not two.
## Crash records and log subscribers
The record is replayed and cleared by the first log subscribe (`on_subscribe_logs_request`), so drain it on the
first boot after an OTA, or a stale record from the previous build shows up. Moving `api: port:` keeps Home Assistant
off the board while testing. `scripts/crash_report/quiet_then_subscribe.py HOST PORT OUT N` drains the record, stays
connected without a log subscription for N reboots, then subscribes and records the replayed record; it tells a crash
that needs a log subscriber (like the W5500 IPv6 reboot abort in `reference/boards.md`) from one that does not.
@@ -1,66 +0,0 @@
# Improv serial and BLE (#22597)
`scripts/improv/` drives Improv on a freshly erased board with no saved network:
- `improvcli.py PORT OUT --secrets FILE`: Improv serial client. It shares the console with the logs and parses
frames out of the log stream. The flow: 300 stray bytes with no `I` in them, state, info, network state, scan, a
bad password (expect `unable_to_connect` after about 30 s), the real password, then state and network state
again. It ends with a count of frames, bad frames, port resets, reboots and log lines. Credentials come from the
secrets file and are never printed, and the SSID is masked in scan results. It reopens a native USB port that
re-enumerates. A reboot is counted from each new `Running through setup()` log line after the settle, so a board
behind a USB-UART bridge that reboots without a port reset is caught too.
Every request must get its reply; a missing reply, an unexpected error, a malformed frame, a port reset or a
reboot fails the run. `--skip-bad` leaves out the bad password case, `--keep-dtr` leaves DTR asserted,
`--allow-reset` accepts a reboot.
- `improvble.py NAME SECRETS`: Improv BLE client (bleak). Finds the device by name, sends WIFI_SETTINGS and prints
the state changes and the RPC result URLs. Needs `improv_ble` (formerly `esp32_improv`) with `authorizer: none`
and a `next_url`; the result must carry a URL.
- `common.yaml`: package with Wi-Fi and no network, `web_server`, `improv_serial` with a `next_url` (so the
provisioned reply carries URLs) and an ALIVE line every 5 s. `example-esp32.yaml` uses it on a classic ESP32.
- `run.sh NAME [improvcli args]` (env `TREE`, `PORT`, `SECRETS`, `PY`): compile, erase, flash and run the client.
It erases with esptool, so ESP chips only; on LibreTiny or RP2040 erase and flash with that platform's tools and
run `improvcli.py` directly. Both clients end with PASS or FAIL and exit non-zero on FAIL.
Per board:
- Improv serial uses the logger's UART, so the client must open the port the log is on. On LibreTiny check which
UART `logger: hardware_uart: DEFAULT` resolves to (see the board notes).
- BW15: drop `web_server:` or add an `ap:` (it resets during setup otherwise), and pass `--allow-reset` for the known
reboot after `Disabling AP`; the provisioned reply usually goes out first, not always. See `reference/boards.md`.
- ESP32-C3 on USB_SERIAL_JTAG: passes with and without `--keep-dtr`; its reboots only show in the
`Running through setup()` count (see `reference/boards.md`). The scan returns only the last scan's results, which
are empty in the first seconds after boot; use `--settle 10` or more when the target network should be listed.
- Pico 2 W: run with `--keep-dtr` (see `reference/boards.md`). Its Improv scan lists no networks, on dev and PR alike.
- Erase the flash between builds: a saved network skips the provisioning path entirely. Both clients fail at once
when the board already reports `provisioned`; erase the flash first. A new config name does not help: the
network is saved under a fixed key when the config has no `networks:`. A provisioned board also stops advertising
Improv over BLE, so `improvble.py` reports the device as not found.
- If the real password fails right after the bad password case, rerun once before blaming the change: on the C3 it
failed once (`Auth Leave` while Wi-Fi was still retrying the bad network) and passed on every rerun.
When posting results:
- Scan results list the neighbours' SSIDs; filter `RPC cmd=4 len=[1-9]` lines out of anything you post.
- Mask IP addresses in the result URLs.
- Cover a long password too: provision once against a network whose password is 20 characters or more (the client
prints the length).
## Improv serial scan reply over the logger UART (#22758)
- `scripts/improv/improvscan.py PORT OUT [--settle S]` (on `improvcli.py`'s frame parser) sends an Improv RPC request
scan (command 0x04) and records each reply frame (checksum, strings, auth field bytes and length) until the
end-of-list reply. Opening the port resets a D1 mini and a classic ESP32 (see `reference/boards.md`), so it waits
30 s before sending.
- A connected device frees its scan list, so the reply is just the end-of-list frame. Add a `wifi_info:`
`scan_results:` text sensor to keep the list.
- For an auth `NO` entry you need an open network in range: run an AP-only build without a password on a second board
(`scripts/improv/openap32.yaml`).
- Scan replies list the neighbours' SSIDs; filter them out of anything you post.
## Log macro rewrites, A/B by log text (#22758)
`scripts/log_macros/`: `lm-common.yaml` (one entity of every common platform plus `improv_serial` and `web_server`),
`drive.py HOST OUT` (presses the exercise button, reads API sensor states and web_server JSON) and `norm.py SERIAL`
(keeps config dump lines, `lm` lines and state lines, and replaces addresses, the device name, signal, setup times
and per-boot values with placeholders instead of dropping the lines) so two builds' captures diff cleanly. Recent ESPHome logs sensor states and switch, light and fan calls only at VERBOSE; at
DEBUG a log diff sees none of them, so `lm-common.yaml` logs at VERBOSE.
@@ -61,10 +61,3 @@ frame of two LEDs set to `Color(0xA5, 0x3C, 0x0F)` reads `3ca50f3ca50f`.
- An RP2350 `panic()` escalates to a HardFault and the rp2 crash handler reboots within about a second, so a panic
during component setup boot-loops before USB CDC enumerates and the board looks dead (no port, no BOOTSEL drive).
Hold BOOTSEL while plugging it in and flash the UF2 drive. To see such a fault, trigger it after boot.
## Counting a PIO strip's edges on its own pin (#16243)
A GPIO interrupt on the strip's own data pin (`gpio_set_irq_enabled_with_callback(pin, GPIO_IRQ_EDGE_RISE, ...)`)
counts every bit the PIO program sends, with no wires or LEDs; a strip that sends nothing shows 0 edges per report.
Log the PIO block's state machine enable mask and program counters next to the count. `pio_probe/pio-common.yaml`
clears PIO1 instruction memory at boot because it survives a reflash (see `reference/boards.md`).
@@ -34,11 +34,3 @@ wave on the same pad no longer reaches the input (the pad reads 0).
- Result on #21074 at 2ef417bd81 with peripherals powered down: the PR caught all 644 real edges (dev 66) but added
4642 calls while the line was high, one per sleep cycle (about 16 ms), with the level read correctly. Peripherals
on: both builds caught every edge. https://github.com/esphome/esphome/pull/21074#issuecomment-6503939850
## Power lock check
`power_management: esp32_power_management` with `profiling: true` and an `interval` lambda that calls
`esp_pm_dump_locks(stdout);` prints the lock and mode tables on the USB console (not through the ESPHome logger).
Compare lock lists between builds: `usb_serial_jtag` holds `NO_LIGHT_SLEEP` by itself. For a soak that the USB console
must not keep awake, set `logger: hardware_uart: UART0`, dump the locks into `open_memstream()` and log the SLEEP,
CPU_MAX and light sleep count lines, read over the API.
@@ -31,49 +31,3 @@ replies, to check what the module does with no component in the way.
- `AT+CFUN=1,1` leaves the module silent for about 2.5 minutes. It comes back without a power cycle.
- A module left in CMUX (`AT+CMUX=0`, then an ESP restart) recovered 10 of 10 times (`Autodetect mode: 5`).
- PPP and a warm reboot during PPP need a SIM with a working data plan.
### SIM7080G with a live SIM
- A SIM whose plan does not cover LTE-M or NB-IoT never registers on the SIM7080G: CEREG goes 0 (not searching) right
after CFUN=1, 2 (searching) for about 60 s, then 3 (denied) for a minute or two, then searching again, with CSQ 19 to
31. COPS=? lists the Cat-M networks; manual COPS fails (ERROR or denied), so don't retry it. PPP, attach timing and a
warm reboot during PPP need a SIM whose plan covers LTE-M.
- esp_modem 2.1.0 sends `AT+CGATT=1`, `AT+CGATT?` and `AT+CEREG?` with a 500 ms timeout. Unregistered, `CGATT=1`
holds the AT channel (15.6 s denied in the passthrough, about 40 s in the component, over 2 minutes with a SIM that
has no data plan) and the module drops every command sent meanwhile: no echo, no reply (an `AT+CMUX=0` sent then is
lost).
- `ATD*99#` sometimes answers `CONNECT 150000000` without an attach. The module then sits in data mode, sends no LCP,
ignores AT for minutes, and esp_modem's autodetect returns 0 forever (dev logs the wiring hint). A guarded `+++`
(1.1 s silence, `+++`, 1.1 s) returns OK at once; give the passthrough an `Escape` template button doing
`write_str("+++")` between two 1200 ms delays.
- `AT+CFUN=0` powers the SIM down only about 1.7 s after OK (`+CPIN: NOT READY` URC), and the component reads
`+CPIN: READY` before that, so `init_at: [AT+CFUN=0]` cannot fake a missing SIM. There is no reliable no-SIM path
without removing the SIM.
- `AT+CFUN=1,1` left the module silent for 20 s to 2.5 min.
- Pins that reach nothing, for the no-modem path on an M5Stack Atom (or any ESP32): `rx_pin: GPIO22`, `tx_pin: GPIO19`.
- Drive the component build with send_at buttons (`AT DIAL` = `ATD*99#`, `AT CFUN1`, `AT+CMGR=9` for an error text)
and the `Restart` button; `mdrive.py press:NAME`. A `send_at` needs about 3 s before a restart to go out.
## SIM7670G on the Waveshare ESP32-S3-SIM7670G-4G (#22581)
- Board: ESP32-S3 console on a CH343 (UART0, so `logger: hardware_uart: UART0`; the default USB logger prints
nothing). Modem UART: ESP TX GPIO18, ESP RX GPIO17, 115200, `model: SIM7670`. The modem is powered by the "4G" DIP
switch, no GPIO power-up needed. Module SIM7670G-MNGV, firmware V1.9.05.
- The module's own USB enumerates as four `05c6:9330` ports; one of them is an AT port that works next to the
component's UART (another is a binary diag stream). Send AT lines there to read CEREG, CGDCONT, CEER or SMS while the
ESP runs. Run AT experiments with an idle ESP image (a hex passthrough), or the component's own reconnects (CFUN=4,
CGDCONT) get mixed into the results.
- Hex passthrough with frame buttons: `uart: debug: after: timeout: 40ms` with `log_hex`, buttons that `uart.write`
SABM/DISC/CLD/AT frames per DLCI (FCS: CRC-8 reversed poly 0xE0 over address, control, length, then 0xFF minus it)
and buttons that write runs of 0xF9.
- Findings: echo is on after power-up or an AT channel reset, and esp_modem's mode guess takes the echoed LCP probe for
a PPP reply (`Autodetect mode: 2`), the start of #22581. After an ESP reset during PPP the module stays in CMUX and
ignores SABM/DISC/CLD/AT/+++ (it answers SABM0 with a UA only now and then); a burst of 4 KB of 0xF9 usually makes it
print `QCRDY` and fall back to command mode with echo on (worked 10 times, failed 4 tries once after a reflash).
- A PDP context written at CFUN=4 makes the next attach fail with `+CEER: EMM_CAUSE_ESM_FAILURE` (CEREG 3) until a
CFUN=0 cycle; written at CFUN=0 it attaches in about 8 s. After each attach the network can rewrite context 1's APN to
its own name. An empty `apn: ""` validates and attaches (the network picks the APN).
- A SIM can attach and get an IP and DNS while no TCP or ICMP traffic comes back, through PPP (CMUX and data mode) and
through the module's own `AT+HTTPACTION` (706) and `AT+CPING`: that is the carrier side, not the component.
- SMS: when the SIM's SM store is full, set the receive store to ME with `AT+CPMS="SM","SM","ME"`. Messages are UCS2
hex in text mode; decode in memory only, never into a log, and keep SIM data (numbers, identifiers) out of results.
@@ -1,33 +0,0 @@
# network.priority DNS loss (#19805, espressif/esp-idf#19082)
With two interfaces in `network: priority:` on ESP32, ESPHome sets CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF and pins
the default with `esp_netif_set_default_netif()`. In that mode a DHCP ACK only fills the netif's own DNS cache; lwIP's
global table is written only by `esp_netif_set_default_netif_internal()`. `esp_netif_dhcpc_start()` and
`esp_netif_set_ip_info()` (DHCP client stopped) on ANY netif call `dns_clear_servers(true)` on the global table, and the
pin makes IDF skip re-election, so the table stays empty until the app re-asserts the default. Lookups then fail at once
with getaddrinfo 202 (lwIP ERR_VAL, no server set). Unfixed on IDF master when this was written.
Triggers: Wi-Fi joining or reconnecting while Ethernet is the default (ESPHome's `wifi_sta_ip_config_` and IDF's
`esp_netif_action_connected` start DHCP); Ethernet with no link while Wi-Fi is the default (the 15 s
`Connecting failed; reconnecting` retry runs `set_ip_info` plus `dhcpc_start` every time).
Harness: `templates/network_dns/dnsrepro.yaml` + `dnsdiag.hpp` for the Waveshare ESP32-S3-ETH (W5500). Every 3 s a `DIAG`
line classifies the global DNS slots against each netif's cache (0 empty, E eth's, W wifi's, B both, X other) and names
the IDF default and lwIP `netif_default`; every 5 s a `LOOKUP` resolves a fresh `*.10.0.0.1.nip.io` name (a public
wildcard name, never cached). Timeline: Wi-Fi off at boot, enabled at 40 s, disabled and enabled at 100 and 110 s, W5500
PHY powered off at 170 s (a software link down, no unplugging) and on at 250 s. Set the `first`/`second` substitutions
for both priority orders; `phy_boot: "false"` starts with the PHY down (a stand-in for no cable). Needs Wi-Fi and, for
the full matrix, a live Ethernet link. The DIAG lines carry no addresses, so captures can be quoted.
- The W5500 PHY driver's `pwrctl()` is a no-op; `dnsdiag::phy_power()` writes PHYCFGR (OPMD=1, OPMDC 110 off and 111
on, RST low then high) and pokes `phy->get_link()`. Power down alone is not reported as a link loss (traffic kept
flowing); the PHY reset at power on is, so the 250 s step is a short link drop and return.
- Harness trap: `lwip_getaddrinfo` on the loop task with DNS servers set and no interface up blocks until the DNS
timeout and trips the task watchdog; `lookup()` skips while offline.
- Counts on #22800 (lookups ok/failed, PR against its merge base): Ethernet first with link 66/1 vs 23/43, Wi-Fi first
with the PHY down until 250 s 57/0 vs 1/56, Ethernet first with the PHY down 58/0 vs 20/36. Dev empties DNS on every
Wi-Fi join with Ethernet as the default, and on the Ethernet lease with Wi-Fi as the default.
- While the PHY is powered down the W5500 MAC logs `send command timeout` every 2 s on any build (driver noise from
the test).
- Compare build sizes only between names of equal length: the name is stored several times, so two names that differ
in length move the flash delta by tens of bytes.
@@ -1,45 +0,0 @@
# nPM1300 PMIC on the Seeed XIAO nRF54LM20A (#22661)
Scripts: `scripts/npm1300/`. The board's nPM1300 sits at 0x6B on P1.18 (SDA) and P1.17 (SCL); board facts, including
which rails must never be switched off, are in `reference/boards.md`.
- Probe first: `npmprobe.yaml` has the hub with no regulator or charger settings, scans the bus and dumps the
registers every 20 s, so you see what is on before any setting is written.
- `npm-all.yaml` (with `npmcommon.yaml`) has every sensor, binary sensor, text sensor and switch, logs each value from
`on_value` and `on_state` lambdas (entity state lines are VERBOSE on dev, so DEBUG shows nothing without them), dumps
the registers and switch states, and toggles the charger and LDO1. Put a setting under test (the VBUS limit, the
charger values) in `npmcommon.yaml`, not in the per-run file.
- `regdump.yaml` reads a fixed register list with `id(pmic).read_register16()` and logs `REGS 0201=.. ...`; compare two
builds' dumps after stripping timestamps and source line numbers.
- `runone.sh NAME CONFIG PORT [SECS]` flashes with `esphome run --no-logs` (pyOCD) while a serial capture stays open on
the same port. Builds without `ota:` have no MCUboot.
Findings:
- With no battery and the charger on, VBAT reads about 4.23 V, IBAT about 0.2 mA, battery detected is ON and the status
flips between Trickle Charge and Constant Current; with the charger off it says No Battery, and it can drop to Not
Charging for one update on its own. The battery temperature stays at 24.6 C (a fixed 10 k on the NTC pin). Charge
current scale and sign need a real cell.
- ADCIBATMEASSTATUS (0x0510) reads 0x0C (charge) most of the time with no cell and the charger on, sometimes 0x08 or
0x0F.
- `vbus_current_limit: 300mA` writes ILIM0 and ILIMSTARTUP as 0x03 and the board stays up on USB.
- BUCKSWCTRLSEL (0x040F) keeps its value across reflashes until a power cycle, so a setup write to it shows no change on
a warm board.
- To prove a setup priority change, add `on_boot` hooks at 1001, 950 and 900 that log markers and see where the
component's first publishes land between them.
## Charger defaults (#22769)
`npmhead.yaml` runs the register dump, the switch dump and the toggles once, 8 s after boot, on top of
`npmcommon.yaml`; put the charger block under test in `npmcommon.yaml`.
- nPM1300 charger registers with the reset-value defaults (32 mA, 3.6 V, 10 %, 2.9 V, 1000 mA; #22769): 0x0308/09 =
08/00, 0x030A/0B = CF/01, 0x030C = 0x030D = 02, 0x030E = 0x030F = 00. BCHGDISABLESET (0x0306) reads back 0x02 when
the NTC check is off (`thermistor_resistance: none`, ADCNTCRSEL 0x050A = 0) and 0x00 with 10k.
- No cell, charger on: BCHGCHARGESTATUS 0x05 (bit 0 plus trickle), VBAT about 3.61 V with VTERM 3.6 V (4.23 V with
4.2 V), 0.02 V with the charger off. NTCSTATUS (0x0332) and DIETEMPSTATUS (0x0333) read 00 throughout, so the NTC
hot and cold states cannot be reached on this board. BCHGERRREASON stays 00 across on/off toggles.
- A bare `charger:` key fails validation ("expected a dictionary"); use `charger: {}`. `esphome compile
--only-generate` with a private PLATFORMIO_CORE_DIR is enough to check the generated NPM1300Config initializer
without a board; a fresh private PlatformIO dir builds four nRF54 configs in about 10 min. A capture started before
the flash holds the old firmware first; cut at the last `Log initialized`.
@@ -104,13 +104,3 @@ Gotchas: an ESP-IDF image can contain `E7 02` at a 4 KiB boundary by chance; fin
instead of "no signature block": the partition still holds the old signature sector past the new image's end.
Results: https://github.com/esphome/esphome/pull/22398#issuecomment-6716330334
## ESP8266 web_server OTA interruption and SSE (#22682)
`scripts/web_server/async_bump/otacases.py` (README there). Facts from a D1 mini on dev and on ESPAsyncWebServer 3.12.1:
- A cut upload logs `OTA upload interrupted; aborting`, keeps the old image and serves again within a second; the
next full upload works without waiting for a lock release. No heap lost per cut.
- Uploads stop by themselves on the network about 1 in 6 to 1 in 15 (curl `000`, old image kept), and about 1 in 25
boots the new image while curl never gets the reply (it waits 30 to 60 s). Both builds; classify, do not fail on it.
- At OTA reboot the device does not close `/events`: a held client sees silence, rarely a FIN. Detect by idle time.
- Max free block drops from about 45 kB to about 37 kB after the first OTA and stays (both builds).
@@ -27,13 +27,3 @@ captures 40 s from boot and runs `ivsum.py`, which prints the run count, first r
10 s after setup the scheduler frees its item pool and shrinks its `to_add_` and `items_` vectors
(`SCHEDULER_FREELIST_TRIM_DELAY_MS` in `application.cpp`). The first burst of timers after that allocates new
items and regrows the vectors once, so heap or timing measurements should skip the first run after boot.
## RP2 scheduler lock under IRQ and lwIP load (#22688)
`scripts/rp2_sched_lock/` (README there). The `irq_sched_stress` external component calls `defer()` and `set_timeout()`
from a 300 us pico-sdk repeating timer while the main loop does the same; the removed item race integration fixture
runs on the board as an API action. `flow.sh` runs the actions, API connect churn (`../api/connstress.py`), REST POST
churn and both together, then the actions again, and fails on a failed action, a failed connstress 500x2 or a reboot.
Judge by counts, not order: RP2 is `ESPHOME_THREAD_SINGLE`, so `defer()` order is not FIFO on any build. Keep
`debug_scheduler` off, it logs from the IRQ. Dev before #22688 failed the defer count on the Pico W; the PR passed.
`looptime.sh` compares the 16 ms interval gaps with the API and page loads running between two builds.
@@ -1,23 +0,0 @@
# serial_proxy with a simulated device (#22687)
`scripts/serial_proxy/`: no external device. On an ESP32-C3 (logger on USB_SERIAL_JTAG) the proxy UART is tx 4 rx 5
and the simulator UART tx 5 rx 4 (GPIO matrix, `allow_other_uses` on all four pins). `spsim.hpp` is the device; the
client drives it through the proxy with 7E-framed commands: `R` one 88 byte reply (A5, seq u32 BE, 83 bytes
(seq + j) % 251), `S` stream replies back to back, `A` ASH DATA frames every 50 ms with ACK latency timing (for
`ezsp_proxy_tap` in PROTOCOL mode), `X` log `SIMDONE` totals and reset, `B<baud>` change the sim's baud. SIMSTAT and
ASHWIN lines each second carry `backlog_max`, the proxy UART's RX backlog (bytes held back). The sim polls every
16 ms, the main loop cadence (a 1 ms interval also speeds up the proxy's loop and skews what it measures); its 1024
byte TX buffer holds the 185 bytes 115200 baud needs per poll, and ACK latencies are good to one poll.
- `spclient.py HOST --baud B --mode reply|stream|ash [--interval MS] [--duration S | --pauses N --pause S --read S]
[--protocol]`: raw plaintext API client (no encryption in the config), subscribes, brings the sim and the proxy to
the baud, pauses reads on a schedule and prints a RESULT line (complete and broken replies, received bytes). Compare
`received` with the sim's `SIMDONE bytes`.
- `suite.sh BUILD TREE` (env PORT) flashes `spBUILD.yaml` (a copy of `example-run.yaml` with its own `name`),
captures, runs every case (`CASES="a b"` picks some).
- `rx_buffer_size` on the proxy UART decides how long a blocked client can stall before the UART overflows
(32768 used; at 115200 a 5 s pause peaks near it).
- macOS ignores a small SO_RCVBUF after connect (reads back 36000), so a pause needs a few seconds to back up.
- Dev at 1920 baud loses bytes even with the client reading: the proxy sends 1 byte API messages (the UART wakes
the loop per byte) and the TCP queue fills; #22687's wait coalesces them. A tap in PROTOCOL mode keeps that loss.
- Stream mode at 115200 (11.5 KB/s) is more than the proxy forwards over Wi-Fi; both builds lose there.
@@ -73,16 +73,3 @@ address they do not simulate.
- An `addressable_light` display writes nothing until its light is turned on.
- Before calling a rebased PR's change trivial, diff the PR's own diff (head against its parent) old against new: a
move that looks like a merge only can carry real commits from below.
## TRF7962A fake chip (#22188)
`scripts/trf7962a_sim/`: `trfsim.hpp` replaces the SPI component's bus (`SPIComponent` is final, so `spi_bus_` is
reached through the explicit-instantiation member pointer trick) with a `FakeBus` from `on_boot` priority 800, between
the bus (1000) and the reader's setup (600). The bus hands both of the reader's clients (MODE0 write, MODE1 read)
delegates on one register, FIFO and IRQ model; the IRQ pad is switched to input/output after setup and driven by the
model. `trfpr.yaml` runs the tag scenarios (none, present, slow, flaky, swap, collision, CRC, error flag, bad MSB,
TX only, stuck IRQ) and prints per-phase counters (CS, field timing, TX payload, reads without an address). The
same FakeBus approach works for any SPI chip whose reply depends on the address byte inside one CS window, which the
ESP32 SPI slave cannot fake.
The header targets the SPI API of the #22188 branch (`SPIBus` and `SPIComponent::spi_bus_`); dev has since dropped
`SPIBus`, so on a newer tree the bus hook has to move to the new delegate creation before it builds.
@@ -72,23 +72,3 @@ case, and `T1 X` shows which frames got through.
about 49 s after reset. Only the second boot logs `CASE done`, so a skipped reboot fails the run.
See `rs485_frame.md` for the same cross-wired UART trick on an ESP32-C3.
## Duco ventilation box (#22560)
`scripts/uart_sim/duco/`: `ducosim.hpp` is the box model from `tests/integration/fixtures/uart_mock_duco.yaml` (ack
plus answer, AA 01 stuffing, CRC16) on a second UART of the same board; on an ESP32-C6 the hub used tx 18 rx 19 and
the box tx 19 rx 18 at 57600, wired across. `gen.py NAME pr|dev` writes the config (every text sensor, sensors, mode,
comfort, sntp clock) with an `on_value` log per entity (`STATE id = '...'`, newlines as `\n`); `DUCO_VERBOSE=1` shows
`Found node`, `DUCO_SERIAL_SIZE=18` gives the dev fixture's short serial answer. `run.sh NAME KIND SECONDS` (env
`TREE`, `DUCO_PORT`, `PY`, optional `BUILD_LOCK`), run from a scratch directory with a copy of `ducosim.hpp`,
generates, builds through `scripts/pio_build.sh`, flashes and captures with `scripts/serial_capture.py`; a pr build
ends with `check.py` against `expected.txt` (exit 1 on a mismatch), and the model logs requests it has no answer for.
- Answer one request per poll call. Answering a 26 request burst in one pass blocks about 100 ms and overflows the
hub's 256 byte UART RX buffer, which silently drops the serial and version answers every round.
- Dev's hub frame is 32 bytes: the PR model's 34 byte serial answer is dropped there and duco sets "No answer".
- Error cases 7 (three long, 210 B) and 8 (four short, 148 B) check that the code-only fallback goes by length.
## ESP8266 software serial byte checks
The worst case for an unlock after a trailing run of high bits is a frame of bytes all below 0x80; a mixed frame
hides it.
@@ -59,66 +59,3 @@ valve, update, alarm_control_panel or water_heater entity reboots with `Exceptio
`json::linked(const char *)` (the ROM `strlen` on a flash address), fixed by #21316. The cover in the template keeps
that path covered; before #21316 is merged, apply its one line change to both trees or the web_server comparison
cannot run.
## Basic auth on the async web servers (ESP8266, RP2040, LibreTiny)
`scripts/web_auth/` (see its README) fuzzes Basic auth over raw sockets: functional routes with and without
credentials, wrong credentials, other schemes, a tampered hash, spacing and case, then large headers, many failed
attempts next to an authenticated `/events` stream, and a timing comparison of wrong first and last bytes. It also
has a captive portal client package that probes `/`, `/config.json`, POST with and without credentials and
`/wifisave`. `compare.py` lines a dev run up with a PR run. These scripts were still being extended when copied here.
The README also covers the newer flows: the heap under paced connection churn (`heap_churn.py`, the LibreTiny TIME_WAIT
check for #22696) and the main task stack high-water mark with the JSON arena (`arena/`, #22699).
## Per-session /events listing on ESP32 (#22691)
Checks that a new `/events` client's entity listing goes only to that client. Config
`scripts/web_server/sse-listing.yaml` (ESP32 ESP-IDF, web_server version 3, 19 entities, 3 sorting groups, heap logged
every 5 s); build each head with a different `-s name` through `pio_build.sh`. Driver:
`python -I scripts/web_server/sse_listing.py DEVICE_IP --rounds 4 --out events.jsonl`. Each round opens streams 1 and
2, waits for their listing, connects stream 3 and counts for 10 s per stream. A `state` event that carries `domain`
is a full detail (detail_all) entry; a `ping` with only `uptime` is the 10 s keepalive, any other `ping` the greeting
(config JSON). The greeting and `sorting_group` events always go only to the new session, so only the detail_all
count tells the builds apart. Ends `RESULT PASS` or `RESULT FAIL` (exit 0 or 1).
On an ESP32-PICO-D4 the control sent all 19 detail_all entries to streams 1 and 2 on every round, the PR none; stream 3
was ordered on both.
## /events stream rework checks (#21973)
Config `scripts/web_server/stream-dut.yaml` (ESP32 ESP-IDF, 20 ms template sensor, a "Wifi Drop" button that runs
`wifi.disable`, 8 s, `wifi.enable`, heap every 5 s). `scripts/web_server/stream_retest.py HOST MODE` has five modes:
`head` (raw bytes of the first 3 s; compare two builds with `head_compare.py A B NAME_A NAME_B`, which masks numbers
and the device name), `multi` (4 clients 20 s, events and longest gap), `stall` (a client with a 2 KB receive buffer
stops reading for 35 s; read the close time from `Closing stuck stream`, or `Closing stuck EventSource connection` on
older builds), `wifidrop` (REST press, the client reconnects after 5 s idle like a browser `EventSource`) and `churn`
(40 connects, 20 of them reset, then a fresh client). `stream_runall.sh NAME PORT` uploads, captures and runs every
mode. Both builds should close the stalled stream at about 20 s and close the stream at the Wi-Fi drop.
- `sse_listing.py` prints stream 3's TCP connect and first event times. A late greeting (3 to 4 s) was TCP connect
time on the network (SYN retransmits), seen on the control too, not the device.
- On a noisy Wi-Fi network multi-client runs fell to 110 to 900 events per client with every client pausing together,
and a stalled client sometimes missed the EOF although the device logged `Closing stuck stream`. Alternate the
builds (flash A, 4 multi runs, flash B, repeat) before calling a rate difference.
- Log text check for refactors: collect every `[web_server*]` line from all captures, mask timestamps, source line
numbers and digits, `sort -u`, and diff the two builds' sets.
## ESPAsyncWebServer / AsyncTCP bump A/B (#22682)
Scripts: `scripts/web_server/async_bump/` (README there). ESP32 never uses ESPAsyncWebServer: `web_server_base` loads
`web_server_idf` for every ESP32 build, Arduino included, so only ESP8266, RP2040/RP2350 and LibreTiny need a run.
Per board: page loads, a 180 s SSE client, REST control, `/update` OTA with the build's own image, restart button,
then the captive portal hammer (`scripts/wifisave_hammer.sh`, `bogus_saves: "5"`) on one board per family.
- Library check: ESP8266 builds use the native toolchain; the library copies sit in
`.esphome/pio_components/arduino8266/<hash>/esp32async/*/library.json`, not in `.piolibdeps`.
- Restart button over REST on LibreTiny: the HTTP reply is often lost (curl 000 after 5 to 10 s) although the board
restarts, on dev too. Not a regression signal.
- LibreTiny AsyncTCP 3.5.0 does not build with `framework: loglevel: debug` (or more verbose): `AsyncTCP.cpp:332` logs
`xPortGetCoreID()`, undeclared on LibreTiny; `log_d` is empty at the default level, so normal builds pass. Any
library bump for LibreTiny needs one build with the framework loglevel at debug.
- SSE rates on a board with a weak radio (a CB3S, say) are unreliable; decide SSE questions on a board with a good
link and the same SDK.
- `/events` churn (`rp2_web_ble/churn.sh`) faults `AsyncEventSource::send` in `AsyncClient::connected()` from
`deferrable_send_state` on the Pico W and the W5500-EVB-Pico; 3.12.1 and the RPAsyncTCP fork do not fix it.
- Stalled-reader runs need about 150 s: the client's receive window can take about 60 s to close, so a 60 s stall run
ends before the 20 s device timeout even starts.
@@ -117,70 +117,3 @@ The DUT runs `ap:` plus `captive_portal:` with no station network and logs `wifi
Erase the flash before each run so no saved credentials skip the portal. On dev the sleep type stayed 2 after
provisioning although the config asked for none; with #22564 it read 0 from the moment the AP started, and the
`networks:` path still read 0.
## Counting the Disassociation burst at reboot (#22715)
`scripts/wpa3_sniff/`: `sniffap.yaml` is a WPA3-SAE only AP with PMF required (any ESP32, set `board:`) that also turns
on promiscuous mode with the management filter (`sniff_inc.hpp`) and logs each assoc request, auth, disassoc and deauth
frame with transmitter, sequence number, Retry and Protected bits. The AP's own sniffer does see retransmitted copies
addressed to it. The station configs share `st-base.yaml`: `st-common.yaml` reboots 10 s after connect (alternating
`App.reboot()`/`safe_reboot()`), `stearly-common.yaml` reboots on the first loop pass after `WIFI_EVENT_STA_CONNECTED`
(the event handler wakes the loop and `on_loop` runs before the Wi-Fi component's loop; measured 0.15 to 0.46 ms
after the event with a 1 ms interval, before the Wi-Fi component handles it), `ds-common.yaml` deep sleeps 5 s.
`run.sh BUILD TREE SECONDS` (env ST, AP) flashes the station and captures both; `an15.py BUILD STA_MAC` groups the
copies per sequence number within one burst (copies more than 2 s apart start a new group).
- On ESP-IDF 5.5.6 the ESP32-C6 station sends 27 to 32 protected Disassociation copies on every reboot while
associated (espressif/esp-idf#19443); the classic ESP32 sends 1. Use a C6 (or C3) as the station.
- Deep sleep on dev sends no Disassociation at all; the AP finds out only when the station returns (reason 2).
- `esp_wifi_sta_get_ap_info()` already returns OK during the SAE exchange, before association completes.
- A capture over the C6 USB-JTAG console loses the last log line before deep sleep; count from the AP side.
- Serial capture timestamps are quantized to about 200 ms on a CH340, too coarse to time a 100 ms shutdown wait.
## Configured credentials from flash (#22757)
- Flows: two `networks:` with a hidden bogus one at higher priority, then the real one; the `wifisave_hammer.sh` flow
with `bogus_saves: 3`, long AP SSID and password (over 18 characters, the `CompactString` inline capacity), then an
RTS reset and an API restart; `wifi.configure` from `on_boot` after 25 s if not connected, then a reset (prints
"skipped"); a lambda building `WiFiAP` from runtime `std::string` and calling `set_sta()` + `start_connecting()`.
- The ESP-IDF API client sees `Connection reset by peer` on disconnect after a button that reconnects Wi-Fi; harmless.
## ESP32 with a hidden network first never joins (#22764)
- On dev an ESP32 with a hidden bogus network listed first ends every attempt on the real network at once with
"Unspecified" or "Auth Leave" and never joins; without `hidden: true` it joins. An ESP8266 joins either way.
- Cause, confirmed with debug prints: after the EXPLICIT_HIDDEN probe fails, the first real attempt calls
`esp_wifi_disconnect()` (config changed, not associated, nothing marked expected). The hidden attempt's leave event
(reason 36 STA_LEAVING, shown as "Unspecified", the bogus SSID, a zero BSSID) is then charged to the real attempt.
Attempt 2 gets reason 36 too, and the adapter restart aborts its auth (reason 3 "Auth Leave"). This loops forever on
ESP-IDF 5.5.6, with the esp-idf and arduino frameworks alike.
- ESPHome does not print numeric reasons; add one log line in the STA_DISCONNECTED handler and one before
`esp_wifi_set_config` to see them. `esp32: framework: log_level: INFO` shows the IDF `state: init -> auth` lines.
- Regression check: 2025.10.5 joins the hidden-first config (no explicit hidden phase); 2026.10.2 and dev loop.
- Soft AP outage on demand without touching the real AP: a D1 mini AP-only config with `enable_on_boot: false` and an
`on_boot` delay of 20 s before `wifi.enable`; an RTS reset of the D1 gives a 20+ s outage (an ESP32 station sees
Beacon Timeout). The ESP8266 soft AP DHCP can take about 20 s to answer after association.
- A soft AP that still holds an ESP32 from its previous boot rejects the first association with 'Too Many
Associations' (dev too), and some APs reject the first auth after a reset ("Authentication Failed" about 10 ms in,
attempt 2 joins).
## Router outages timed into the portal cooldown (#22797)
`scripts/wifi_outage/`: `rtr.yaml` makes a D1 mini an AP-only test router (its own SSID and password from secrets
`t_ssid`/`t_pw`) that logs `AP client connected/disconnected`, `AP Distribute Station IP` and a 1 s `RTR` station list.
`dut-common.yaml` is a BK7238 DUT (one network, `ap:` with `ap_timeout: 10s`, `captive_portal:`, UART1 log, `ALIVE`
line) with `dhcpwrap.hpp`, a `-Wl,--wrap=udp_sendto_if`/`udp_sendto_if_src` hook that counts DHCP DISCOVER, REQUEST
and RELEASE and logs `DHCPRELEASE sent n= up=` (`up` = netif still up). `c3-common.yaml` is an ESP-IDF C3 DUT without
AP. `outage.py DUT_PORT RTR_PORT LABEL N [--no-ap]` owns both ports: waits for 20 s of `conn=1`, holds the D1 in reset
(RTS on EN), waits for `→ RESTARTING` after `Starting fallback AP` (or `Restarting adapter` with `--no-ap`), lets the
router boot 1 s later and waits for the first line that ends the cooldown (the ones `an.py` uses, at most 40 s).
`an.py LABEL...` prints per outage skip, cooldown length, driver association and address inside the cooldown,
Connected-then-lost, held, releases after the router was back and router-side leaves.
- The D1 router is back about 1 s after release and hands out the address in about 0.2 s, but the BK7238 only reports
it 7 to 8 s after associating; the 30 s portal cooldown leaves plenty of room.
- BK7238 on dev: the Beken supplicant keeps trying after the skip branch's `WiFi.disconnect()` and joins about 5 s into
the cooldown on every outage; base then logs Connected and, 200 ms later, Connection lost (20/20), #22797 0/20. The
BK station never deauths on that teardown: the ESP8266 router logs `err already associed!` and only then the leave.
The release is issued with the netif already down (`up=0`), so it is not proof it hit the air.
- The first `Connection lost` in a capture is the reset from opening the D1 mini port (see `reference/boards.md`), not
an outage.
- About 2 min per outage; run blocks of 10 interleaved base/PR with a reflash between.
@@ -21,28 +21,3 @@ uart_button/uartbtn*.yaml
value_range/rng*.yaml
ld2420_sim/ldenergy*.yaml
ld2420_sim/ldsimple*.yaml
apikey.txt
pio/
rp2_web_ble/*.log
rp2_web_ble/*.txt
rp2_web_ble/*.pcap
gatt_uuid/*.json
gatt_uuid/*.txt
web_auth/configs/*.log
web_auth/configs/*.txt
web_auth/configs/*.json
improv/*.log
npm1300/*-cap.txt
npm1300/*-cap.err
npm1300/*-run.log
rp2_sched_lock/*.txt
rp2_sched_lock/*.log
serial_proxy/*.txt
serial_proxy/*.log
web_server/async_bump/*.log
web_server/async_bump/*.txt
web_server/async_bump/*.pcap
web_server/async_bump/img-*.bin
wifi_outage/*.txt
wpa3_sniff/*.txt
api/overflow/putbe-sensors.yaml
@@ -1,88 +0,0 @@
"""
Rapid native API connect/disconnect stress test (from esphome#14687 and esphome#14706).
usage: connstress.py HOST [ITERATIONS] [CONCURRENCY] (default 500 iterations, 4 at a time)
env: API_KEY (base64 noise key; unset, empty or - for plaintext), API_PORT (default 6053), API_PASSWORD
Each attempt connects with login, disconnects and counts a failure on any error or a 10 s timeout on either step.
Exits 1 when any attempt failed. Watch the serial log for crashes: the client only sees resets.
"""
import asyncio
import contextlib
import os
import sys
import time
from aioesphomeapi import APIClient
HOST = sys.argv[1] if len(sys.argv) > 1 else sys.exit(__doc__)
PORT = int(os.environ.get("API_PORT", "6053"))
PASSWORD = os.environ.get("API_PASSWORD", "")
NOISE_PSK = (
None if os.environ.get("API_KEY") in (None, "", "-") else os.environ["API_KEY"]
)
async def connect_disconnect(client_id: int, iteration: int) -> tuple[int, bool, str]:
cli = APIClient(HOST, PORT, PASSWORD, noise_psk=NOISE_PSK)
try:
await asyncio.wait_for(cli.connect(login=True), timeout=10)
# a disconnect that hangs on a wedged device is a failure too, not a stuck slot
await asyncio.wait_for(cli.disconnect(), timeout=10)
return iteration, True, ""
except Exception as e: # noqa: BLE001 every failure is a counted result
return (
iteration,
False,
f"client{client_id} iter{iteration}: {type(e).__name__}: {e}",
)
finally:
with contextlib.suppress(Exception):
await asyncio.wait_for(cli.disconnect(force=True), timeout=10)
async def main() -> None:
iterations = int(sys.argv[2]) if len(sys.argv) > 2 else 500
concurrency = int(sys.argv[3]) if len(sys.argv) > 3 else 4
print(f"Iterations: {iterations}, Concurrency: {concurrency}", flush=True)
success = fail = 0
errors: list[str] = []
start = time.monotonic()
sem = asyncio.Semaphore(concurrency)
async def run(client_id: int, iteration: int) -> tuple[int, bool, str]:
async with sem:
return await connect_disconnect(client_id, iteration)
tasks = [asyncio.create_task(run(i % concurrency, i)) for i in range(iterations)]
for coro in asyncio.as_completed(tasks):
_, ok, err = await coro
if ok:
success += 1
else:
fail += 1
errors.append(err)
total = success + fail
if total % 10 == 0 or not ok:
rate = total / max(time.monotonic() - start, 1e-6)
print(
f"[{total}/{iterations}] ok={success} fail={fail} ({rate:.1f}/s)",
flush=True,
)
if err:
print(f" ERROR: {err}", flush=True)
elapsed = time.monotonic() - start
print(f"\nDone in {elapsed:.1f}s")
print(f"Success: {success}, Failed: {fail}, Rate: {iterations / elapsed:.1f}/s")
if errors:
print("\nLast 10 errors:")
for e in errors[-10:]:
print(f" {e}")
print("RESULT", "PASS" if fail == 0 else "FAIL")
sys.exit(1 if fail else 0)
if __name__ == "__main__":
asyncio.run(main())
@@ -1,173 +0,0 @@
"""apitest.py HOST OUT.json: Noise API check (entities, states, button) then a flood with a stalled reader
so the device's API overflow buffer fills and drains. Validates every received burst state."""
import asyncio
import gc
import json
import math
import pathlib
import socket
import sys
import time
from aioesphomeapi import SensorState, TextSensorState
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
import aioesphomeapi.connection as conn_mod
from apiconn import connect # noqa: E402
HOST, OUT = sys.argv[1], sys.argv[2]
TL = 800
class SmallSock(socket.socket):
def setsockopt(self, level, opt, *a):
if level == socket.SOL_SOCKET and opt == socket.SO_RCVBUF and a[0] != 2048:
return None
return super().setsockopt(level, opt, *a)
async def start_small(addr_infos, **kw):
fam, typ, proto, _, addr = addr_infos[0]
s = SmallSock(fam, typ, proto)
s.setblocking(False)
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2048)
await asyncio.get_running_loop().sock_connect(s, addr)
return s
conn_mod.aiohappyeyeballs.start_connection = start_small
def txt_ok(s, slot):
if len(s) != TL or s[8] != "|" or not s[:8].isdigit():
return None
n = int(s[:8])
for i in range(9, TL):
if s[i] != chr(ord("A") + (n * 7 + slot * 3 + i) % 26):
return None
return n
async def main():
res = {"host": HOST}
stopped = {"t": None}
async def on_stop(expected):
stopped["t"] = time.monotonic()
cli = await connect(HOST, on_stop=on_stop)
info = await cli.device_info()
res["device"] = info.name
res["version"] = info.esphome_version
ents, _ = await cli.list_entities_services()
res["entities"] = len(ents)
by_key = {e.key: e for e in ents}
names = {e.object_id: e for e in ents}
flood = names["flood"]
bump = names["bump"]
state = {}
stats = {"states": 0, "bad_sensor": 0, "bad_text": 0, "burst_states": 0}
def on_state(s):
e = by_key.get(s.key)
if e is None:
return
stats["states"] += 1
oid = e.object_id
if isinstance(s, SensorState) and oid.startswith("s") and oid[1:].isdigit():
i = int(oid[1:])
stats["burst_states"] += 1
if not s.missing_state and (
int(s.state) % 100 != i or s.state != int(s.state)
):
stats["bad_sensor"] += 1
if isinstance(s, TextSensorState) and oid.startswith("t") and oid[1:].isdigit():
stats["burst_states"] += 1
if not s.missing_state and txt_ok(s.state, int(oid[1:])) is None:
stats["bad_text"] += 1
state[oid] = s.state
cli.subscribe_states(on_state)
await asyncio.sleep(3)
res["initial_states"] = len(state)
b0 = state.get("bump_count")
b0 = 0 if b0 is None or math.isnan(b0) else int(b0)
for _ in range(5):
cli.button_command(bump.key)
await asyncio.sleep(0.5)
await asyncio.sleep(3)
res["bump_delta"] = int(state.get("bump_count", 0)) - b0
o0 = (
state.get("ovf_enqueue"),
state.get("ovf_drain"),
state.get("ovf_enqueue_bytes"),
state.get("ovf_enqueue_fail"),
)
sock = cli._connection._socket
transport = next(
o
for o in gc.get_objects()
if isinstance(o, asyncio.Transport)
and not o.is_closing()
and o.get_extra_info("socket") is not None
and o.get_extra_info("socket").fileno() == sock.fileno()
)
cli.switch_command(flood.key, True)
await asyncio.sleep(3)
for _ in range(3):
transport.pause_reading()
await asyncio.sleep(6)
transport.resume_reading()
await asyncio.sleep(4)
cli.switch_command(flood.key, False)
await asyncio.sleep(6)
fN = state.get("flood_n")
final_ok = (
fN is not None
and not math.isnan(fN)
and all(state.get(f"s{i}") == fN * 100 + i for i in range(60))
and all(txt_ok(state.get(f"t{j}", ""), j) == int(fN) for j in range(4))
)
o1 = (
state.get("ovf_enqueue"),
state.get("ovf_drain"),
state.get("ovf_enqueue_bytes"),
state.get("ovf_enqueue_fail"),
)
res.update(stats)
res["flood_n"] = fN
res["final_states_match"] = final_ok
# a counter with no state (missing or NaN) gives no delta, which fails the run
for name, a, b in zip(
(
"ovf_enqueue_delta",
"ovf_drain_delta",
"ovf_enqueue_bytes_delta",
"ovf_enqueue_fail_delta",
),
o0,
o1,
strict=True,
):
ok_ab = all(x is not None and not math.isnan(x) for x in (a, b))
res[name] = b - a if ok_ab else None
res["dropped"] = stopped["t"] is not None
await cli.disconnect()
res["pass"] = (
not res["dropped"]
and final_ok
and res["bump_delta"] == 5
and stats["bad_sensor"] == 0
and stats["bad_text"] == 0
and (res["ovf_enqueue_delta"] or 0) > 0
and (res["ovf_drain_delta"] or 0) > 0
# a refused enqueue loses a message
and res["ovf_enqueue_fail_delta"] == 0
)
print(json.dumps(res))
pathlib.Path(OUT).write_text(json.dumps(res, indent=1), encoding="utf-8")
return 0 if res["pass"] else 1
sys.exit(asyncio.run(main()))
@@ -1,67 +0,0 @@
"""gen_sensors.py: write putbe-sensors.yaml for putbe-common.yaml.
It holds the BS_COUNT (60) template sensors bs0..bs59 and the BT_COUNT (4) 800 char text sensors bt0..bt3 that the
flood lambda publishes through the BS and BT pointer arrays of txt.hpp (filled by a boot lambda), and the remote
entity_transport sensors and binary sensors: count, flt and bin from both the base (${peer}b) and the PR (${peer}p)
name of the peer, over both links (et_plain, et_full).
"""
import pathlib
BS_COUNT = 60 # txt.hpp
BT_COUNT = 4 # txt.hpp
LINKS = ("plain", "full")
PEERS = ("b", "p")
def ptr_fill(kind: str, arr: str, prefix: str, n: int) -> list[str]:
ids = ", ".join(f"id({prefix}{i})" for i in range(n))
return [
" - lambda: |-",
f" {kind} *all[] = {{{ids}}};",
f" for (size_t i = 0; i < {arr}_COUNT; i++) {arr}[i] = all[i];",
]
def remote(link: str, peer: str, rid: str, name: str) -> list[str]:
return [
" - platform: entity_transport",
f" entity_transport_id: et_{link}",
f" id: r_{link}_{peer}_{rid}",
f" name: R {link} {peer} {name}",
f" provider: ${{peer}}{peer}",
f" remote_id: {rid}",
]
out = ["esphome:", " on_boot:", " priority: 600", " then:"]
out += ptr_fill("sensor::Sensor", "BS", "bs", BS_COUNT)
out += ptr_fill("text_sensor::TextSensor", "BT", "bt", BT_COUNT)
out.append("sensor:")
for i in range(BS_COUNT):
out += [
" - platform: template",
f" id: bs{i}",
f" name: S{i}",
" update_interval: never",
" accuracy_decimals: 0",
]
for link in LINKS:
for peer in PEERS:
out += remote(link, peer, "count", "count")
out += remote(link, peer, "flt", "flt") + [" accuracy_decimals: 3"]
out.append("binary_sensor:")
for link in LINKS:
for peer in PEERS:
out += remote(link, peer, "bin", "bin")
out.append("text_sensor:")
for i in range(BT_COUNT):
out += [
" - platform: template",
f" id: bt{i}",
f" name: T{i}",
" update_interval: never",
]
pathlib.Path(__file__).with_name("putbe-sensors.yaml").write_text(
"\n".join(out) + "\n", encoding="utf-8"
)
@@ -1,30 +0,0 @@
#pragma once
// Counts calls into the API overflow buffer through -Wl,--wrap (test only).
#include <cstddef>
#include <cstdint>
#include <sys/types.h>
struct iovec;
extern "C" {
uint32_t ovf_enq_calls = 0;
uint32_t ovf_enq_bytes = 0;
uint32_t ovf_drain_calls = 0;
uint32_t ovf_enq_fails = 0; // the buffer refused a message: it is lost
bool __real__ZN7esphome3api17APIOverflowBuffer11enqueue_iovEPK5iovecijj(void *self, const iovec *iov, int n,
size_t total, size_t skip);
bool __wrap__ZN7esphome3api17APIOverflowBuffer11enqueue_iovEPK5iovecijj(void *self, const iovec *iov, int n,
size_t total, size_t skip) {
bool ok = __real__ZN7esphome3api17APIOverflowBuffer11enqueue_iovEPK5iovecijj(self, iov, n, total, skip);
if (ok) {
ovf_enq_calls++;
ovf_enq_bytes += total - skip;
} else {
ovf_enq_fails++;
}
return ok;
}
ssize_t OVF_DRAIN_REAL(void *self, void *sock);
ssize_t OVF_DRAIN_WRAP(void *self, void *sock) {
ovf_drain_calls++;
return OVF_DRAIN_REAL(self, sock);
}
}
@@ -1,156 +0,0 @@
esphome:
name: ${name}
includes:
- ovfwrap.hpp
- txt.hpp
build_flags:
- -Wl,--wrap=_ZN7esphome3api17APIOverflowBuffer11enqueue_iovEPK5iovecijj
- -Wl,--wrap=${drain_sym}
- -DOVF_DRAIN_WRAP=__wrap_${drain_sym}
- -DOVF_DRAIN_REAL=__real_${drain_sym}
logger:
level: DEBUG
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
power_save_mode: none
api:
reboot_timeout: 0s
encryption:
key: !secret api_key
ota:
- platform: esphome
packages:
# the flooded sensors and text sensors, their pointer arrays and the remote entities; run gen_sensors.py once
bs: !include putbe-sensors.yaml
globals:
- id: flood_n
type: uint32_t
initial_value: "0"
- id: bump_n
type: uint32_t
initial_value: "0"
- id: tick
type: uint32_t
initial_value: "0"
switch:
- platform: template
id: flood
name: Flood
optimistic: true
button:
- platform: template
name: Bump
on_press:
- lambda: |-
id(bump_n)++;
ESP_LOGI("bump", "press %u", (unsigned) id(bump_n));
id(bump_sensor).publish_state(id(bump_n));
interval:
- interval: 50ms
then:
- if:
condition:
switch.is_on: flood
then:
- lambda: |-
uint32_t n = ++id(flood_n);
for (size_t i = 0; i < BS_COUNT; i++)
BS[i]->publish_state(n * 100 + i);
for (size_t i = 0; i < BT_COUNT; i++)
BT[i]->publish_state(make_txt(n, i));
id(flood_sensor).publish_state(n);
- interval: 1s
then:
- lambda: |-
uint32_t t = ++id(tick);
id(loc_count).publish_state(t);
id(loc_float).publish_state(12345.678f + t * 0.001f - (t % 7) * 1000.5f);
id(loc_bin).publish_state((t / 3) % 2 == 1);
id(ovf_enq).publish_state(ovf_enq_calls);
id(ovf_enq_b).publish_state(ovf_enq_bytes);
id(ovf_drain).publish_state(ovf_drain_calls);
id(ovf_enq_fail).publish_state(ovf_enq_fails);
udp:
- id: udp_plain
port: 18611
addresses: ["${peer_ip}"]
- id: udp_full
port: 18612
addresses: ["${peer_ip}"]
packet_interface:
- platform: udp
id: pi_plain
udp_id: udp_plain
- platform: udp
id: pi_full
udp_id: udp_full
addressing:
address: ${my_addr}
destination: ${peer_addr}
encryption:
key: putbe test key
rolling_code_enable: true
reliability:
fragmentation:
session:
entity_transport:
- id: et_plain
packet_interface: pi_plain
update_interval: 2s
sensors:
- id: loc_count
broadcast_id: count
- id: loc_float
broadcast_id: flt
binary_sensors:
- id: loc_bin
broadcast_id: bin
- id: et_full
packet_interface: pi_full
sensors:
- id: loc_count
broadcast_id: count
- id: loc_float
broadcast_id: flt
binary_sensors:
- id: loc_bin
broadcast_id: bin
sensor:
- platform: template
id: flood_sensor
name: Flood N
update_interval: never
- platform: template
id: bump_sensor
name: Bump count
update_interval: never
- platform: template
id: loc_count
name: Local count
update_interval: never
- platform: template
id: loc_float
name: Local float
accuracy_decimals: 3
update_interval: never
- platform: template
id: ovf_enq
name: Ovf enqueue
update_interval: never
- platform: template
id: ovf_enq_b
name: Ovf enqueue bytes
update_interval: never
- platform: template
id: ovf_drain
name: Ovf drain
update_interval: never
- platform: template
id: ovf_enq_fail
name: Ovf enqueue fail
update_interval: never
binary_sensor:
- platform: template
id: loc_bin
name: Local bin
@@ -1,19 +0,0 @@
#pragma once
#include <string>
#include <cstdio>
// the flooded template sensors and text sensors, filled at boot by putbe-sensors.yaml (gen_sensors.py)
static constexpr size_t BS_COUNT = 60;
static esphome::sensor::Sensor *BS[BS_COUNT];
static constexpr size_t BT_COUNT = 4;
static esphome::text_sensor::TextSensor *BT[BT_COUNT];
// 800 chars: 8 digit n, '|', then letters from n and the slot
static std::string make_txt(uint32_t n, int slot) {
std::string s(800, ' ');
char head[16];
snprintf(head, sizeof(head), "%08u|", (unsigned) n);
for (int i = 0; i < 9; i++)
s[i] = head[i];
for (int i = 9; i < 800; i++)
s[i] = 'A' + (n * 7 + slot * 3 + i) % 26;
return s;
}
@@ -4,7 +4,6 @@ Import it with this directory on sys.path (the drivers add their parent director
"""
import asyncio
from collections.abc import Awaitable, Callable
import contextlib
import os
import re
@@ -28,32 +27,19 @@ FATAL = (
)
async def connect(
host: str,
tries: int = 30,
timeout: float = 10,
port: int = 6053,
on_stop: Callable[[bool], Awaitable[None]] | None = None,
) -> APIClient:
async def connect(host: str, tries: int = 30, timeout: float = 10) -> APIClient:
"""Connect and log in, retrying once a second; exits after TRIES failures with the last error.
API_KEY in the env selects Noise; unset, empty or - is plaintext. ON_STOP is called when the connection ends.
API_KEY in the env selects Noise; unset, empty or - is plaintext.
"""
key = os.environ.get("API_KEY")
last: BaseException | None = None
for _ in range(tries):
c = APIClient(
host, port, None, noise_psk=None if key in (None, "", "-") else key
host, 6053, None, noise_psk=None if key in (None, "", "-") else key
)
live = [False]
# a failed attempt's cleanup may call on_stop too; pass on only stops of the returned client
async def stop(expected: bool, live: list[bool] = live) -> None:
if live[0] and on_stop is not None:
await on_stop(expected)
try:
await asyncio.wait_for(c.connect(on_stop=stop, login=True), timeout)
await asyncio.wait_for(c.connect(login=True), timeout)
except FATAL as e:
sys.exit(f"no API connection to {host}: {type(e).__name__}: {e}")
except Exception as e: # noqa: BLE001
@@ -63,7 +49,6 @@ async def connect(
await c.disconnect(force=True)
await asyncio.sleep(1)
else:
live[0] = True
return c
sys.exit(
f"no API connection to {host} after {tries} tries: {type(last).__name__}: {last}"
@@ -73,80 +58,3 @@ async def connect(
def log_text(msg) -> str:
"""The message of a subscribe_logs callback as text, without ANSI colour codes."""
return ANSI.sub("", msg.message.decode(errors="replace"))
def stop_event() -> tuple[asyncio.Event, Callable[[bool], Awaitable[None]]]:
"""An Event and an on_stop callback for connect() that sets it when the connection ends."""
ev = asyncio.Event()
async def on_stop(expected: bool) -> None:
ev.set()
return ev, on_stop
async def ble_connect(
cli: APIClient,
addr: int,
on_lost: Callable[[int], None] | None = None,
advert_timeout: float = 60,
timeout: float = 30,
) -> tuple[bool, int, int, Callable[[], None]]:
"""Wait for an advert from ADDR, then connect through the proxy without a cache (like Home Assistant).
Returns (connected, mtu, error, cancel); a missing advert or a connect timeout gives (False, 0, -1, cancel), so
callers can retry. ON_LOST(error) is called when the link drops later.
"""
seen = asyncio.Event()
unsub = cli.subscribe_bluetooth_le_raw_advertisements(
lambda m: (
seen.set() if any(a.address == addr for a in m.advertisements) else None
)
)
try:
await asyncio.wait_for(seen.wait(), advert_timeout)
except TimeoutError:
return False, 0, -1, lambda: None
finally:
unsub()
first: asyncio.Queue = asyncio.Queue()
pending = True
def on_state(connected: bool, mtu: int, err: int) -> None:
nonlocal pending
if pending:
pending = False
first.put_nowait((connected, mtu, err))
elif not connected and on_lost is not None:
on_lost(err)
cancel = await cli.bluetooth_device_connect(
addr,
on_state,
timeout=timeout,
address_type=0,
feature_flags=0xFF,
has_cache=False,
)
try:
connected, mtu, err = await asyncio.wait_for(first.get(), timeout + 5)
except TimeoutError:
return False, 0, -1, cancel
return connected, mtu, err, cancel
async def enable_notify(
cli: APIClient, addr: int, ch, on_notify: Callable[[int, bytearray], None]
) -> bool:
"""Start notify on characteristic CH and write its first CCCD (2902) like Home Assistant.
Returns False when the characteristic lists no CCCD.
"""
await cli.bluetooth_gatt_start_notify(addr, ch.handle, on_notify)
cccd = next(
(d for d in ch.descriptors if d.uuid.lower().startswith("00002902")), None
)
if cccd is None:
return False
await cli.bluetooth_gatt_write_descriptor(addr, cccd.handle, b"\x01\x00")
return True
@@ -1,57 +0,0 @@
"""Count rounds, BTU_TASK crashes, reconnects without reboot and MTU 517 in a central capture.
analyze.py CAPTURE
A round counts from its "start" line (a crashing round never logs "fired"); rounds that log "not queued" or
"aborted" are taken back out and listed apart. Exits 1 when no round counts, since such a capture tested nothing.
"""
import pathlib
import re
import sys
lines = (
pathlib.Path(sys.argv[1]).read_text(encoding="utf-8", errors="replace").splitlines()
)
rounds = crashes = other_panics = boots = connects = mtu517 = mtu_other = 0
not_queued = aborted = skipped = 0
reconnect_ok = reconnect_reboot = 0
pending = False # a round fired and we wait for the next connect
for ln in lines:
if "Stack canary watchpoint triggered (BTU_TASK)" in ln:
crashes += 1
elif "Guru Meditation" in ln or "abort() was called" in ln:
other_panics += 1
if "rst:0x" in ln:
boots += 1
if pending:
reconnect_reboot += 1
pending = False
if "CLI connected" in ln:
connects += 1
if pending:
reconnect_ok += 1
pending = False
if re.search(r"ROUND \d+ start", ln):
rounds += 1
pending = True
if re.search(r"ROUND \d+ (not queued|aborted)", ln):
rounds -= 1
pending = False
not_queued += "not queued" in ln
aborted += "aborted" in ln
skipped += "ROUND skipped" in ln
if m := re.search(r"cfg_mtu status 0, mtu (\d+)", ln):
if m.group(1) == "517":
mtu517 += 1
else:
mtu_other += 1
print(
f"rounds={rounds} btu_canary_crashes={crashes} other_panics={other_panics} boots={boots}"
)
print(
f"connects={connects} reconnect_without_reboot={reconnect_ok} reconnect_after_reboot={reconnect_reboot}"
)
print(f"mtu517={mtu517} mtu_other={mtu_other}")
print(f"not_queued={not_queued} aborted={aborted} skipped={skipped}")
if rounds <= 0:
sys.exit("FAIL: no round reached the BTU queue")
@@ -1,75 +0,0 @@
# Central for the Bluedroid queued MTU recursion repro (esphome#17954). Every connection: wait 1.5 s, then
# suspend BTU_TASK, local disconnect, 4 reads + 1 MTU request (or execute write with exec_write: "true") in one
# batch, resume. ble_client reconnects.
esp32:
board: esp32dev
framework:
type: esp-idf
sdkconfig_options:
CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK: y
logger:
level: DEBUG
esp32_ble_tracker:
scan_parameters:
active: false
globals:
- {id: rounds, type: int, initial_value: "0"}
- {id: chr_handle, type: uint16_t, initial_value: "0"}
ble_client:
- mac_address: ${peer_mac}
id: srv
on_connect:
- logger.log: {format: "CLI connected", level: INFO}
# Runs inside SEARCH_CMPL, before ble_client releases the GATT cache (it has no other nodes)
- lambda: |-
esp_bt_uuid_t uuid = esp32_ble_tracker::ESPBTUUID::from_raw("5ec10001-0000-1000-8000-00805f9b34fb").get_uuid();
esp_gattc_char_elem_t elem;
uint16_t count = 1;
id(chr_handle) = 0;
if (esp_ble_gattc_get_char_by_uuid(id(srv)->get_gattc_if(), id(srv)->get_conn_id(), 1, 0xFFFF, uuid, &elem,
&count) == ESP_GATT_OK && count > 0)
id(chr_handle) = elem.char_handle;
- delay: 1500ms
- lambda: |-
if (!id(srv)->connected()) return;
esp_gatt_if_t gattc_if = id(srv)->get_gattc_if();
uint16_t conn_id = id(srv)->get_conn_id();
uint16_t handle = id(chr_handle);
if (handle == 0) {
ESP_LOGW("btu", "ROUND skipped, no characteristic");
return;
}
int n = ++id(rounds);
ESP_LOGI("btu", "ROUND %d start conn_id=%u handle=0x%04x", n, conn_id, handle);
TaskHandle_t btu = xTaskGetHandle("BTU_TASK");
if (btu == nullptr) {
// vTaskSuspend(nullptr) would suspend this task forever
ESP_LOGE("btu", "ROUND %d aborted, no BTU_TASK", n);
return;
}
vTaskSuspend(btu);
// a rejected disconnect leaves the link up, so the queued calls never take the failing send path
esp_err_t err = esp_ble_gap_disconnect(id(srv)->get_remote_bda());
for (int i = 0; i < 4; i++) {
esp_err_t e = esp_ble_gattc_read_char(gattc_if, conn_id, handle, ESP_GATT_AUTH_REQ_NONE);
if (e != ESP_OK)
err = e;
}
esp_err_t e = ${exec_write} ? esp_ble_gattc_execute_write(gattc_if, conn_id, true)
: esp_ble_gattc_send_mtu_req(gattc_if, conn_id);
if (e != ESP_OK)
err = e;
delay(30);
vTaskResume(btu);
// a round whose calls were rejected never reached the BTU queue, so it tests nothing
if (err != ESP_OK) {
ESP_LOGW("btu", "ROUND %d not queued: %s", n, esp_err_to_name(err));
} else {
ESP_LOGI("btu", "ROUND %d fired", n);
}
on_disconnect:
- logger.log: {format: "CLI disconnected", level: INFO}
@@ -1,9 +0,0 @@
esphome:
name: btuclibase # one name per build (btuclibase, btuclipr)
substitutions:
peer_mac: "AA:BB:CC:DD:EE:FF" # the peer S3 Bluetooth MAC (Wi-Fi MAC + 2)
exec_write: "false"
packages:
common: !include btu-common.yaml
@@ -1,31 +0,0 @@
# Peer for the Bluedroid queued MTU recursion repro: a GATT server with one readable and writable characteristic
esphome:
name: btusrv
esp32:
variant: esp32s3
board: esp32-s3-devkitc-1
framework:
type: esp-idf
logger:
level: DEBUG
hardware_uart: USB_SERIAL_JTAG
esp32_ble:
name: btusrv
esp32_ble_server:
on_connect:
- logger.log: {format: "SRV connected", level: INFO}
on_disconnect:
- logger.log: {format: "SRV disconnected", level: INFO}
services:
- uuid: 5ec10000-0000-1000-8000-00805f9b34fb
advertise: true
characteristics:
- id: numc
uuid: 5ec10001-0000-1000-8000-00805f9b34fb
read: true
write: true
value: [42]
@@ -1,15 +0,0 @@
esphome:
name: btuxwbase # one name per build (btuxwbase, btuxwpr)
substitutions:
peer_mac: "AA:BB:CC:DD:EE:FF" # the peer S3 Bluetooth MAC (Wi-Fi MAC + 2)
exec_write: "true"
esp32:
framework:
sdkconfig_options:
# GATT API trace prints one "GATTC_ExecuteWrite conn_id=" line per execute send
CONFIG_BT_LOG_GATT_TRACE_LEVEL_API: y
packages:
common: !include btu-common.yaml
@@ -1,102 +0,0 @@
"""quiet_then_subscribe.py HOST PORT OUT QUIET_BOOTS: on the first boot drain any crash record (the first log
subscribe replays and clears it), then stay connected without a log subscription for QUIET_BOOTS reboots, then
subscribe on the next boot and record the log (including a crash record replayed on subscribe) until a line with
REBOOT. The drain connection is dropped and replaced by one without a subscription before boot 1 reboots, so a crash
that needs a log subscriber is not recorded as a quiet one; a reboot during the drain, or a reconnect slow enough to
hide one, fails the run instead of shifting the boot count. Exits 1 when that line never comes or a quiet boot does
not reboot within QUIET_REBOOT_WAIT seconds (default 900). Every lost connection counts as a reboot, so run it on a
stable link.
env: API_KEY (unset for a plaintext API), QUIET_REBOOT_WAIT."""
import asyncio
import contextlib
import os
import pathlib
import sys
import time
from aioesphomeapi import LogLevel
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from apiconn import connect, log_text, stop_event # noqa: E402
# how long a quiet boot may run before its reboot; QUIET_REBOOT_WAIT in the env overrides it
REBOOT_WAIT = float(os.environ.get("QUIET_REBOOT_WAIT", "900"))
# a reconnect slower than this may have waited out a reboot (connect() retries once a second)
RECONNECT_MAX_S = 5.0
async def main(host: str, port: int, outf: str, quiet: int) -> None:
with pathlib.Path(outf).open("a", encoding="utf-8") as f:
def w(t: str) -> None:
f.write(f"{time.strftime('%H:%M:%S')} {t}\n")
f.flush()
boots = 0
while True:
lost, on_stop = stop_event()
cli = await connect(host, tries=300, timeout=5, port=port, on_stop=on_stop)
boots += 1
info = await cli.device_info()
w(
f"=== CONNECTED boot {boots} name={info.name} quiet={1 < boots <= quiet + 1}"
)
if boots > quiet + 1:
done = asyncio.Event()
def on_log(m, done: asyncio.Event = done) -> None:
t = log_text(m)
w(t)
if "REBOOT" in t:
done.set()
cli.subscribe_logs(
on_log, log_level=LogLevel.LOG_LEVEL_DEBUG, dump_config=False
)
try:
await asyncio.wait_for(done.wait(), 120)
except TimeoutError:
w("=== no REBOOT within 120 s")
with contextlib.suppress(Exception):
await cli.disconnect()
if not done.is_set():
sys.exit("FAIL: no REBOOT line within 120 s of subscribing")
return
if boots == 1:
# drain any crash record left by the reboot that brought this build up
cli.subscribe_logs(
lambda m: w("drain " + log_text(m)),
log_level=LogLevel.LOG_LEVEL_DEBUG,
dump_config=False,
)
await asyncio.sleep(3)
if lost.is_set():
w("=== boot 1 rebooted during the drain")
sys.exit("FAIL: boot 1 rebooted with the drain subscriber attached")
with contextlib.suppress(Exception):
await cli.disconnect()
lost, on_stop = stop_event()
t = time.monotonic()
cli = await connect(
host, tries=300, timeout=5, port=port, on_stop=on_stop
)
if (dt := time.monotonic() - t) > RECONNECT_MAX_S:
w(f"=== boot 1 reconnect took {dt:.1f} s")
sys.exit(
f"FAIL: the reconnect after the drain took {dt:.1f} s, boot 1 may have rebooted"
)
w("=== boot 1 reconnected without a log subscription")
# quiet: wait for the device to drop the connection (its reboot)
try:
await asyncio.wait_for(lost.wait(), REBOOT_WAIT)
except TimeoutError:
w(f"=== boot {boots}: no reboot within {REBOOT_WAIT:.0f} s")
sys.exit(
f"FAIL: boot {boots} did not reboot within {REBOOT_WAIT:.0f} s"
)
w("=== connection lost")
await asyncio.sleep(2)
asyncio.run(main(sys.argv[1], int(sys.argv[2]), sys.argv[3], int(sys.argv[4])))
@@ -1,168 +0,0 @@
"""trcheck.py D1HOST D1VAR E32HOST E32VAR SECONDS OUT.json: watch the entity_transport remote entities on both
boards over the API and compare each received value with the sender's own published values."""
import asyncio
import json
import math
import pathlib
import struct
import sys
import time
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from apiconn import connect # noqa: E402
D1, D1V, E32, E32V, SECS, OUT = (
sys.argv[1],
sys.argv[2],
sys.argv[3],
sys.argv[4],
float(sys.argv[5]),
sys.argv[6],
)
def f32(v):
return struct.unpack("<f", struct.pack("<f", v))[0]
def expect(t): # 12345.678f + t * 0.001f - (t % 7) * 1000.5f in single precision
return f32(f32(f32(12345.678) + f32(f32(t) * f32(0.001))) - f32((t % 7) * 1000.5))
async def main():
boards = {"d1": (D1, D1V), "e32": (E32, E32V)}
hist = {
b: {"count": [], "float": set(), "bin": [], "count_to_float": {}}
for b in boards
}
obs = {} # (receiver, kind, field) -> list of (t, value, missing)
clients = {}
for b, (host, _) in boards.items():
c = await connect(host)
clients[b] = c
ents, _ = await c.list_entities_services()
keys = {e.key: e.object_id for e in ents}
peer_var = boards["e32" if b == "d1" else "d1"][1]
last = {}
def cb(s, b=b, keys=keys, peer_var=peer_var, last=last):
oid = keys.get(s.key)
t = time.monotonic()
if oid is None:
return
miss = bool(s.missing_state) or (
isinstance(s.state, float) and math.isnan(s.state)
)
h = hist[b]
if oid == "local_count" and not miss:
h["count"].append((t, int(s.state)))
last["count"] = int(s.state)
elif oid == "local_float" and not miss:
h["float"].add(f32(s.state))
if "count" in last:
h["count_to_float"][last["count"]] = f32(s.state)
elif oid == "local_bin":
h["bin"].append((t, bool(s.state)))
elif oid.startswith("r_"):
_, kind, var, field = oid.split("_")
if var == peer_var:
obs.setdefault(f"{b}<-{kind}:{field}", []).append(
(t, s.state, miss)
)
elif not miss:
obs.setdefault(f"{b}<-{kind}:{field}:otherpeer", []).append(
(t, s.state, False)
)
c.subscribe_states(cb)
await asyncio.sleep(SECS)
for c in clients.values():
await c.disconnect()
res = {"d1": D1V, "e32": E32V, "seconds": SECS, "links": {}}
for key, lst in sorted(obs.items()):
recv, rest = key.split("<-")
kind, field = rest.split(":")[:2]
sender = "e32" if recv == "d1" else "d1"
h = hist[sender]
if key.endswith("otherpeer"):
res["links"][key] = {"values_after_initial": len(lst) - 1}
continue
vals = [(t, v) for t, v, m in lst if not m][
1:
] # the first is the state from before the run
missing_after_first = sum(
1
for i, (t, v, m) in enumerate(lst)
if m and any(not mm for _, _, mm in lst[:i])
)
r = {"updates": len(vals), "missing_after_first": missing_after_first}
if field == "count":
sent = {c for _, c in h["count"]}
first = min(sent) if sent else 0
r["before_run"] = sum(1 for _, v in vals if int(v) < first)
last_sent = max(sent) if sent else 0
r["not_sent"] = sum(
1 for _, v in vals if int(v) > last_sent + 60 or int(v) != v
)
r["api_gap_values"] = sum(
1
for _, v in vals
if first <= int(v) <= last_sent and int(v) not in sent
)
lags = []
for t, v in vals:
prior = [c for tt, c in h["count"] if tt <= t]
if prior:
lags.append(prior[-1] - int(v))
r["max_lag_s"] = max(lags) if lags else None
elif field == "flt" and not h["count"]:
# no sender count over the API: the floats cannot be checked, which fails the link
r["no_sender_counts"] = True
elif field == "flt":
ok_t = [
t
for t, v, _m in obs[key.replace("flt", "count")]
if not (isinstance(v, float) and math.isnan(v))
and int(v) >= min(c for _, c in h["count"])
]
t0 = min(ok_t) if ok_t else 0
lo, hi = min(c for _, c in h["count"]), max(c for _, c in h["count"]) + 60
allowed = {expect(c) for c in range(max(1, lo - 30), hi + 1)}
r["not_sent"] = sum(1 for t, v in vals if t >= t0 and f32(v) not in allowed)
r["sender_float_mismatch"] = sum(
1 for c, fv in h["count_to_float"].items() if fv != expect(c)
)
else:
sent = [v for _, v in h["bin"]]
r["transitions"] = sum(
1 for i in range(1, len(vals)) if vals[i][1] != vals[i - 1][1]
)
r["sender_transitions"] = sum(
1 for i in range(1, len(sent)) if sent[i] != sent[i - 1]
)
res["links"][key] = r
ok = True
for k, r in res["links"].items():
if k.endswith("otherpeer"):
ok = ok and r["values_after_initial"] == 0
continue
if (
r["updates"] < 3
or r.get("not_sent", 0)
or r.get("sender_float_mismatch", 0)
or r.get("no_sender_counts")
):
ok = False
if "transitions" in r and r["transitions"] < 2:
ok = False
res["expected_links_present"] = (
len([k for k in res["links"] if not k.endswith("otherpeer")]) == 12
)
res["pass"] = ok and res["expected_links_present"]
print(json.dumps(res, indent=1))
pathlib.Path(OUT).write_text(json.dumps(res, indent=1), encoding="utf-8")
return 0 if res["pass"] else 1
sys.exit(asyncio.run(main()))
@@ -1,62 +0,0 @@
"""cmp.py REF.json OTHER.json : list each UUID (service / characteristic / descriptor, in order) where OTHER differs
from REF, whether reads match (static characteristics), whether every notifying characteristic notified and
whether OTHER lost its link before the final disconnect. Exits 1 on any difference."""
import json
import pathlib
import sys
def flat(p):
d = json.loads(pathlib.Path(p).read_text(encoding="utf-8"))
rows = []
for s in d["services"]:
rows.append(("svc", s["uuid"].lower()))
for c in s["characteristics"]:
rows.append(("chr", c["uuid"].lower()))
rows += [("dsc", x.lower()) for x in c["descriptors"]]
return d, rows
rd, ref = flat(sys.argv[1])
od, oth = flat(sys.argv[2])
diff = [(a, b) for a, b in zip(ref, oth, strict=False) if a != b]
print(
f"entries ref={len(ref)} other={len(oth)} differing={len(diff) + abs(len(ref) - len(oth))}"
)
for a, b in diff:
print(f" {a[0]} ref {a[1]} other {b[1]}")
def chars(d: dict) -> list[dict]:
return [c for s in d["services"] for c in s["characteristics"]]
# compare by position: a UUID form bug renames the keys, so values and notify counts are matched by table order
problems = []
rc, oc = chars(rd), chars(od)
for i, (a, b) in enumerate(zip(rc, oc, strict=False)):
if a["props"] != b["props"]:
problems.append(
f"props {i} {b['uuid']} 0x{b['props']:02X} != ref 0x{a['props']:02X}"
)
rv, ov = rd["reads"].get(a["uuid"]), od["reads"].get(b["uuid"])
if str(ov).startswith("FAILED"):
problems.append(f"read {i} {b['uuid']} {ov}")
elif not a["props"] & 0x10 and rv is not None and ov != rv:
problems.append(f"read {i} {b['uuid']} {ov!r} != ref {rv!r}")
if a["props"] & 0x10:
n = od["notify"].get(b["uuid"])
if not isinstance(n, int) or n <= 0:
problems.append(f"notify {i} {b['uuid']} {n}")
# a link that dropped after the first notification still has counts, so the drop itself fails the run
if od.get("lost"):
problems.append(f"link lost before the disconnect: {od['lost']}")
print(f"notify {od['notify']}")
for x in problems:
print(" ", x)
if diff or len(ref) != len(oth) or problems:
sys.exit(
f"FAIL: {len(diff)} differing entries, {len(problems)} read or notify problems"
)
print("PASS")
@@ -1,100 +0,0 @@
"""List every service, characteristic and descriptor UUID a bluetooth_proxy reports for a peer, read each readable
characteristic, enable notify (CCCD write) on each notifying one and count 10 s of notifications, then disconnect.
A link lost before that disconnect is recorded as "lost" in the JSON, which cmp.py fails on.
usage: gattlist.py PROXY PEER_MAC OUT_JSON env: API_KEY (unset for a plaintext API). Retries 0x3E connect failures."""
import asyncio
import json
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from apiconn import ble_connect, connect, enable_notify # noqa: E402
async def once(host: str, addr: int) -> dict | None:
cli = await connect(host)
lost: list[int] = []
closing = False
def on_lost(e: int) -> None:
if not closing:
lost.append(e)
print(f"LINK LOST err={e}", flush=True)
c, _mtu, err, cancel = await ble_connect(cli, addr, on_lost)
if not c:
print(f"connect err={err}", flush=True)
cancel()
await cli.disconnect()
return None
svcs = await cli.bluetooth_gatt_get_services(addr)
out = {"services": [], "reads": {}, "notify": {}}
notif: dict[str, int] = {}
for s in svcs.services:
so = {"uuid": s.uuid, "characteristics": []}
for ch in s.characteristics:
so["characteristics"].append(
{
"uuid": ch.uuid,
"props": ch.properties,
"descriptors": [d.uuid for d in ch.descriptors],
}
)
if ch.properties & 0x02:
try:
out["reads"][ch.uuid] = bytes(
await cli.bluetooth_gatt_read(addr, ch.handle)
).hex()
except Exception as e: # noqa: BLE001
out["reads"][ch.uuid] = f"FAILED {type(e).__name__}"
if ch.properties & 0x10:
notif[ch.uuid] = 0
try:
if not await enable_notify(
cli,
addr,
ch,
lambda h, d, u=ch.uuid: (
notif.__setitem__(u, notif[u] + 1)
if isinstance(notif[u], int)
else None
),
):
notif[ch.uuid] = "FAILED no CCCD"
except Exception as e: # noqa: BLE001
notif[ch.uuid] = f"FAILED {type(e).__name__}"
out["services"].append(so)
await asyncio.sleep(10)
out["notify"] = notif
out["lost"] = lost
closing = True
await cli.bluetooth_device_disconnect(addr)
await asyncio.sleep(2)
cancel()
await cli.disconnect()
return out
async def main(host: str, peer: str, path: str) -> None:
addr = int(peer.replace(":", ""), 16)
for _attempt in range(6):
res = await once(host, addr)
if res:
break
await asyncio.sleep(10)
else:
sys.exit("FAIL: no connection")
pathlib.Path(path).write_text(json.dumps(res, indent=1), encoding="utf-8")
for s in res["services"]:
print(f"SVC {s['uuid']}")
for c in s["characteristics"]:
print(
f" CHR {c['uuid']} props=0x{c['props']:02X} read={res['reads'].get(c['uuid'], '-')}"
f" notify={res['notify'].get(c['uuid'], '-')}"
)
for d in c["descriptors"]:
print(f" DSC {d}")
asyncio.run(main(sys.argv[1], sys.argv[2], sys.argv[3]))
@@ -1,14 +0,0 @@
#!/bin/zsh
# run.sh NAME: build ../rp2_web_ble/picow.yaml as NAME, USB flash the Pico W proxy, list the GATT UUID server
# (server.yaml here) through it and compare with the ESP32 reference. Exit 0 only when the lists match.
# env: TREE, PY, PICO_SN, PEER_MAC (the server); esp32ref.json (gattlist.py through an ESP32 proxy) and apikey.txt here
D=${0:A:h}; N=$1; S=$D/..; T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}; C=$S/rp2_web_ble/picow.yaml
$S/pio_build.sh compile $N $C || exit 1
PORT=$($PY $S/ports.py --wait 2e8a --serial ${PICO_SN:?set PICO_SN} --timeout 30) || { echo "no pico"; exit 1; }
$S/pio_build.sh upload $N $C $PORT || exit 1
H=$($S/resolve.sh $N) || exit 1; sleep 5
rm -f $D/$N.json
API_KEY=$(cat $D/apikey.txt) timeout 600 $PY -I $D/gattlist.py $H ${PEER_MAC:?set PEER_MAC} $D/$N.json > $D/$N-list.txt
RC=$?; grep -v "^ *CHR 00002a\|DSC 00002902\|SVC 000018" $D/$N-list.txt
[ $RC = 0 ] && [ -s $D/$N.json ] || { echo "FAIL: gattlist.py exited $RC"; exit 1; }
$PY $D/cmp.py $D/esp32ref.json $D/$N.json
@@ -1,27 +0,0 @@
# GATT server (ESP32-S3) for the UUID form check: the ble_notify server (16 bit and 32-bit base UUIDs, notify) plus a
# 128 bit service whose characteristics and descriptors use 128 bit, 32-bit base (zero and nonzero low half) and
# 16 bit UUIDs, with a 2901 user description. Set the name with -s name.
packages:
notify: !include ../ble_notify/server.yaml
esp32_ble_server:
services:
- uuid: 0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0
characteristics:
- uuid: 0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f1
read: true
value: "c128"
description: "text value"
descriptors:
- uuid: 5ec1ab01-0000-1000-8000-00805f9b34fb
value: "d32"
- uuid: 7d3e0a51-9c1b-4f2e-8a6d-1c2b3a4d5e6f
value: "d128"
- uuid: 5ec20000-0000-1000-8000-00805f9b34fb
read: true
value: "c32zero"
- uuid: 5ec2abcd-0000-1000-8000-00805f9b34fb
read: true
value: "c32"
- uuid: 2a19
read: true
value: [77]
@@ -1,18 +0,0 @@
# Package for Improv tests: Wi-Fi with no network saved, web_server and improv_serial with a next_url, and an ALIVE
# line every 5 s. Substitution: name. Drop web_server on a LibreTiny board with no ap: (it boot-loops, see
# reference/recipes/improv.md).
esphome:
name: ${name}
wifi:
power_save_mode: none
web_server:
improv_serial:
next_url: https://example.com/?device_name={{device_name}}&ip_address={{ip_address}}
interval:
- interval: 5s
then:
- logger.log: "ALIVE"
@@ -1,15 +0,0 @@
# Classic ESP32 devkit with Improv over serial (UART0, shared with the log) and BLE. Copy it per build with its own
# name; run.sh wants the file name to match name.
substitutions:
name: improv32
packages:
common: !include common.yaml
esp32:
board: esp32dev
framework:
type: esp-idf
logger:
hardware_uart: UART0
improv_ble:
authorizer: none
next_url: https://example.com/?device_name={{device_name}}&ip_address={{ip_address}}
@@ -1,96 +0,0 @@
"""Improv over BLE: find the device by name, send WIFI_SETTINGS and print state, errors and the RPC result URLs.
usage: improvble.py NAME SECRETS (needs bleak; the device needs improv_ble authorizer: none and a next_url)"""
import asyncio
import pathlib
import sys
from bleak import BleakClient, BleakScanner
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from improvcli import load_wifi_secrets, strings # noqa: E402
BASE = "00467768-6228-2272-4663-2774782680"
STATE, ERROR, RPC, RESULT = BASE + "01", BASE + "02", BASE + "03", BASE + "04"
STATES = {1: "awaiting_auth", 2: "authorized", 3: "provisioning", 4: "provisioned"}
def pkt(cmd: int, data: bytes) -> bytes:
b = bytes([cmd, len(data)]) + data
return b + bytes([sum(b) & 0xFF])
async def main(name: str, secrets: str) -> None:
ssid, pw = (x.encode() for x in load_wifi_secrets(secrets))
dev = await BleakScanner.find_device_by_name(name, timeout=30)
if dev is None:
sys.exit(
"FAIL: device not found (a provisioned board stops advertising Improv)"
)
loop = asyncio.get_running_loop()
t0 = loop.time()
done = asyncio.Event()
errors: list = []
states: list[int] = []
async with BleakClient(dev) as c:
def on_state(_, d: bytearray) -> None:
if not d:
errors.append("empty state")
return
states.append(d[0])
print(f"{loop.time() - t0:6.2f} STATE {STATES.get(d[0], d[0])}", flush=True)
def on_error(_, d: bytearray) -> None:
if not d:
errors.append("empty error")
elif d[0]:
errors.append(d[0])
print(f"{loop.time() - t0:6.2f} ERROR {d[0]}", flush=True)
def on_result(_, d: bytearray) -> None:
if len(d) < 3 or d[1] != len(d) - 3 or sum(d[:-1]) & 0xFF != d[-1]:
errors.append("bad result frame")
print(
f"{loop.time() - t0:6.2f} BAD RESULT {bytes(d).hex()}", flush=True
)
return
try:
strs = strings(bytes(d[2:-1]))
except ValueError:
errors.append("string overruns the result")
strs = []
print(f"{loop.time() - t0:6.2f} RESULT cmd={d[0]} {strs}", flush=True)
if (
d[0] == 1
): # the WIFI_SETTINGS reply; the example sets next_url, so it carries a URL
if not any(x.startswith("http") for x in strs):
errors.append("no URL in result")
done.set()
await c.start_notify(STATE, on_state)
await c.start_notify(ERROR, on_error)
await c.start_notify(RESULT, on_result)
s = await c.read_gatt_char(STATE)
print(f"initial state {STATES.get(s[0], s[0]) if s else 'empty'}")
if not s or s[0] == 4:
sys.exit(
"FAIL: board already provisioned or no state; erase the flash first"
)
payload = bytes([len(ssid)]) + ssid + bytes([len(pw)]) + pw
await c.write_gatt_char(RPC, pkt(1, payload), response=True)
try:
await asyncio.wait_for(done.wait(), 45)
except TimeoutError:
print("no result within 45 s")
await asyncio.sleep(1)
last = await c.read_gatt_char(STATE)
states.append(last[0] if last else 0)
if not done.is_set() or errors or states[-1] != 4:
sys.exit(
f"FAIL (errors {errors}, last state {STATES.get(states[-1], states[-1])})"
)
print("PASS")
asyncio.run(main(sys.argv[1], sys.argv[2]))
@@ -1,340 +0,0 @@
"""Improv serial client that reads frames out of the log stream on the same port.
usage: improvcli.py PORT OUT --secrets FILE [--baud N] [--keep-dtr] [--settle S] [--skip-bad] [--allow-reset]
Runs: 300 stray bytes, state, info, network state, scan, provision with a bad password, provision with the real one,
state and network state again. Prints parsed frames; the raw stream overwrites OUT.
Exit 2 when the port does not open or the secrets file lacks a key. Exit 1 when any request goes unanswered, an
unexpected error or a malformed frame arrives, or the port resets or the log shows a reboot (unless --allow-reset).
Credentials come from the secrets file (wifi_ssid, wifi_password) and are never printed; the SSID is masked in scan
results."""
import argparse
import pathlib
import random
import sys
import time
import serial
import yaml
STATES = {
0: "stopped",
1: "awaiting_auth",
2: "authorized",
3: "provisioning",
4: "provisioned",
}
ERRORS = {
0: "none",
1: "invalid_rpc",
2: "unknown_rpc",
3: "unable_to_connect",
4: "not_authorized",
0xFF: "unknown",
}
def frame(cmd: int, payload: bytes = b"") -> bytes:
data = bytes([cmd, len(payload)]) + payload
body = b"IMPROV" + bytes([1, 3, len(data)]) + data
return body + bytes([sum(body) & 0xFF])
BOOT_MARKER = (
b"Running through setup()" # ESPHome logs it once per boot on every platform
)
def rpc_strings(data: bytes) -> bytes:
return data[2 : 2 + data[1]]
def strings(p: bytes, raw: bool = False) -> list:
"""Split length-prefixed strings (bytes with raw); raise ValueError when a prefix runs past the end."""
out = []
while p:
if 1 + p[0] > len(p):
raise ValueError("string overruns the payload")
b = p[1 : 1 + p[0]]
out.append(b if raw else b.decode(errors="replace"))
p = p[1 + p[0] :]
return out
def load_wifi_secrets(path: str) -> tuple[str, str]:
"""wifi_ssid and wifi_password from a secrets file; exits 2 (setup error) when it cannot be used."""
try:
with pathlib.Path(path).open(encoding="utf-8") as f:
sec = yaml.safe_load(f)
except (OSError, yaml.YAMLError) as exc:
print(f"cannot read secrets file: {exc}", file=sys.stderr)
sys.exit(2)
try:
raw = (sec["wifi_ssid"], sec["wifi_password"])
except (KeyError, TypeError) as exc:
print(f"secrets file lacks {exc}", file=sys.stderr)
sys.exit(2)
if not all(
isinstance(x, (str, int, float)) and not isinstance(x, bool) for x in raw
):
print("wifi_ssid and wifi_password must be plain values", file=sys.stderr)
sys.exit(2)
return str(raw[0]), str(raw[1]) # YAML reads an unquoted number as int
class Dev:
def __init__(
self, port: str, baud: int, out: str, keep_dtr: bool, ssid: str
) -> None:
self.ser = serial.Serial()
self.ser.port, self.ser.baudrate, self.ser.timeout = port, baud, 0.05
if not keep_dtr:
self.ser.dtr = False
self.ser.rts = False
self.reopen(setup=True)
self.buf = bytearray()
try:
self.log = pathlib.Path(out).open("wb") # noqa: SIM115
except OSError as exc:
print(f"cannot open output file: {exc}", file=sys.stderr)
sys.exit(2)
self.t0 = time.time()
self.events: list[tuple[float, int, bytes, bool]] = []
self.loglines = 0
self.reopens = 0
self.boots = 0
self.tail = b""
self.ssid = ssid
def reopen(self, setup: bool = False) -> None:
# Native USB ports re-enumerate on reset; wait up to 10 s for them.
err: Exception | None = None
for _ in range(40):
try:
if self.ser.is_open:
self.ser.close()
self.ser.open()
return
except (serial.SerialException, OSError) as exc:
err = exc
time.sleep(0.25)
print(
f"port did not {'open' if setup else 'come back'}: {err}", file=sys.stderr
)
sys.exit(2 if setup else 1)
def pump(self, dur: float) -> None:
end = time.time() + dur
while time.time() < end:
try:
d = self.ser.read(4096)
except serial.SerialException:
# A dropped native USB port usually means the board reset; make that visible.
self.reopens += 1
print(
f"{time.time() - self.t0:7.2f} PORT RESET (reopen {self.reopens})",
flush=True,
)
self.reopen()
continue
if d:
seen = self.tail + d
self.boots += seen.count(BOOT_MARKER)
self.tail = seen[-(len(BOOT_MARKER) - 1) :]
self.log.write(d)
self.log.flush()
self.buf += d
self.parse()
def parse(self) -> None:
while True:
i = self.buf.find(b"IMPROV")
if i < 0:
keep = max(0, len(self.buf) - 6)
self.loglines += self.buf[:keep].count(b"\n")
del self.buf[:keep]
return
self.loglines += self.buf[:i].count(b"\n")
del self.buf[:i]
if len(self.buf) < 9:
return
if self.buf[6] != 1: # not a version 1 header: "IMPROV" in log text
del self.buf[:6]
continue
ln = self.buf[8]
if len(self.buf) < 10 + ln:
return
body, ck = bytes(self.buf[: 9 + ln]), self.buf[9 + ln]
del self.buf[: 10 + ln]
typ, data = body[7], body[9:]
ok = (sum(body) & 0xFF) == ck
# A malformed frame is counted as bad, so the predicates never index past it.
short = len(data) < {1: 1, 2: 1, 4: 2}.get(typ, 0)
if typ == 4 and not short:
try:
# ESPHome sends one trailing byte after the strings (an unused checksum slot).
short = data[1] > len(data) - 2
strings(rpc_strings(data))
except ValueError:
short = True
self.events.append((time.time() - self.t0, typ, data, ok and not short))
self.show(typ, data, ok, short)
def show(self, typ: int, data: bytes, ok: bool, short: bool) -> None:
t = f"{time.time() - self.t0:7.2f}"
tag = "" if ok else " BADCHECKSUM"
if short:
print(f"{t} TYPE{typ} {data.hex()} MALFORMED{tag}")
elif typ == 1:
print(f"{t} STATE {STATES.get(data[0], data[0])}{tag}")
elif typ == 2:
print(f"{t} ERROR {ERRORS.get(data[0], data[0])}{tag}")
elif typ == 4:
strs = [
"<ssid>" if x == self.ssid else x for x in strings(rpc_strings(data))
]
print(f"{t} RPC cmd={data[0]} len={data[1]} {strs}{tag}")
else:
print(f"{t} TYPE{typ} {data.hex()}{tag}")
def send(self, cmd: int, payload: bytes = b"", wait: float = 2.0) -> None:
self.ser.write(frame(cmd, payload))
self.ser.flush()
self.pump(wait)
def wait_for(self, pred, timeout: float, start: int) -> tuple | None:
end = time.time() + timeout
while time.time() < end:
self.pump(0.2)
for e in self.events[start:]:
if pred(e):
return e
return None
def ask(
d: Dev, label: str, cmd: int, pred, timeout: float = 1.5, payload: bytes = b""
) -> bool:
"""Send one request and require a reply matching pred; any other nonzero ERROR frame fails it."""
print(f"== {label}")
start = len(d.events) # before sending, so an immediate reply counts
t = time.time()
d.send(cmd, payload, wait=0)
e = d.wait_for(pred, timeout, start)
print(
f"reply after {time.time() - t:.1f}s"
if e
else f"NO reply within {timeout:.0f}s"
)
errs = [
x for x in d.events[start:] if x[1] == 2 and x[3] and x[2][0] and not pred(x)
]
if errs:
print(f"unexpected errors: {[ERRORS.get(x[2][0], x[2][0]) for x in errs]}")
return e is not None and not errs
def rpc(cmd: int):
return lambda e: e[1] == 4 and e[3] and e[2][0] == cmd
def state(e: tuple) -> bool:
return e[1] == 1 and e[3]
def main() -> None:
a = argparse.ArgumentParser()
a.add_argument("port")
a.add_argument("out")
a.add_argument("--baud", type=int, default=115200)
a.add_argument(
"--keep-dtr",
action="store_true",
help="leave DTR asserted (Pico 2 W CDC sends nothing without)",
)
a.add_argument("--secrets", required=True)
a.add_argument("--settle", type=float, default=3)
a.add_argument("--skip-bad", action="store_true")
a.add_argument(
"--allow-reset",
action="store_true",
help="a port reset or a reboot in the log does not fail the run",
)
o = a.parse_args()
ssid, pw = load_wifi_secrets(o.secrets)
s, w = ssid.encode(), pw.encode()
print(f"password length {len(w)} bytes")
d = Dev(o.port, o.baud, o.out, o.keep_dtr, ssid)
d.pump(o.settle)
boots_at_start = d.boots
before = d.loglines
print("== stray bytes")
j = len(d.events)
junk = bytes(
random.choice([b for b in range(256) if b != 0x49]) for _ in range(300)
)
d.ser.write(junk)
d.ser.flush()
d.pump(1.0)
# Stray bytes must be ignored silently; the state reply below shows the parser recovered.
ok = not any(e[1] == 2 and e[3] and e[2][0] for e in d.events[j:])
# A saved network skips provisioning: the board must start unprovisioned.
ok &= ask(d, "state", 2, lambda e: state(e) and e[2][0] != 4)
if any(state(e) and e[2][0] == 4 for e in d.events[j:]):
# The rest of the flow means nothing on a provisioned board; stop before re-provisioning it.
print(
"board is already provisioned: erase the flash first (a new config name keeps the saved network)"
)
print("FAIL")
sys.exit(1)
ok &= ask(d, "info", 3, rpc(3))
ok &= ask(d, "netstate", 7, rpc(7))
# The scan sends one reply per network and ends with an empty one.
ok &= ask(d, "scan", 4, lambda e: rpc(4)(e) and e[2][1] == 0, timeout=10)
seen = any(e[1] == 4 and e[3] and e[2][0] == 4 and s in e[2] for e in d.events)
print(f"target network in scan: {seen}")
creds = bytes([len(s)]) + s
if not o.skip_bad:
bad_pw = b"wrong-password-0123456789"
ok &= ask(
d,
"provision bad password",
1,
lambda e: e[1] == 2 and e[3] and e[2][0] == 3,
timeout=60,
payload=creds + bytes([len(bad_pw)]) + bad_pw,
)
d.pump(2)
# common.yaml sets next_url, so the provisioned reply must carry a URL.
ok &= ask(
d,
"provision good",
1,
lambda e: (
rpc(1)(e) and any(x.startswith("http") for x in strings(rpc_strings(e[2])))
),
timeout=60,
payload=creds + bytes([len(w)]) + w,
)
d.pump(3)
ok &= ask(d, "state is provisioned", 2, lambda e: state(e) and e[2][0] == 4)
ok &= ask(d, "netstate", 7, rpc(7))
d.pump(2)
bad = sum(1 for e in d.events if not e[3])
# Errors outside an ask() window, boot included: only the bad password case may report one.
errors = sum(1 for e in d.events if e[1] == 2 and e[3] and e[2][0])
if errors > (0 if o.skip_bad else 1):
print(f"unexpected error frames: {errors}")
ok = False
reboots = d.boots - boots_at_start
if (d.reopens or reboots) and not o.allow_reset:
ok = False
print(
f"frames={len(d.events)} badframes={bad} reopens={d.reopens} reboots={reboots} loglines={d.loglines} "
f"(before stray {before})"
)
print("PASS" if ok and not bad else "FAIL")
sys.exit(0 if ok and not bad else 1)
if __name__ == "__main__":
main()
@@ -1,70 +0,0 @@
"""Improv RPC request scan over the logger UART: dump each reply's fields (auth field as raw bytes).
usage: improvscan.py PORT OUT [--settle S]
Opens the port with DTR and RTS low, waits SETTLE seconds (a D1 mini and a classic ESP32 still reset on open), sends
request scan (0x04) and reads until the end-of-list reply or 15 s. OUT gets one line per reply and OUT.raw the raw
stream; prints the reply count, the auth values seen and the bad checksum count.
"""
import argparse
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from improvcli import Dev, frame, rpc_strings, strings # noqa: E402
class ScanDev(Dev):
"""Collects scan replies as they are parsed instead of printing every frame."""
def __init__(self, *args) -> None:
super().__init__(*args)
self.lines: list[str] = []
self.auths: set[bytes] = set()
self.bad_checksums = 0
self.malformed = 0
def show(self, typ: int, data: bytes, ok: bool, short: bool) -> None:
if typ != 4:
return
self.bad_checksums += not ok
if short:
self.malformed += 1
self.lines.append(f"reply malformed {data.hex()} checksum_ok={ok}")
return
strs = strings(rpc_strings(data), raw=True)
if not strs:
self.lines.append(f"reply cmd={data[0]} checksum_ok={ok} end of list")
return
self.auths.add(strs[-1])
self.lines.append(
f"reply cmd={data[0]} checksum_ok={ok} fields={len(strs)} auth={strs[-1]!r} auth_len={len(strs[-1])} "
f"rssi_len={len(strs[1]) if len(strs) > 1 else -1}"
)
def main() -> None:
a = argparse.ArgumentParser()
a.add_argument("port")
a.add_argument("out")
a.add_argument("--settle", type=float, default=30)
o = a.parse_args()
d = ScanDev(o.port, 115200, o.out + ".raw", False, "")
d.pump(o.settle)
start = len(d.events)
d.ser.write(frame(4))
d.ser.flush()
end = d.wait_for(
lambda e: e[1] == 4 and e[3] and e[2][0] == 4 and e[2][1] == 0, 15, start
)
d.ser.close()
pathlib.Path(o.out).write_text("\n".join(d.lines) + "\n", encoding="utf-8")
print(
f"{len(d.lines)} replies; auth values: {sorted(d.auths)}; bad checksums: {d.bad_checksums}; malformed: {d.malformed}"
+ ("" if end else "; NO end-of-list reply within 15 s")
)
sys.exit(0 if end and not d.bad_checksums and not d.malformed else 1)
if __name__ == "__main__":
main()
@@ -1,10 +0,0 @@
esphome:
name: openap32
esp32:
board: esp32dev
framework:
type: esp-idf
logger:
wifi:
ap:
ssid: hwtest-open-ap
@@ -1,23 +0,0 @@
#!/bin/bash
# run.sh NAME [improvcli.py args...]: build NAME.yaml (next to this script, or a path) from TREE, erase the flash so no
# credentials are saved, flash it over serial and run improvcli.py on PORT. Output lands in out-NAME/.
# env: TREE (checkout under test), PORT, PY (checkout python), SECRETS (secrets.yaml with wifi_ssid, wifi_password),
# BUILD_LOCK (optional); builds go through ../pio_build.sh with a private PlatformIO directory
# ESP chips only (esptool erase). On LibreTiny or RP2040 erase and flash with that platform's tools, then run
# improvcli.py directly. Exit status is improvcli.py's: 0 pass, 1 fail, 2 setup failed.
set -o pipefail
D=$(cd "$(dirname "$0")" && pwd); N=${1:?name}; shift
W=${TREE:?set TREE}; PORT=${PORT:?set PORT}; S=${SECRETS:?set SECRETS}; PY=${PY:-$W/venv/bin/python}
Y=$N; [ -f "$Y" ] || Y=$D/$N.yaml; Y=$(cd "$(dirname "$Y")" && pwd)/$(basename "$Y"); N=$(basename "$Y" .yaml)
O=$D/out-$N; mkdir -p "$O"
REV=$(git -C "$W" rev-parse --short=10 HEAD) || { echo "TREE is not a git checkout: $W"; exit 2; }
echo "== $N $REV"
# the erase runs while the firmware compiles
$PY -m esptool --port "$PORT" erase_flash > "$O/erase.log" 2>&1 &
ERASE=$!
"$(dirname "$D")/pio_build.sh" compile "$N" "$Y" || { wait $ERASE; exit 2; }
wait $ERASE || { echo "$N erase failed"; exit 2; }
"$(dirname "$D")/pio_build.sh" upload "$N" "$Y" "$PORT" || exit 2
sleep 1
rm -f "$O/raw.bin"
$PY "$D/improvcli.py" "$PORT" "$O/raw.bin" --secrets "$S" "$@" 2>&1 | tee "$O/improv.txt"
@@ -1,58 +0,0 @@
"""drive.py HOST OUT: press exercise, read API sensor states and web_server sensor JSON."""
import asyncio
import http.client
import pathlib
import sys
import urllib.parse
import urllib.request
from aioesphomeapi import ButtonInfo, SensorInfo
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from apiconn import connect # noqa: E402
HOST, OUT = sys.argv[1], sys.argv[2]
async def main():
c = await connect(HOST)
ents, _ = await c.list_entities_services()
b = {e.name: e for e in ents if isinstance(e, ButtonInfo)}
sens = {e.key: e for e in ents if isinstance(e, SensorInfo)}
st = {}
c.subscribe_states(lambda s: st.__setitem__(s.key, s) if s.key in sens else None)
await asyncio.sleep(7)
c.button_command(b["exercise"].key)
await asyncio.sleep(3)
out = []
for k, e in sorted(sens.items(), key=lambda x: x[1].name):
s = st.get(k)
out.append(
f"API {e.name}: state={s.state!r} missing={s.missing_state} acc={e.accuracy_decimals}"
if s
else f"API {e.name}: no state"
)
for path in (f"/sensor/{urllib.parse.quote(e.name)}", f"/sensor/{e.object_id}"):
try:
out.append(
f"WEB {e.name}: "
+ urllib.request.urlopen(f"http://{HOST}{path}", timeout=5)
.read()
.decode()
)
break
except (OSError, http.client.HTTPException) as ex:
last = ex
else:
out.append(f"WEB {e.name}: error {last}")
await c.disconnect()
pathlib.Path(OUT).write_text("\n".join(out) + "\n", encoding="utf-8")
# a sensor with no API state or no web_server answer leaves a hole in the A/B comparison
holes = [x for x in out if x.endswith(": no state") or ": error " in x]
for x in holes:
print(x)
return 1 if holes else 0
sys.exit(asyncio.run(main()))
@@ -1,75 +0,0 @@
esphome:
name: ${name}
logger:
# sensor states and switch, light and fan calls log at VERBOSE; at DEBUG an A/B sees none of them
level: VERBOSE
api:
reboot_timeout: 0s
ota:
- platform: esphome
web_server:
port: 80
improv_serial:
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
binary_sensor:
- {platform: template, id: bs1, name: bs one, lambda: return true;}
- {platform: template, id: bs2, name: bs two, lambda: return false;}
switch:
- {platform: template, id: sw1, name: sw one, optimistic: true, restore_mode: ALWAYS_OFF, assumed_state: true}
number:
- {platform: template, name: num one, optimistic: true, min_value: 0, max_value: 10, step: 0.5, restore_value: false, initial_value: 2.5}
lock:
- {platform: template, name: lock one, optimistic: true, assumed_state: true}
fan:
- {platform: template, id: fan1, name: fan one, speed_count: 3, has_oscillating: true}
output:
- {platform: template, id: out1, type: binary, write_action: []}
light:
- {platform: binary, id: light1, name: light one, output: out1}
alarm_control_panel:
- platform: template
name: acp one
codes: ["1234"]
binary_sensors:
- input: bs1
bypass_armed_home: true
chime: true
- input: bs2
bypass_auto: true
sensor:
- {platform: template, id: s0, name: s acc0, accuracy_decimals: 0, lambda: return 12.5f;, update_interval: 5s}
- {platform: template, id: s2, name: s acc2, accuracy_decimals: 2, lambda: return 3.14159f;, update_interval: 5s}
- {platform: template, id: sneg, name: s neg2, accuracy_decimals: 2, lambda: return -0.005f;, update_interval: 5s}
- {platform: template, id: s_nan, name: s nan, accuracy_decimals: 1, lambda: return NAN;, update_interval: 5s}
- {platform: template, id: s_inf, name: s inf, accuracy_decimals: 1, lambda: return INFINITY;, update_interval: 5s}
- {platform: template, id: shi, name: s acc6, accuracy_decimals: 6, lambda: return 1.2345678f;, update_interval: 5s}
- {platform: template, id: sbig, name: s big, accuracy_decimals: 3, lambda: return 123456789.0f;, update_interval: 5s}
button:
- platform: template
name: exercise
on_press:
- lambda: |-
ESP_LOGI("lm", "MARK exercise");
ESPTime t = ESPTime::from_epoch_utc(1700000000);
char buf[ESPTime::STRFTIME_BUFFER_SIZE];
size_t n = t.strftime_to(buf, "%Y-%m-%d %H:%M:%S %A %B");
ESP_LOGI("lm", "STRF normal len=%u '%s'", (unsigned) n, buf);
n = t.strftime_to(buf, "%Y-%m-%d %H:%M:%S %A %B | %Y-%m-%d %H:%M:%S %A %B | %Y-%m-%d %H:%M:%S %A %B | %Y-%m-%d %H:%M:%S %A %B | %c");
ESP_LOGI("lm", "STRF overflow len=%u '%s'", (unsigned) n, buf);
ESP_LOGI("lm", "WORDS %s %s %s %s %s %s", YESNO(true), YESNO(false), ONOFF(true), ONOFF(false), TRUEFALSE(true), TRUEFALSE(false));
- switch.toggle: sw1
- delay: 200ms
- switch.toggle: sw1
- fan.turn_on: {id: fan1, speed: 2, oscillating: true}
- delay: 200ms
- fan.turn_off: fan1
- light.turn_on: light1
- delay: 200ms
- light.turn_off: light1
- lambda: ESP_LOGI("lm", "MARK exercise done");
text_sensor:
- platform: wifi_info
scan_results:
name: scan results
@@ -1,68 +0,0 @@
"""norm.py SERIAL: config lines ([C] and indented follow-ups), lm lines, sensor/switch/fan/light/lock state lines.
Volatile values are masked, not dropped, so a line that changes between builds still shows in the diff: addresses,
the device name (from the Hostname line), signal, setup times, and the value of keys that change per boot or per build.
"""
import pathlib
import re
import sys
out = []
cfg = False
MASKS = (
(re.compile(r"\b(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}\b"), "<mac>"),
(re.compile(r"\b\d{1,3}(?:\.\d{1,3}){3}\b"), "<ip>"),
(re.compile(r"-?\d+(?:\.\d+)? ?dBm?\b.*"), "<dB>"),
(re.compile(r"\btook \d+ ?ms\b"), "took <t>"),
)
# keys whose value changes per boot, per board or per build; the key stays, the value becomes <v>
VOLATILE_KEY = re.compile(
r"^((?:\w [\w.]+: )?\s*(?:Channel|Unsuccessful boot attempts|Reset reason|Wakeup cause|Free heap|Heap|"
r"Uptime|Compiled|Compilation time|Config hash|Build|ESPHome version|Flash size|CPU frequency|Chip):\s*)\S.*$",
re.IGNORECASE,
)
name = None
with pathlib.Path(sys.argv[1]).open(encoding="utf-8", errors="replace") as fh:
for raw in fh:
x = re.sub(r"^\[[0-9:.]+\]", "", raw.rstrip("\n"))
m = re.match(r"\[(\w)\]\[([\w.]+)(?::\d+)?\]: ?(.*)$", x)
if m:
lvl, tag, msg = m.groups()
cfg = lvl == "C"
if (
lvl == "C"
or tag == "lm"
or re.search(r"State|state|Setting|Sending|Turning|'.*'", msg)
and tag
in (
"sensor",
"switch",
"fan",
"light",
"lock",
"binary_sensor",
"number",
"alarm_control_panel",
"template.alarm_control_panel",
)
):
line = f"{lvl} {tag}: {msg}"
else:
continue
elif cfg and x.startswith(" "):
line = " " + x.strip()
else:
continue
if name is None and (m := re.search(r"Hostname: '?([\w-]+)'?$", line)):
name = m.group(1)
line = VOLATILE_KEY.sub(r"\1<v>", line)
for rx, repl in MASKS:
line = rx.sub(repl, line)
out.append(line)
text = "\n".join(out)
if name:
text = re.sub(rf"\b{re.escape(name)}\b", "<name>", text)
print(text)
if not out:
sys.exit(f"no config, lm or state lines in {sys.argv[1]}")
@@ -1,20 +0,0 @@
# XIAO nRF54LM20A with every nPM1300 entity: dumps the registers and switch states 8 s after boot, then runs the
# toggles script. Name set with -s name.
esphome:
name: ${name}
on_boot:
- priority: -100
then:
- delay: 8s
- script.execute: regdump
- script.execute: swdump
- delay: 2s
- script.execute: toggles
nrf52:
board: xiao_nrf54lm20a
logger:
level: DEBUG
hardware_uart: UART0
packages:
regdump: !include regdump.yaml
common: !include npmcommon.yaml
@@ -1,179 +0,0 @@
# nPM1300 hub with every entity, a 500 mA VBUS limit, the charger settings, BUCK2 at 3.3 V and LDO1 as a 3.3 V LDO,
# state log lines from on_value and on_state lambdas, a register and switch dump every 60 s, and a toggles script
# (charger off and on, LDO1 off and on). Never switch BUCK2 off on the XIAO nRF54LM20A: it powers the board.
i2c:
- id: pmic_bus
sda: P1.18
scl: P1.17
npm1300:
id: pmic
i2c_id: pmic_bus
update_interval: 5s
vbus_current_limit: 500mA
thermistor_resistance: 10kOhm
thermistor_beta: 3380
charger:
charge_current: 150mA
termination_voltage: 4.2V
warm_termination_voltage: 4.0V
termination_current: 20%
trickle_voltage: 2.5V
discharge_current_limit: 1000mA
recharge: true
buck2:
voltage: 3.3V
ldo1:
voltage: 3.3V
mode: ldo
enabled: true
ldo2:
mode: load_switch
enabled: false
globals:
- id: txt_count
type: int
initial_value: '0'
sensor:
- platform: npm1300
battery_voltage:
name: VBAT
on_value:
- lambda: 'ESP_LOGI("st", "SENS VBAT=%.4f", x);'
battery_current:
name: IBAT
on_value:
- lambda: 'ESP_LOGI("st", "SENS IBAT=%.4f", x);'
battery_temperature:
name: TBAT
on_value:
- lambda: 'ESP_LOGI("st", "SENS TBAT=%.4f", x);'
die_temperature:
name: TDIE
on_value:
- lambda: 'ESP_LOGI("st", "SENS TDIE=%.4f", x);'
system_voltage:
name: VSYS
on_value:
- lambda: 'ESP_LOGI("st", "SENS VSYS=%.4f", x);'
vbus_voltage:
name: VBUS
on_value:
- lambda: 'ESP_LOGI("st", "SENS VBUS=%.4f", x);'
vbus_current_limit:
name: ILIM
on_value:
- lambda: 'ESP_LOGI("st", "SENS ILIM=%.4f", x);'
binary_sensor:
- platform: npm1300
vbus_present:
name: VBUS Present
trigger_on_initial_state: true
on_state:
- lambda: 'ESP_LOGI("st", "BIN vbus_present=%s", x ? "ON" : "OFF");'
vbus_current_limit_active:
name: ILIM Active
trigger_on_initial_state: true
on_state:
- lambda: 'ESP_LOGI("st", "BIN vbus_current_limit_active=%s", x ? "ON" : "OFF");'
charging:
name: Charging
trigger_on_initial_state: true
on_state:
- lambda: 'ESP_LOGI("st", "BIN charging=%s", x ? "ON" : "OFF");'
charge_complete:
name: Charge Complete
trigger_on_initial_state: true
on_state:
- lambda: 'ESP_LOGI("st", "BIN charge_complete=%s", x ? "ON" : "OFF");'
battery_detected:
name: Battery Detected
trigger_on_initial_state: true
on_state:
- lambda: 'ESP_LOGI("st", "BIN battery_detected=%s", x ? "ON" : "OFF");'
charger_error:
name: Charger Error
trigger_on_initial_state: true
on_state:
- lambda: 'ESP_LOGI("st", "BIN charger_error=%s", x ? "ON" : "OFF");'
text_sensor:
- platform: npm1300
charger_status:
name: Charger Status
on_value:
- lambda: |-
id(txt_count) += 1;
ESP_LOGI("st", "TXT #%d charger_status='%s'", id(txt_count), x.c_str());
switch:
- platform: npm1300
charger:
id: sw_charger
name: Charger
restore_mode: DISABLED
on_state:
- lambda: 'ESP_LOGI("st", "SW charger=%s", x ? "ON" : "OFF");'
buck1:
id: sw_buck1
name: BUCK1
restore_mode: DISABLED
on_state:
- lambda: 'ESP_LOGI("st", "SW buck1=%s", x ? "ON" : "OFF");'
buck2:
id: sw_buck2
name: BUCK2
restore_mode: DISABLED
on_state:
- lambda: 'ESP_LOGI("st", "SW buck2=%s", x ? "ON" : "OFF");'
ldo1:
id: sw_ldo1
name: LDO1
restore_mode: DISABLED
on_state:
- lambda: 'ESP_LOGI("st", "SW ldo1=%s", x ? "ON" : "OFF");'
ldo2:
id: sw_ldo2
name: LDO2
restore_mode: DISABLED
on_state:
- lambda: 'ESP_LOGI("st", "SW ldo2=%s", x ? "ON" : "OFF");'
script:
- id: swdump
then:
- lambda: |-
ESP_LOGI("st", "SWSTATE charger=%d buck1=%d buck2=%d ldo1=%d ldo2=%d txt_count=%d", id(sw_charger).state,
id(sw_buck1).state, id(sw_buck2).state, id(sw_ldo1).state, id(sw_ldo2).state, id(txt_count));
- id: toggles
then:
- logger.log: "STEP charger off"
- switch.turn_off: sw_charger
- delay: 1s
- script.execute: regdump
- component.update: pmic
- delay: 1s
- script.execute: swdump
- logger.log: "STEP charger on"
- switch.turn_on: sw_charger
- delay: 1s
- script.execute: regdump
- component.update: pmic
- delay: 1s
- script.execute: swdump
- logger.log: "STEP ldo1 off"
- switch.turn_off: sw_ldo1
- delay: 1s
- script.execute: regdump
- component.update: pmic
- delay: 1s
- script.execute: swdump
- logger.log: "STEP ldo1 on"
- switch.turn_on: sw_ldo1
- delay: 1s
- script.execute: regdump
- component.update: pmic
- delay: 1s
- script.execute: swdump
- logger.log: "STEP done"
interval:
- interval: 60s
then:
- script.execute: regdump
- script.execute: swdump
@@ -1,18 +0,0 @@
esphome:
name: npmhead
on_boot:
- priority: -100
then:
- delay: 8s
- script.execute: regdump
- script.execute: swdump
- delay: 2s
- script.execute: toggles
nrf52:
board: xiao_nrf54lm20a
logger:
level: DEBUG
hardware_uart: UART0
packages:
regdump: !include regdump.yaml
common: !include npmcommon.yaml
@@ -1,38 +0,0 @@
# XIAO nRF54LM20A probe build: the hub with no regulator or charger settings, a bus scan and a register dump every
# 20 s, to see the power-on state before writing anything. Name set with -s name.
esphome:
name: ${name}
on_boot:
- priority: -100
then:
- delay: 3s
- script.execute: regdump
nrf52:
board: xiao_nrf54lm20a
logger:
level: DEBUG
hardware_uart: UART0
packages:
regdump: !include regdump.yaml
i2c:
- id: pmic_bus
sda: P1.18
scl: P1.17
scan: true
npm1300:
id: pmic
i2c_id: pmic_bus
sensor:
- platform: npm1300
system_voltage:
name: VSYS
vbus_voltage:
name: VBUS
battery_voltage:
name: VBAT
die_temperature:
name: Die
interval:
- interval: 20s
then:
- script.execute: regdump
@@ -1,16 +0,0 @@
# Register dump of the nPM1300 with id(pmic).read_register16; "!" marks a failed read.
script:
- id: regdump
then:
- lambda: |-
static const uint16_t REGS[] = {0x0201, 0x0202, 0x0207, 0x0304, 0x0308, 0x0309, 0x030C, 0x0334, 0x0336,
0x0408, 0x040A, 0x040F, 0x0410, 0x0411, 0x0434, 0x0804, 0x0807, 0x0808,
0x0809, 0x080C, 0x080D, 0x050A};
char buf[400];
size_t pos = 0;
for (uint16_t r : REGS) {
uint8_t v = 0;
auto err = id(pmic).read_register16(r, &v, 1);
pos += snprintf(buf + pos, sizeof(buf) - pos, " %04X=%s%02X", r, err == i2c::ERROR_OK ? "" : "!", v);
}
ESP_LOGI("regs", "REGS%s", buf);
@@ -1,28 +0,0 @@
#!/bin/bash
# runone.sh NAME CONFIG PORT [SECS]: flash CONFIG as NAME with `esphome run --no-logs` (pyOCD through the XIAO's
# CMSIS-DAP probe) from TREE while a serial capture of SECS (default 240) stays open on the probe's PORT. The first
# seconds of the capture are the old firmware; cut at "Log initialized". A failed compile, flash or timeout, or no
# "compiled on" line with this build's time in the capture, exits 1. env: TREE, PY, PIO_CORE
D=$(cd "$(dirname "$0")" && pwd); S=$(dirname "$D"); N=${1:?name}; C=${2:?config}; P=${3:?port}; SECS=${4:-240}
T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}
export PLATFORMIO_CORE_DIR=${PIO_CORE:-$D/pio} PYTHONPATH=$T PYTHONUNBUFFERED=1
$PY "$S/serial_capture.py" "$P" "$SECS" "$D/$N-cap.txt" > /dev/null 2> "$D/$N-cap.err" &
CAP=$!
sleep 2
if ! (cd "$T" && timeout 300 $PY -m esphome -s name "$N" run --no-logs "$D/$C" --device "$P") > "$D/$N-run.log" 2>&1
then
# The capture holds the old firmware only; stop it so it is not read as a run of the new build.
tail -1 "$D/$N-run.log"; kill $CAP 2>/dev/null; wait $CAP 2>/dev/null
echo "FAIL: $N run failed (see $D/$N-run.log)"; exit 1
fi
tail -1 "$D/$N-run.log"
# A capture that ended during the flash holds only the old firmware
kill -0 $CAP 2>/dev/null || { echo "FAIL: the capture ended before the flash finished (see $D/$N-cap.err; if empty, raise SECS)"; exit 1; }
wait $CAP
# a flash that returned 0 but never booted the new image leaves only the old firmware in the capture, so look for
# this build's own compile time, which every boot logs
BI=$D/.esphome/build/$N/src/esphome/core/build_info_data.cpp
BT=$(sed -n 's/.*ESPHOME_BUILD_TIME_STR\[\][^"]*"\(.*\)";.*/\1/p' "$BI" 2>/dev/null | head -1)
[ -n "$BT" ] || { echo "FAIL: no build time in $BI"; exit 1; }
grep -a -q -F "compiled on $BT" "$D/$N-cap.txt" ||
{ echo "FAIL: no boot of the build from $BT in $D/$N-cap.txt"; exit 1; }
@@ -1,27 +0,0 @@
#!/bin/bash
# pio_build.sh compile|upload NAME YAML [DEVICE] [esphome options...]: esphome compile or upload of YAML with
# `-s name NAME`, built from TREE with a private PlatformIO core directory. Logs to <yaml dir>/NAME-<action>.log and
# prints the RAM and Flash lines (compile) or the upload result. Exits 1 on a failure or when esphome would not import
# from TREE. A config that sets `name: ${name}` builds one copy per NAME, so a PR and a dev build of the same file
# never share a build directory.
# env: TREE (checkout under test), PY (default $TREE/venv/bin/python), PIO_CORE (default <yaml dir>/pio),
# BUILD_LOCK (optional command prefix that serialises builds on a shared machine; compile only)
A=${1:?compile|upload}; N=${2:?name}; Y=${3:?yaml}; shift 3
T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}
Y=$(cd "$(dirname "$Y")" && pwd)/$(basename "$Y"); D=$(dirname "$Y")
export PLATFORMIO_CORE_DIR=${PIO_CORE:-$D/pio} PYTHONPATH=$T PYTHONUNBUFFERED=1
L=$D/$N-$A.log
F=$(cd "$T" && $PY -c 'import esphome, os; print(os.path.dirname(esphome.__file__))')
[ "$F" = "$(cd "$T" && pwd)/esphome" ] || { echo "esphome imports from $F, not $T"; exit 1; }
echo "esphome from $F" > "$L"
case $A in
compile)
(cd "$T" && ${BUILD_LOCK:-} timeout 1500 $PY -m esphome -s name "$N" "$@" compile "$Y") >> "$L" 2>&1
RC=$?; grep -a -E "^(RAM|Flash):" "$L"; [ $RC = 0 ] || { echo "$N compile failed (see $L)"; exit 1; } ;;
upload)
DEV=${1:?device}; shift
(cd "$T" && timeout 600 $PY -m esphome -s name "$N" "$@" upload "$Y" --device "$DEV") >> "$L" 2>&1 ||
{ echo "$N upload failed (see $L)"; tail -3 "$L"; exit 1; }
grep -a -E "OTA successful|Successfully uploaded" "$L" | tail -1 ;;
*) echo "unknown action $A"; exit 1 ;;
esac
@@ -1,16 +1,8 @@
# Shared by pa.yaml and pc.yaml: Pico 2 W, pioscope.hpp, PIO1 memory cleared at boot, an ALIVE line every 2 s and
# the s_ws_p0 strip on pin 2.
# Shared by pa.yaml and pc.yaml: Pico 2 W, pioscope.hpp, an ALIVE line every 2 s and the s_ws_p0 strip on pin 2.
esphome:
name: ${name}
includes:
- pioscope.hpp
on_boot:
# PIO instruction memory survives a reflash; clear PIO1 so a program left by the previous firmware cannot hide a
# missing pio_add_program
- priority: 1000
then:
- lambda: |-
for (int i = 0; i < 32; i++) pio1->instr_mem[i] = 0;
rp2040:
board: rpipico2w
@@ -1,10 +0,0 @@
#!/bin/bash
# resolve.sh NAME [TRIES]: print the address of NAME.local once it resolves and answers a ping, retrying every 3 s
# (default 30 tries). Exits 1 when it never does.
for _ in $(seq 1 "${2:-30}"); do
IP=$(python3 -c 'import socket, sys; print(socket.gethostbyname(sys.argv[1]))' "$1.local" 2>/dev/null) &&
ping -c 1 "$IP" > /dev/null 2>&1 && { echo "$IP"; exit 0; }
sleep 3
done
echo "$1.local did not resolve or answer" >&2
exit 1
@@ -1,19 +0,0 @@
# RP2 scheduler lock under IRQ and lwIP load (#22688)
On RP2, lwIP callbacks and pico-sdk timers can call into the scheduler from IRQ context while the main loop is inside
it. `components/irq_sched_stress/` reproduces that on purpose: a 300 us pico-sdk repeating timer calls `defer()` and
`set_timeout()` while the main loop does the same. Judge it by counts: every defer runs, and exactly 10 of 400 named
timeouts on 10 shared names run. RP2 is `ESPHOME_THREAD_SINGLE`, so `defer()` order is not FIFO on any build; the
out of order count is informational. Keep `esphome: debug_scheduler:` off, it logs from the IRQ.
- `stress.yaml`: the component, `run_test`, `run_defer` and `run_cancel` API actions, REST entities for the churn
loops and a 16 ms interval that logs its gaps. `race.yaml` ports the removed item race integration fixture.
`picow.yaml` and `evb.yaml` add them to the `../rp2_web_ble/` role configs (encrypted API, web_server, diagnostics);
put `secrets.yaml` here or next to the role configs.
- `flow.sh NAME CONFIG HOST [SERIAL_PORT]`: upload, then the actions, connstress, REST churn and both together; ends
with PASS or FAIL. `svcrun.py HOST ACTION DONE_REGEX TIMEOUT` runs one action and prints its result lines.
- `restchurn.sh HOST SECS OUT`: 4 parallel REST POST loops. `looptime.sh NAME HOST SECS`: 16 ms interval gaps and
50 ms re-arms with the API and page loads running, to compare the cost of the lock between builds.
Build both heads with `../pio_build.sh` under different names. Dev before #22688 failed the defer count on the Pico W;
the PR passed every action.
@@ -1,20 +0,0 @@
"""Test only: a pico-sdk repeating timer calls defer() and set_timeout() from IRQ context while the main loop
does the same, like the host scheduler fixtures do from std::thread workers (RP2040/RP2350 only)."""
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import CONF_ID
from esphome.types import ConfigType
DOMAIN = "irq_sched_stress"
irq_sched_stress_ns = cg.esphome_ns.namespace("irq_sched_stress")
IrqSchedStress = irq_sched_stress_ns.class_("IrqSchedStress", cg.Component)
CONFIG_SCHEMA = cv.Schema({cv.GenerateID(): cv.declare_id(IrqSchedStress)}).extend(
cv.COMPONENT_SCHEMA
)
async def to_code(config: ConfigType) -> None:
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
@@ -1,124 +0,0 @@
#pragma once
// Test only. run_defer(): N defer() calls from a 300 us repeating timer IRQ plus N from the main loop; every one must
// run. run_cancel(): NC set_timeout() calls on 10 shared names from each side inside one 150 ms window; exactly 10
// must run, the rest are implicit cancellations. Results are logged as "DEFER RESULT" and "CANCEL RESULT".
// Keep esphome: debug_scheduler off, it logs from the IRQ.
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
#include <pico/time.h>
namespace esphome::irq_sched_stress {
class IrqSchedStress : public Component {
public:
void loop() override {
if (this->mode_ == IDLE || this->finishing_)
return;
// Issue the main loop share in one tight burst while the IRQ issues its share, so every operation lands inside
// the 150 ms timeout window and the IRQ interleaves with the main loop inside the scheduler.
// The time limit keeps a stalled timer IRQ from wedging the main loop; the result then reports the shortfall.
uint32_t lim = this->mode_ == DEFER ? N : NC;
while ((this->main_issued_ < lim || this->irq_issued_ < lim) && millis() - this->start_ms_ < ISSUE_LIMIT_MS) {
if (this->main_issued_ < lim)
this->step_(false);
delayMicroseconds(60);
}
cancel_repeating_timer(&this->timer_);
this->issue_ms_ = millis() - this->start_ms_;
this->finishing_ = true;
this->set_timeout(1000, [this]() { this->finish_(); });
}
void run_defer() { this->start_(DEFER); }
void run_cancel() { this->start_(CANCEL); }
protected:
enum Mode : uint8_t { IDLE, DEFER, CANCEL };
static constexpr uint32_t N = 500; // per source, defer mode
static constexpr uint32_t NC = 200; // per source, cancel mode
static constexpr uint32_t ISSUE_LIMIT_MS = 2000;
static constexpr const char *NAMES[10] = {"shared_0", "shared_1", "shared_2", "shared_3", "shared_4",
"shared_5", "shared_6", "shared_7", "shared_8", "shared_9"};
static bool irq_tick_(repeating_timer_t *t) {
static_cast<IrqSchedStress *>(t->user_data)->step_(true);
return true;
}
void start_(Mode mode) {
if (this->mode_ != IDLE) {
// a request during a running test is dropped; say so instead of leaving the caller to time out
ESP_LOGW("irq_sched_stress", "%s RESULT FAIL busy", mode == DEFER ? "DEFER" : "CANCEL");
return;
}
this->irq_issued_ = this->main_issued_ = this->irq_exec_ = this->main_exec_ = 0;
this->fifo_viol_ = this->cancel_exec_ = 0;
this->irq_last_ = this->main_last_ = -1;
this->finishing_ = false;
this->start_ms_ = millis();
ESP_LOGI("irq_sched_stress", "%s test start", mode == DEFER ? "defer" : "cancel");
this->mode_ = mode;
if (!add_repeating_timer_us(-300, &IrqSchedStress::irq_tick_, this, &this->timer_)) {
this->mode_ = IDLE;
ESP_LOGE("irq_sched_stress", "%s RESULT FAIL timer not started", mode == DEFER ? "DEFER" : "CANCEL");
}
}
// One operation from the IRQ (irq true) or the main loop.
void step_(bool irq) {
volatile uint32_t &issued = irq ? this->irq_issued_ : this->main_issued_;
if (this->mode_ == DEFER && issued < N) {
int32_t id = issued;
issued = issued + 1;
if (irq) {
this->defer([this, id]() { this->ran_(this->irq_last_, this->irq_exec_, id); });
} else {
this->defer([this, id]() { this->ran_(this->main_last_, this->main_exec_, id); });
}
} else if (this->mode_ == CANCEL && issued < NC) {
uint32_t i = issued;
issued = issued + 1;
this->set_timeout(NAMES[i % 10], 150, [this]() { this->cancel_exec_ = this->cancel_exec_ + 1; });
}
}
void ran_(volatile int32_t &last, volatile uint32_t &exec, int32_t id) {
if (id != last + 1)
this->fifo_viol_ = this->fifo_viol_ + 1;
last = id;
exec = exec + 1;
}
void finish_() {
unsigned total = this->irq_issued_ + this->main_issued_;
if (this->mode_ == DEFER) {
bool ok = this->irq_exec_ == N && this->main_exec_ == N;
ESP_LOGI("irq_sched_stress", "DEFER RESULT %s irq_exec=%u/%u main_exec=%u/%u out_of_order=%u issued_in=%u ms",
ok ? "PASS" : "FAIL", (unsigned) this->irq_exec_, (unsigned) N, (unsigned) this->main_exec_,
(unsigned) N, (unsigned) this->fifo_viol_, (unsigned) this->issue_ms_);
} else {
// Without every set_timeout() issued from both sides the race never ran; 10 executions alone prove nothing.
bool ok = this->cancel_exec_ == 10 && this->irq_issued_ == NC && this->main_issued_ == NC;
ESP_LOGI("irq_sched_stress", "CANCEL RESULT %s scheduled=%u executed=%u (expect 10) issued_in=%u ms",
ok ? "PASS" : "FAIL", total, (unsigned) this->cancel_exec_, (unsigned) this->issue_ms_);
}
this->mode_ = IDLE;
}
repeating_timer_t timer_{};
volatile Mode mode_{IDLE};
volatile uint32_t irq_issued_{0};
volatile uint32_t main_issued_{0};
volatile uint32_t irq_exec_{0};
volatile uint32_t main_exec_{0};
volatile int32_t irq_last_{-1};
volatile int32_t main_last_{-1};
volatile uint32_t fifo_viol_{0};
volatile uint32_t cancel_exec_{0};
uint32_t start_ms_{0};
uint32_t issue_ms_{0};
bool finishing_{false};
};
} // namespace esphome::irq_sched_stress
@@ -1,5 +0,0 @@
# W5100S-EVB-Pico on wired Ethernet with the scheduler lock packages (name set with -s name).
packages:
board: !include ../rp2_web_ble/evb.yaml
stress: !include stress.yaml
race: !include race.yaml
@@ -1,65 +0,0 @@
#!/bin/zsh
# flow.sh NAME CONFIG HOST [SERIAL_PORT]: the RP2 scheduler lock flow (#22688). Uploads CONFIG (picow.yaml or evb.yaml)
# as NAME to DEVICE (default HOST, an OTA), captures SERIAL_PORT for the whole run when given, polls the Fast counter,
# then runs the removed item race, IRQ defer and IRQ cancel actions, connstress 500x4 and 500x2, 90 s of REST churn,
# REST churn and connstress together, and the IRQ actions again. PASS needs every action to pass, connstress 500x2
# without a failure, at least half of each REST churn answered 200, at least 90% of the counter polls answered, no
# reboot (counter reset) and, with SERIAL_PORT, no crash or assert line and a capture that lasted the run; exits 1
# otherwise. connstress at 4 is diagnostic: the API has 3 sockets on these builds, so 4 at a time always shows some
# "dropped after hello" failures.
# env: TREE, PY, DEVICE, API_KEY (unset for a plaintext API)
D=${0:A:h}; N=$1; C=$2; H=$3; SP=$4; S=$D/..; cd $D
T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}; L=$D/$N-flow.txt; : > $L
FAILS=0; fail() { echo "FAIL: $*" | tee -a $L; FAILS=$((FAILS + 1)); }
log() { echo "$*" | tee -a $L; }
# restchurn.sh prints "REST 200:n 404:m ..."; fail when fewer than half of the POSTs answered 200.
restok() {
local ok all
read ok all < <(echo "$2" | tr ' ' '\n' | awk -F: 'NF == 2 {a += $2; if ($1 == 200) o = $2} END {print o+0, a+0}')
[ "$all" -gt 0 ] && [ $((ok * 2)) -ge "$all" ] || fail "$1: $ok of $all POSTs answered 200"; }
heap() { curl -s -m 4 "http://$H/sensor/Heap%20free" | grep -o '"value":[0-9]*' | cut -d: -f2; }
# Portable TCP check of the API port (nc -G is macOS only): apiopen TIMEOUT_S
apiopen() { $PY -c 'import socket, sys; socket.create_connection((sys.argv[1], 6053), float(sys.argv[2])).close()' $H $1 2>/dev/null; }
up() { for _ in $(seq 1 60); do apiopen 1 && return 0; sleep 2; done; return 1; }
$S/pio_build.sh upload $N $D/$C ${DEVICE:-$H} || exit 1
up || { echo "FAIL: API port never opened"; exit 1; }; sleep 8
if [ -n "$SP" ]; then $PY $S/serial_capture.py $SP 3600 $D/$N-serial.log 2> $D/$N-cap.err & CAP=$!; sleep 3; fi
( while true; do echo "$(date +%s) $(curl -s -m 3 "http://$H/sensor/Fast%20counter" | grep -o '"value":[0-9]*')"; sleep 2; done ) > $D/$N-ctr.txt 2>&1 &
CTR=$!; trap 'kill $CTR $CAP 2>/dev/null' EXIT
actions() {
for a in "run_test:Test Complete:20" "run_defer:DEFER RESULT:30" "run_cancel:CANCEL RESULT:30"; do
IFS=: read s pat t <<< "$a"; [ "$1" = again ] && [ $s = run_test ] && continue
out=$($PY -I $D/svcrun.py $H $s "$pat" $t 2>&1) || fail "$s ($1)"; log "$out"; sleep 2
done
}
log "heap at start: $(heap)"
actions first
$PY -I $S/api/connstress.py $H 500 4 > $D/$N-cs4.txt 2>&1; log "connstress 500x4: $(grep -a -E '^Success|^RESULT' $D/$N-cs4.txt | tr '\n' ' ')"
sleep 5
$PY -I $S/api/connstress.py $H 500 2 > $D/$N-cs2.txt 2>&1 || fail "connstress 500x2"
log "connstress 500x2: $(grep -a -E '^Success|^RESULT' $D/$N-cs2.txt | tr '\n' ' ')"
sleep 5; R=$($D/restchurn.sh $H 90 $D/$N-rest.txt); log "REST churn 90 s: $R"; restok "REST churn 90 s" "$R"
sleep 5; log "heap after REST churn: $(heap)"
$D/restchurn.sh $H 120 $D/$N-rest2.txt > $D/$N-rest2.sum & RP=$!
$PY -I $S/api/connstress.py $H 500 4 > $D/$N-csrest.txt 2>&1
log "connstress 500x4 during REST churn: $(grep -a -E '^Success|^RESULT' $D/$N-csrest.txt | tr '\n' ' ')"
wait $RP; R=$(cat $D/$N-rest2.sum); log "REST during connstress: $R"; restok "REST during connstress" "$R"
sleep 5; log "heap at end: $(heap)"
actions again
[ -n "$SP" ] && { kill -0 $CAP 2>/dev/null || fail "the capture ended before the run did (see $D/$N-cap.err)"; }
kill $CTR $CAP 2>/dev/null; wait $CAP 2>/dev/null; trap - EXIT
RESETS=$(grep -o 'value":[0-9]*' $D/$N-ctr.txt | cut -d: -f2 | awk 'NR>1 && $1<p {r++} {p=$1} END {print r+0}')
POLLS=$(wc -l < $D/$N-ctr.txt | tr -d ' '); BADPOLLS=$(grep -vc value $D/$N-ctr.txt)
log "counter resets (reboots): $RESETS, failed counter polls: $BADPOLLS of $POLLS"
[ "$RESETS" = 0 ] || fail "$RESETS reboots"
# A wedged web_server or a board that is down answers no polls, which would otherwise read as no reboot.
[ "$POLLS" -gt 0 ] && [ $((BADPOLLS * 10)) -le "$POLLS" ] || fail "$BADPOLLS of $POLLS counter polls failed"
if [ -n "$SP" ]; then
CRASH=$(grep -a -c -i -E 'CRASH|panic|HardFault|assert' $D/$N-serial.log)
log "serial: crash lines $CRASH, boots $(grep -a -c 'Log initialized' $D/$N-serial.log)"
# a live capture that read nothing would pass the crash check without proving anything
[ "$(grep -a -c -v '^\[[0-9:.]*\]\[capture\]' $D/$N-serial.log)" -gt 0 ] || fail "no firmware lines in $D/$N-serial.log"
[ "$CRASH" = 0 ] || fail "$CRASH crash or assert lines"
fi
[ $FAILS = 0 ] || exit 1
log PASS
@@ -1,22 +0,0 @@
#!/bin/zsh
# looptime.sh NAME HOST SECS: the API connected (logs and states) plus a page load every 2 s for SECS, then a summary of
# the 16 ms interval gap lines from stress.yaml (average, worst) and the 50 ms re-arms per 5 s. Diagnostic only;
# compare two builds. Exits 1 when apilog.py fails, fewer than 2 windows were logged or most page loads did not
# return 200, so a broken or unloaded run is not read as a comparison.
# env: TREE or PY, API_KEY (unset for a plaintext API)
D=${0:A:h}; N=$1; H=$2; S=$3; PY=${PY:-${TREE:?set TREE or PY}/venv/bin/python}; cd $D
# apilog.py appends, so start from an empty log or an earlier run's windows count for this one
: > $D/$N-lt-api.log
$PY -I ../rp2_web_ble/apilog.py $H $S $D/$N-lt-api.log > /dev/null & AP=$!
( end=$(( $(date +%s) + S ))
while (( $(date +%s) < end )); do curl -s -o /dev/null -m 5 -w '%{http_code}\n' http://$H/; sleep 2; done
) > $N-lt-web.txt & PP=$!
wait $AP; RC=$?; kill $PP 2>/dev/null
[ $RC = 0 ] || { echo "$N: apilog.py failed ($RC), see $N-lt-api.log"; exit 1; }
WOK=$(grep -c '^200$' $N-lt-web.txt); WALL=$(wc -l < $N-lt-web.txt | tr -d ' ')
[ "$WALL" -gt 0 ] && [ $((WOK * 2)) -ge "$WALL" ] ||
{ echo "$N: NOT LOADED, $WOK of $WALL page loads returned 200"; exit 1; }
grep -a -o "n=[0-9]* avg_gap_us=[0-9]* max_gap_us=[0-9]* btn=[0-9]* rearms=[0-9]*" $N-lt-api.log | tail -n +2 > $N-lt.txt
awk -v n=$N '{split($2,b,"="); split($3,c,"="); split($5,d,"="); k++; sa+=b[2]; if (c[2]>mx) mx=c[2]; sm+=c[2]; if (k>1) rr+=d[2]-pr; pr=d[2]}
END {if (k < 2) {print n ": fewer than 2 windows"; exit 1}
printf "%s: %d windows of 5 s, 16 ms interval avg gap %.0f us, mean window max %.0f us, worst %d us, re-arms per 5 s %.1f\n", n, k, sa/k, sm/k, mx, rr/(k-1)}' $N-lt.txt
@@ -1,10 +0,0 @@
# Pico W on the station network with the scheduler lock packages (name set with -s name).
rp2:
board: rpipicow
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
packages:
common: !include ../rp2_web_ble/rp-common.yaml
stress: !include stress.yaml
race: !include race.yaml
@@ -1,40 +0,0 @@
# The removed item race from tests/integration/fixtures/scheduler_removed_item_race.yaml, run on the board through
# the run_test action: cancelled timeouts behind a live one at the front of the heap must never run.
globals:
- id: removed_item_executed
type: int
initial_value: '0'
- id: normal_item_executed
type: int
initial_value: '0'
sensor:
- platform: template
id: race_sensor
update_interval: never
lambda: return 0.0;
script:
- id: run_test_script
then:
- lambda: |-
id(removed_item_executed) = 0;
id(normal_item_executed) = 0;
auto *c = id(race_sensor);
auto normal = []() { id(normal_item_executed)++; };
auto removed = []() { id(removed_item_executed)++; };
App.scheduler.set_timeout(c, "blocker", 1, normal);
App.scheduler.set_timeout(c, "cancel_1", 1, removed);
App.scheduler.set_timeout(c, "cancel_2", 1, removed);
App.scheduler.set_timeout(c, "cancel_3", 1, removed);
App.scheduler.set_timeout(c, "normal_1", 1, normal);
App.scheduler.set_timeout(c, "normal_2", 1, normal);
App.scheduler.set_timeout(c, "normal_3", 1, normal);
App.scheduler.process_to_add();
App.scheduler.cancel_timeout(c, "cancel_1");
App.scheduler.cancel_timeout(c, "cancel_2");
App.scheduler.cancel_timeout(c, "cancel_3");
- delay: 20ms
- lambda: |-
bool ok = id(removed_item_executed) == 0 && id(normal_item_executed) == 4;
ESP_LOGI("test", "%s: normal %d (expect 4), removed %d (expect 0)", ok ? "TEST PASSED" : "TEST FAILED",
id(normal_item_executed), id(removed_item_executed));
ESP_LOGI("test", "=== Test Complete ===");
@@ -1,10 +0,0 @@
#!/bin/zsh
# restchurn.sh HOST SECS OUT: 4 parallel loops of REST POSTs (Sw toggle, Lt on with a brightness, Num set, Btn press
# from stress.yaml) for SECS; writes "time code" lines to OUT and prints the count per HTTP code.
H=$1; S=$2; O=$3; : > $O; : > $O.1; : > $O.2; : > $O.3; : > $O.4; end=$(( $(date +%s) + S ))
# $1 is expanded per request outside the command substitution, so each $RANDOM in it is a new value
loop() { while (( $(date +%s) < end )); do u=${(e)1}; echo "$(date +%s) $(curl -s -o /dev/null -m 3 -w '%{http_code}' -X POST "http://$H$u")"; done >> $O.$2; }
loop '/switch/Sw/toggle' 1 & loop '/light/Lt/turn_on?brightness=$((RANDOM % 255))' 2 &
loop '/number/Num/set?value=$((RANDOM % 100))' 3 & loop '/button/Btn/press' 4 & wait
cat $O.1 $O.2 $O.3 $O.4 | sort -n > $O; rm -f $O.1 $O.2 $O.3 $O.4
echo "REST $(awk '{c[$2]++} END {for (k in c) printf "%s:%d ", k, c[k]}' $O)"
@@ -1,91 +0,0 @@
# RP2 scheduler lock check (#22688): the IRQ stress component with its API actions, REST entities for the churn
# loops (Sw, Lt, Num, Btn), a 50 ms self re-arming script and a 16 ms interval that logs its gaps every 5 s as
# "n=... avg_gap_us=... max_gap_us=... btn=... rearms=..." (read by looptime.sh).
external_components:
- source:
type: local
path: components
components: [irq_sched_stress]
irq_sched_stress:
id: irqss
api:
actions:
- action: run_test
then:
- script.execute: run_test_script
- action: run_defer
then:
- lambda: id(irqss)->run_defer();
- action: run_cancel
then:
- lambda: id(irqss)->run_cancel();
switch:
- platform: template
name: Sw
optimistic: true
output:
- platform: template
id: lt_out
type: float
write_action:
- lambda: id(lt_level) = state;
light:
- platform: monochromatic
name: Lt
output: lt_out
default_transition_length: 0s
number:
- platform: template
name: Num
optimistic: true
min_value: 0
max_value: 100
step: 1
globals:
- id: lt_level
type: float
initial_value: '0'
- id: btn_presses
type: uint32_t
initial_value: '0'
- id: rearms
type: uint32_t
initial_value: '0'
button:
- platform: template
name: Btn
on_press:
- lambda: id(btn_presses)++;
script:
- id: rearm
mode: restart
then:
- delay: 50ms
- lambda: id(rearms)++;
- script.execute: rearm
esphome:
on_boot:
- script.execute: rearm
interval:
- interval: 16ms
then:
- lambda: |-
static uint32_t last = 0, n = 0, sum = 0, mx = 0, t0 = 0;
uint32_t now = micros();
if (last != 0) {
uint32_t g = now - last;
n++;
sum += g;
if (g > mx)
mx = g;
}
last = now;
if (t0 == 0)
t0 = now;
if (now - t0 >= 5000000) {
ESP_LOGI("lt", "n=%u avg_gap_us=%u max_gap_us=%u btn=%u rearms=%u level=%.2f", (unsigned) n,
(unsigned) (n ? sum / n : 0), (unsigned) mx, (unsigned) id(btn_presses),
(unsigned) id(rearms), id(lt_level));
n = sum = mx = 0;
t0 = now;
}
@@ -1,59 +0,0 @@
"""svcrun.py HOST ACTION DONE_REGEX TIMEOUT: run a user defined API action, collect the logs until DONE_REGEX matches
or TIMEOUT seconds pass, and print the result lines. env: API_KEY (unset for a plaintext API).
Exits 1 on a timeout, when a result line says FAIL, FAILED or crash, or when no result line says PASS or PASSED."""
import asyncio
import pathlib
import re
import sys
import time
from aioesphomeapi import LogLevel
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from apiconn import connect, log_text # noqa: E402
RESULT = re.compile(
r"RESULT|TEST PASSED|TEST FAILED|Test Complete|crash", re.IGNORECASE
)
async def main(host: str, action: str, done: str, timeout: float) -> int:
cli = await connect(host, tries=30, timeout=15)
lines: list[str] = []
finished = asyncio.Event()
rx = re.compile(done)
def on_log(msg) -> None:
line = log_text(msg)
lines.append(line)
if rx.search(line):
finished.set()
cli.subscribe_logs(on_log, log_level=LogLevel.LOG_LEVEL_DEBUG)
_, services = await cli.list_entities_services()
svc = next((s for s in services if s.name == action), None)
if svc is None:
sys.exit(f"no action {action} on {host}")
await asyncio.sleep(0.5)
t0 = time.monotonic()
await cli.execute_service(svc, {})
try:
await asyncio.wait_for(finished.wait(), timeout)
status = "DONE"
except TimeoutError:
status = "TIMEOUT"
found = [line for line in lines if RESULT.search(line)]
for line in found:
print(" " + line)
print(f"{action}: {status} after {time.monotonic() - t0:.1f} s")
await cli.disconnect()
failed = any(
re.search(r"\bFAIL(ED)?\b|crash", line, re.IGNORECASE) for line in found
)
# a missing PASS line (dropped log, a check that never ran) is not a pass
passed = any(re.search(r"\bPASS(ED)?\b", line) for line in found)
return 1 if status != "DONE" or failed or not passed else 0
sys.exit(asyncio.run(main(sys.argv[1], sys.argv[2], sys.argv[3], float(sys.argv[4]))))
@@ -1,31 +0,0 @@
# RP2040/RP2350 web_server, API and BLE proxy A/B (#22671)
Configs take their name from the command line (`-s name ...` through `../pio_build.sh`), so a PR build and a dev build
of the same file never share a build directory: `picow.yaml` (Pico W with an active bluetooth_proxy), `pico2w.yaml`,
`evb.yaml` (W5100S-EVB-Pico on Ethernet), `picow-ap.yaml` (fallback AP with the AP client count from `appeek.hpp`) and
`client.yaml` (ESP32 that provisions it). `rp-common.yaml` adds the encrypted API, web_server and a restart button to
`templates/diagnostics.yaml`. Put `secrets.yaml` and `apikey.txt` (the `api_key` secret) in this directory; both are
git-ignored.
The runners read `TREE` and `PY` from the environment, plus `PICO_SN` (the Pico's USB serial number), `PEER_MAC` (the
`ble_notify/server.yaml` GATT server) and `CLIENT_PORT`/`CLIENT_TREE` where noted. `staflow.sh`, `bleseq.sh`,
`apflow.sh` and `churn.sh` end with PASS or FAIL and exit 1 on FAIL; `sseabc.sh` and `sserun.sh` are diagnostic and
only print counts.
- `staflow.sh NAME CONFIG BLE`: USB flash, API soak with page loads, 30 s SSE, OTA, restart, short soak, and with
BLE=1 a 180 s GATT hold.
- `bleseq.sh NAME`: 180 s GATT hold through the Pico W proxy (`gatthold.py`), then 4 short reconnects.
- `apflow.sh NAME`: fallback AP on the Pico W, the ESP32 client provisions it, the AP client count is logged.
- `sseabc.sh HOST TAG`: SSE alone, with the API soak, and with page loads (state events per 5 s).
- `sserun.sh HOST TAG SECS MODE N`: N SSE streams with a pcap, a netstat poll, the API log (`apilog.py`) and probes
after each; `pcapsum.py PCAP IP` summarizes the pcap and `stallctr.py PCAP IP APILOG` lines the RPAsyncTCP counters
up with each stall.
- `H=<device ip> churn.sh TAG SECS`: `/events` connect and disconnect churn, reboots from the reported uptime, then
the crash report through `../crash_report/peek.py`.
- `soak.py HOST SECONDS LOG`: states, drops, uptime resets, reset reason, crash and assert lines from the API logs.
- `churnflow.sh NAME CONFIG HOST`: upload, then rounds of `churn.sh` with the heap before, after and settled and a
main loop check; uploads again by OTA when a round left the board in safe mode. PASS or FAIL.
- `leakflow.sh NAME CONFIG HOST`: rounds of 300 `/events` connects that never complete (`neverconn.py HOST N
rst|head`: reset right after the GET, or after reading the first bytes of the head), heap before, after and
settled. PASS when each round completes most GETs (head mode: with an HTTP/1.1 200 status), the board does not
reboot and the settled heap stays near idle.
@@ -1,39 +0,0 @@
#!/bin/zsh
# apflow.sh NAME: Pico W fallback AP (picow-ap.yaml as NAME; use a fresh NAME per build) and an ESP32 client
# (client.yaml) that provisions it through /wifisave. Prints the AP client count changes, the provisioning and crash
# or reboot markers. PASS needs a client on the AP, status 200 for the real save, the DUT on the station network
# with its AP disabled, no crash line and a capture that lasted the run; exits 1 otherwise.
# env: TREE, PY, PICO_SN, CLIENT_PORT, CLIENT_TREE (checkout for the client build)
D=${0:A:h}; N=$1; S=$D/..; T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}
SN=${PICO_SN:?set PICO_SN}; CPORT=${CLIENT_PORT:?set CLIENT_PORT}; CTREE=${CLIENT_TREE:?set CLIENT_TREE}
FAILS=0; fail() { echo "FAIL: $*"; FAILS=$((FAILS + 1)); }
# both builds first, so the DUT capture only has to cover the provisioning
$S/pio_build.sh compile $N $D/picow-ap.yaml || exit 1
TREE=$CTREE $S/pio_build.sh compile $N-client $D/client.yaml || exit 1
PORT=$($PY $S/ports.py --wait 2e8a --serial $SN --timeout 30) || { echo "FAIL: no pico"; exit 1; }
$S/pio_build.sh upload $N $D/picow-ap.yaml $PORT || exit 1
PORT=$($PY $S/ports.py --wait 2e8a --serial $SN --timeout 60) || { echo "FAIL: pico gone after the upload"; exit 1; }
L=$D/$N-serial.log; CL=$D/$N-client.log
$PY $S/serial_capture.py $PORT 600 $L 2> $D/$N-cap.err &
CAP=$!; trap 'kill $CAP $CCAP 2>/dev/null' EXIT
n=0; until grep -a -q "Starting fallback AP\|Captive portal" $L; do sleep 2; n=$((n+2)); [ $n -ge 150 ] && { echo "FAIL: the AP never came up"; exit 1; }; done
echo "AP up after ${n}s"
TREE=$CTREE $S/pio_build.sh upload $N-client $D/client.yaml $CPORT || exit 1
$PY $S/serial_capture.py $CPORT 200 $CL --reset 2> $D/$N-ccap.err &
CCAP=$!
n=0; until grep -a -q "real save status" $CL; do sleep 2; n=$((n+2)); [ $n -ge 180 ] && { echo "FAIL: the client never saved"; exit 1; }; done
echo "client posted after ${n}s; settling 60s"; sleep 60
kill -0 $CAP 2>/dev/null || fail "the DUT capture ended before the run did (see $D/$N-cap.err)"
kill $CAP $CCAP 2>/dev/null; wait 2>/dev/null; trap - EXIT
echo "--- DUT"
grep -a -E "AP clients|Starting fallback AP|Requested WiFi|Connected\$|IP Address|Disabling AP|CRASH|panic|HardFault|Log initialized|port lost" $L | sed -E 's/(IP Address: )[0-9.]+/\1<ip>/' | cut -c1-120 | head -40
echo "--- client"
grep -a -E "connected, ip|save status|posting" $CL | sed -E 's/ip [0-9.]+/ip <ip>/' | head
grep -a -q "AP clients [1-9]" $L || fail "the DUT never counted a client on its AP"
grep -a -q "real save status 200" $CL || fail "the real save did not return 200"
grep -a -q "Disabling AP" $L || fail "the DUT never disabled its AP"
# the fallback AP logs its own 192.168.4.x address too, so only another address shows the station side
grep -a "IP Address" $L | grep -v -q "192\.168\.4\." || fail "the DUT never got a station address"
CRASH=$(grep -a -c -E "CRASH|panic|HardFault" $L); [ "$CRASH" = 0 ] || fail "$CRASH crash lines"
[ $FAILS = 0 ] || exit 1
echo PASS
@@ -1,55 +0,0 @@
"""apilog.py HOST SECONDS OUT: subscribe VERBOSE logs and states for SECONDS with ms timestamps, reconnecting on a drop.
env: API_KEY (unset for a plaintext API). Prints the state and drop counts at the end; exits 1 on a drop or when no
state arrived, so an unexercised API is not read as a working one."""
import asyncio
import contextlib
import pathlib
import sys
import time
from aioesphomeapi import LogLevel
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from apiconn import connect, log_text, stop_event # noqa: E402
def ts() -> str:
return f"{time.time():.3f}"
async def main(host: str, secs: float, outf: str) -> None:
end = time.monotonic() + secs
states = drops = 0
with pathlib.Path(outf).open("a", encoding="utf-8") as out:
def w(line: str) -> None:
out.write(f"{ts()} {line}\n")
out.flush()
def on_state(_s) -> None:
nonlocal states
states += 1
while time.monotonic() < end:
stopped, on_stop = stop_event()
cli = await connect(host, tries=60, timeout=15, on_stop=on_stop)
w(f"API connected {(await cli.device_info()).name}")
cli.subscribe_states(on_state)
cli.subscribe_logs(
lambda m: w(log_text(m)), log_level=LogLevel.LOG_LEVEL_VERBOSE
)
with contextlib.suppress(TimeoutError):
await asyncio.wait_for(stopped.wait(), max(0.0, end - time.monotonic()))
if stopped.is_set():
drops += 1
w("API DROPPED")
with contextlib.suppress(Exception):
await cli.disconnect()
w(f"API done states={states} drops={drops}")
print(f"api states={states} drops={drops}")
if drops or not states:
sys.exit(1)
asyncio.run(main(sys.argv[1], float(sys.argv[2]), sys.argv[3]))
@@ -1,14 +0,0 @@
#pragma once
// Reads the protected WiFiComponent::ap_clients_ for the test: explicit instantiation skips access checks.
#include "esphome/components/wifi/wifi_component.h"
namespace appeek {
struct Tag {
using type = uint8_t esphome::wifi::WiFiComponent::*;
friend type get(Tag);
};
template<typename T, typename T::type M> struct Rob {
friend typename T::type get(T) { return M; }
};
template struct Rob<Tag, &esphome::wifi::WiFiComponent::ap_clients_>;
inline int ap_clients() { return esphome::wifi::global_wifi_component->*get(Tag{}); }
} // namespace appeek
@@ -1,33 +0,0 @@
#!/bin/zsh
# bleseq.sh NAME: 180 s GATT hold through the Pico W proxy NAME (built by staflow.sh), then 4 short holds 10 s apart,
# with the serial log captured. PASS needs every hold to pass, no crash line, boot or port loss and a capture that
# lasted the run.
# env: TREE, PY, PICO_SN, PEER_MAC (the ble_notify server); apikey.txt here
D=${0:A:h}; N=$1; S=$D/..; T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}; H=$(cat $D/$N-host.txt)
FAILS=0; fail() { echo "FAIL: $*"; FAILS=$((FAILS + 1)); }
export API_KEY=$(cat $D/apikey.txt)
PORT=$($PY $S/ports.py --wait 2e8a --serial ${PICO_SN:?set PICO_SN} --timeout 10) || { echo "FAIL: no pico"; exit 1; }
L=$D/$N-bleseq-serial.log
$PY $S/serial_capture.py $PORT 420 $L 2> $D/$N-bleseq-cap.err &
CAP=$!; trap 'kill $CAP 2>/dev/null' EXIT
sleep 2
timeout 300 $PY -I $D/gatthold.py $H ${PEER_MAC:?set PEER_MAC} 180 > $D/$N-hold.txt 2>&1 || fail "the 180 s hold"
grep -v '^uuids' $D/$N-hold.txt
for i in 1 2 3 4; do
sleep 10
timeout 90 $PY -I $D/gatthold.py $H $PEER_MAC 15 > $D/$N-hold$i.txt 2>&1 || fail "short hold $i"
grep -E "PASS|FAIL|held" $D/$N-hold$i.txt | tr '\n' ' '; echo
done
sleep 3
kill -0 $CAP 2>/dev/null || fail "the capture ended before the run did (see $D/$N-bleseq-cap.err)"
[ "$(grep -a -c -v '^\[[0-9:.]*\]\[capture\]' $L)" -gt 0 ] || fail "no firmware lines in $L"
kill $CAP; wait $CAP 2>/dev/null; trap - EXIT
CRASH=$(grep -a -c -i -E 'CRASH|panic|HardFault|assert' $L)
echo "serial: crash/assert $CRASH boots $(grep -a -c 'ESPHome version' $L) notify-response warnings $(grep -a -c 'Failed to send notify' $L) connects $(grep -a -c 'Connecting v3' $L)"
grep -a -E "Disconnected, reason|Connection failed|status" $L | cut -c1-120 | sort | uniq -c | sort -rn | head -5
[ "$CRASH" = 0 ] || fail "$CRASH crash lines"
# the capture opens on a running proxy, so any boot or USB drop is a reboot the next hold's retry would hide
BOOTS=$(grep -a -c 'ESPHome version' $L); LOSSES=$(grep -a -c 'port lost' $L)
[ "$BOOTS" = 0 ] && [ "$LOSSES" = 0 ] || fail "$BOOTS boots and $LOSSES port losses during the holds"
[ $FAILS = 0 ] || exit 1
echo PASS
@@ -1,24 +0,0 @@
#!/bin/zsh
# H=<device ip> churn.sh TAG SECS: 4 parallel loops of short /events connections (0.2 to 1.5 s) for SECS, logging the
# uptime each stream reports; counts reboots from the uptime going backwards, then reads the crash report over the API
# with crash_report/peek.py. PASS needs streams that got data (at least as many as got nothing), no reboot and no
# replayed crash record; exits 1 otherwise. env: H, TREE or PY, API_KEY (unset for a plaintext API)
D=${0:A:h}; T=$1; S=$2; H=${H:?set H to the device address}; PY=${PY:-${TREE:?set TREE or PY}/venv/bin/python}; cd $D
rm -f $T-churn*.txt
end=$(( $(date +%s) + S ))
for k in 1 2 3 4; do
( while (( $(date +%s) < end )); do m=0.$(( RANDOM % 9 + 2 )); [[ $((RANDOM % 3)) == 0 ]] && m=1.5
r=$(curl -s -N --connect-timeout 1 -m $m http://$H/events 2>/dev/null | grep -a -o '"uptime":[0-9]*' | head -1)
echo "$(date +%s) ${r:-none}"; done > $T-churn$k.txt ) &
done; wait
cat $T-churn*.txt | sort -n > $T-churn.txt
FAILS=0; fail() { echo "FAIL: $*"; FAILS=$((FAILS + 1)); }
read -r OK NONE REBOOTS < <(awk '$2 ~ /uptime/ {split($2,a,":"); b=$1-a[2]; if (pb!="" && b-pb>3) n++; pb=b; c++} $2=="none"{x++} END{print c+0, x+0, n+0}' $T-churn.txt)
echo "streams_with_ping=$OK none=$NONE reboots=$REBOOTS"
[ "$OK" -gt 0 ] && [ "$OK" -ge "$NONE" ] || fail "most streams got nothing (the stimulus did not reach the device)"
[ "$REBOOTS" = 0 ] || fail "$REBOOTS reboots"
PEEK=$($PY -I $D/../crash_report/peek.py $H) || fail "reading the crash report"
echo "crash report: $PEEK"
[[ $PEEK == *"replay lines 0"* ]] || fail "a crash record was replayed"
[ $FAILS = 0 ] || exit 1
echo PASS
@@ -1,31 +0,0 @@
#!/bin/zsh
# churnflow.sh NAME CONFIG HOST: upload CONFIG as NAME to DEVICE (default HOST, an OTA), then ROUNDS (default 2) rounds
# of `churn.sh` for 90 s with the free heap before, right after and after a 30 s settle, and a main loop check (the
# Fast counter must advance). A board that fell into safe mode (API port closed) gets NAME again by OTA and the round
# fails. PASS needs every churn.sh round to pass, the loop to keep running and no safe mode; exits 1 otherwise.
# env: TREE, PY, DEVICE, ROUNDS, API_KEY
D=${0:A:h}; N=$1; C=$2; H=$3; S=$D/..; cd $D
T=${TREE:?set TREE}; export PY=${PY:-$T/venv/bin/python}; FAILS=0
val() { curl -s -m 4 "http://$H/sensor/$1" | grep -o '"value":[0-9]*' | cut -d: -f2; }
loopchk() { local a b; a=$(val Fast%20counter); sleep 3; b=$(val Fast%20counter); [[ -n $a && -n $b && $b -gt $a ]]; }
# Portable TCP check of the API port (nc -G is macOS only): apiopen TIMEOUT_S
apiopen() { $PY -c 'import socket, sys; socket.create_connection((sys.argv[1], 6053), float(sys.argv[2])).close()' $H $1 2>/dev/null; }
ready() { for _ in $(seq 1 40); do [ -n "$(val Uptime)" ] && return 0; sleep 3; done; return 1; }
$S/pio_build.sh upload $N $D/$C ${DEVICE:-$H} || exit 1
ready || { echo "FAIL: $N never answered"; exit 1; }
echo "$N idle heap: $(val Heap%20free)"
for r in $(seq 1 ${ROUNDS:-2}); do
sleep 10; hb=$(val Heap%20free)
res=$(H=$H $D/churn.sh $N-churn$r 90 2>&1) || FAILS=$((FAILS + 1))
sleep 5; ha=$(val Heap%20free); sleep 30; hs=$(val Heap%20free)
loopchk && lp="loop ok" || { lp="LOOP STUCK"; FAILS=$((FAILS + 1)); }
echo "$N round $r: $(echo $res | tr '\n' ' ') | heap before $hb, after $ha, settled $hs | $lp"
if ! apiopen 2; then
sleep 15
apiopen 2 || { echo "$N: API port closed after round $r (safe mode?), uploading again"; FAILS=$((FAILS + 1))
$S/pio_build.sh upload $N $D/$C $H && ready || { echo "$N: recovery after round $r failed, stopping"
FAILS=$((FAILS + 1)); break; }; }
fi
done
[ $FAILS = 0 ] || { echo FAIL; exit 1; }
echo PASS
@@ -1,12 +0,0 @@
# Classic ESP32 that joins the Pico W's fallback AP and provisions it once through /wifisave (name set with -s name).
substitutions:
ap_ssid: rp2webap
real_ssid: !secret wifi_ssid
real_psk: !secret wifi_password
bogus_saves: "1"
esp32:
board: pico32
framework:
type: esp-idf
packages:
hwtest: !include ../../templates/client-wifisave.yaml
@@ -1,13 +0,0 @@
# WIZnet W5100S-EVB-Pico on wired Ethernet (name set with -s name).
rp2:
board: wiznet_5100s_evb_pico
ethernet:
type: W5100
clk_pin: 18
mosi_pin: 19
miso_pin: 16
cs_pin: 17
interrupt_pin: 21
reset_pin: 20
packages:
common: !include rp-common.yaml
@@ -1,89 +0,0 @@
"""Through a bluetooth_proxy: connect to the ble_notify GATT server (server.yaml), read both characteristics, enable
notify on both (writing the CCCD like Home Assistant), hold for HOLD seconds re-reading every 3 s, then disconnect.
usage: gatthold.py PROXY PEER_MAC HOLD env: API_KEY, ALLOW_UUID_REMAP=1 (accept the pre-#22679 short UUIDs).
Prints counts; exits 1 on a lost link, a failed read or a short UUID reported in place of the real one."""
import asyncio
import os
import pathlib
import sys
import time
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from apiconn import ble_connect, connect, enable_notify # noqa: E402
NUM = "5ec10001-0000-1000-8000-00805f9b34fb"
TXT = "5ec10002-0000-1000-8000-00805f9b34fb"
async def main(host: str, peer: str, hold: float) -> None:
addr = int(peer.replace(":", ""), 16)
cli = await connect(host)
lost: list[tuple[float, int]] = []
closing = False
def on_lost(err: int) -> None:
if not closing:
lost.append((time.monotonic(), err))
print(f"LINK LOST err={err}", flush=True)
t = time.monotonic()
c, mtu, err, cancel = await ble_connect(cli, addr, on_lost)
if not c:
sys.exit(f"FAIL connect err={err}")
print(f"connected in {time.monotonic() - t:.1f}s mtu={mtu}", flush=True)
svcs = await cli.bluetooth_gatt_get_services(addr)
chars = {ch.uuid.lower(): ch for s in svcs.services for ch in s.characteristics}
print("uuids", sorted(chars), flush=True)
print(f"services {len(svcs.services)} characteristics {len(chars)}", flush=True)
# before #22679 the rp2 proxy reported a 32-bit base UUID as its low 16 bits (5ec10001 -> 00000001)
remapped = 0
for u in (NUM, TXT):
if u not in chars and "0000" + u[4:] in chars:
remapped += 1
print(f"UUID {u[:8]} reported as {'0000' + u[4:8]}", flush=True)
chars[u] = chars["0000" + u[4:]]
got = {NUM: 0, TXT: 0}
reads = fails = empty = 0
samples: list[bytes] = []
for u in (NUM, TXT):
if not await enable_notify(
cli, addr, chars[u], lambda h, d, u=u: got.__setitem__(u, got[u] + 1)
):
sys.exit(f"FAIL: {u[:8]} lists no CCCD")
end = time.monotonic() + hold
while time.monotonic() < end and not lost:
for u in (NUM, TXT):
try:
v = bytes(await cli.bluetooth_gatt_read(addr, chars[u].handle))
reads += 1
empty += not v
if v and len(samples) < 4:
samples.append(v)
except Exception as e: # noqa: BLE001
fails += 1
print(f"read {u[4:8]} FAILED {type(e).__name__}: {e}", flush=True)
# 3 s, so a hold covers several of the server's 10 s empty-value cycles
await asyncio.sleep(3)
print(
f"held {hold:.0f}s: notifications num={got[NUM]} txt={got[TXT]} reads ok={reads} failed={fails} "
f"link losses={len(lost)} empty reads={empty} uuid_remapped={remapped} samples={samples}",
flush=True,
)
closing = True
await cli.bluetooth_device_disconnect(addr)
await asyncio.sleep(2)
cancel()
await cli.disconnect()
# server.yaml empties both values on every 5th 2 s round, so about one read in five is legitimately empty; the
# client cannot tell which round it hit, so only a majority of empty reads counts as a proxy returning no data
if remapped and os.environ.get("ALLOW_UUID_REMAP") != "1":
sys.exit(
f"FAIL: {remapped} UUIDs reported in short form (ALLOW_UUID_REMAP=1 accepts them)"
)
if lost or fails or not got[NUM] or not got[TXT] or empty * 2 > reads:
sys.exit("FAIL")
print("PASS", flush=True)
asyncio.run(main(sys.argv[1], sys.argv[2], float(sys.argv[3])))
@@ -1,25 +0,0 @@
#!/bin/zsh
# leakflow.sh NAME CONFIG HOST: upload CONFIG as NAME to DEVICE (default HOST, an OTA), then 3 rounds of 300 /events
# connects reset right after the GET and 1 round of 300 that read the response head first (neverconn.py), with the
# free heap before, right after and after a 30 s settle. PASS needs every neverconn.py round to pass (MIN_OK of the
# GETs completed), the Uptime to advance by the wall time of each round (no reboot) and every settled heap within
# LEAK_TOL bytes (default 4096) of the idle heap; exits 1 otherwise. env: TREE, PY, DEVICE, LEAK_TOL, MIN_OK
D=${0:A:h}; N=$1; C=$2; H=$3; S=$D/..; cd $D
T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}; TOL=${LEAK_TOL:-4096}; FAILS=0
val() { curl -s -m 4 "http://$H/sensor/$1" | grep -o '"value":[0-9]*' | cut -d: -f2; }
heap() { val Heap%20free; }
$S/pio_build.sh upload $N $D/$C ${DEVICE:-$H} || exit 1
for _ in $(seq 1 40); do curl -s -m 3 -o /dev/null http://$H/ && break; sleep 3; done; sleep 15
IDLE=$(heap); echo "$N idle heap: $IDLE"; [ -n "$IDLE" ] || { echo "FAIL: no Heap free reading"; exit 1; }
for r in rst rst rst head; do
ub=$(val Uptime); t0=$SECONDS; hb=$(heap)
res=$($PY -I $D/neverconn.py $H 300 $r 2>&1) || { echo "FAIL: neverconn.py $r"; FAILS=$((FAILS + 1)); }
sleep 3; ha=$(heap); sleep 30; hs=$(heap); ua=$(val Uptime)
echo "$N $r: ${res//$'\n'/ } | before $hb | after $ha | settled $hs | uptime $ub -> $ua"
# A reboot during the round leaves the uptime short of the wall time that passed.
[ -n "$ub" ] && [ -n "$ua" ] && [ $((ua - ub)) -ge $((SECONDS - t0 - 10)) ] ||
{ echo "FAIL: uptime ${ub:-none} -> ${ua:-none} in $((SECONDS - t0)) s (reboot?)"; FAILS=$((FAILS + 1)); }
[ -n "$hs" ] && [ $((IDLE - hs)) -le $TOL ] || { echo "FAIL: settled heap ${hs:-none} vs idle $IDLE"; FAILS=$((FAILS + 1)); }
done
[ $FAILS = 0 ] || exit 1
echo PASS
@@ -1,67 +0,0 @@
"""neverconn.py HOST N [rst|head]: open N /events connections that never complete the SSE connect.
rst (default) sends the GET and resets at once (SO_LINGER 0), before the response head is ACKed, after one probe
GET confirms /events answers HTTP/1.1 200 (a refused path would make every reset count); head reads the
status line of the response head, then resets. Prints the counts of completed GETs (head: with a 200 status) and of
each failure; exits 1 when fewer than MIN_OK (default 90%) of the N connections completed.
env: MIN_OK (fraction)
"""
from collections import Counter
import os
import socket
import struct
import sys
import time
host, n = sys.argv[1], int(sys.argv[2])
mode = sys.argv[3] if len(sys.argv) > 3 else "rst"
ok = 0
errs: Counter[str] = Counter()
if mode == "rst":
try:
with socket.create_connection((host, 80), timeout=3) as p:
p.sendall(
b"GET /events HTTP/1.1\r\nHost: x\r\nAccept: text/event-stream\r\n\r\n"
)
got = b""
while len(got) < 12 and (d := p.recv(16 - len(got))):
got += d
except OSError as e:
sys.exit(f"FAIL: the /events probe failed: {e}")
if not got.startswith(b"HTTP/1.1 200"):
sys.exit(
f"FAIL: /events answered {got!r}, so the resets would not reach the SSE path"
)
for _ in range(n):
s = socket.socket()
s.settimeout(3)
step = "connect"
try:
s.connect((host, 80))
step = "send"
s.sendall(
b"GET /events HTTP/1.1\r\nHost: x\r\nAccept: text/event-stream\r\n\r\n"
)
if mode == "head":
step = "recv"
got = b""
while len(got) < 12 and (d := s.recv(16 - len(got))):
got += d
if not got:
errs["recv_eof"] += 1
continue
# a refused stream (401, 503) never ran the SSE path under test
if not got.startswith(b"HTTP/1.1 200"):
errs["status"] += 1
continue
s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
ok += 1
except OSError:
errs[step] += 1
finally:
s.close()
time.sleep(0.15)
print(f"completed={ok}/{n} failed={dict(errs)}")
if ok < n * float(os.environ.get("MIN_OK", "0.9")):
sys.exit(f"FAIL: only {ok}/{n} {mode} connections completed")
@@ -1,112 +0,0 @@
"""pcapsum.py PCAP DEVICE_IP: per TCP connection to port 80, device data segments, last data time and seq, retransmits,
FIN/RST and who sent them, windows, and anything sent by the device after its last data. Uses tcpdump -tt text.
Exits 1 when the capture has no TCP packet. packets() is shared with stallctr.py."""
from collections.abc import Iterator
import re
import subprocess
import sys
RX = re.compile(
r"^(\d+\.\d+) IP (\S+)\.(\d+) > (\S+)\.(\d+): Flags \[([^\]]*)\](?:, seq (\d+)(?::(\d+))?)?(?:, ack (\d+))?, win (\d+).*length (\d+)"
)
def packets(pcap: str, dev: str) -> Iterator[dict]:
"""Each TCP packet in PCAP as a dict; port is the host side's port, from_dev tells the direction."""
r = subprocess.run(
["tcpdump", "-n", "-tt", "-S", "-r", pcap],
capture_output=True,
text=True,
check=False,
)
if r.returncode != 0:
sys.exit(f"tcpdump -r {pcap} failed: {r.stderr.strip()}")
skipped = parsed = 0
for line in r.stdout.splitlines():
m = RX.match(line)
if not m:
skipped += " IP " in line and "Flags [" in line
continue
parsed += 1
t, sip, sp, _dip, dp, fl, s1, s2, ack, win, ln = m.groups()
from_dev = sip == dev
yield {
"t": float(t),
"from_dev": from_dev,
"port": dp if from_dev else sp,
"flags": fl,
"seq": (s1, s2),
"ack": int(ack) if ack else None,
"win": int(win),
"len": int(ln),
"line": line,
}
if skipped:
# on stdout, so a summary built from part of the capture says so
print(f"warning: {skipped} TCP lines did not parse", flush=True)
if skipped and not parsed:
sys.exit("no TCP line parsed; the tcpdump output format differs")
def main(pcap: str, dev: str) -> None:
conns: dict[str, dict] = {}
for k in packets(pcap, dev):
t = k["t"]
c = conns.setdefault(
k["port"],
{
"t0": t,
"data": 0,
"bytes": 0,
"last_data": None,
"last_seq": None,
"seen": set(),
"retx": 0,
"fin": [],
"rst": [],
"cwin": [],
"dwin": [],
"after": [],
"last_ack_from_client": None,
"http": None,
},
)
if "GET /" in k["line"] and not k["from_dev"]:
c["http"] = k["line"].split("HTTP: ")[-1][:20]
if k["from_dev"]:
c["dwin"].append(k["win"])
if k["len"] > 0:
if k["seq"] in c["seen"]:
c["retx"] += 1
c["seen"].add(k["seq"])
c["data"] += 1
c["bytes"] += k["len"]
c["last_data"] = t
c["last_seq"] = int(k["seq"][1])
c["after"] = []
else:
c["after"].append((round(t - c["t0"], 3), k["flags"]))
else:
c["cwin"].append(k["win"])
if k["ack"] is not None:
c["last_ack_from_client"] = k["ack"]
who = "dev" if k["from_dev"] else "host"
if "F" in k["flags"]:
c["fin"].append((who, round(t - c["t0"], 3)))
if "R" in k["flags"]:
c["rst"].append((who, round(t - c["t0"], 3)))
if not conns:
sys.exit(f"no TCP packets in {pcap}")
for p, c in conns.items():
ld = round(c["last_data"] - c["t0"], 3) if c["last_data"] else None
print(
f"port {p} {c['http']}: dev data segs={c['data']} bytes={c['bytes']} last_data=+{ld}s "
f"last_dev_seq_end={c['last_seq']} host_last_ack={c['last_ack_from_client']} retx={c['retx']} "
f"FIN={c['fin']} RST={c['rst']} host_win=[{min(c['cwin'] or [0])},{max(c['cwin'] or [0])}] "
f"dev_win=[{min(c['dwin'] or [0])},{max(c['dwin'] or [0])}] dev_ctrl_after_last_data={c['after'][:4]}"
)
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])
@@ -1,8 +0,0 @@
# Pico 2 W on the station network (name set with -s name).
rp2:
board: rpipico2w
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
packages:
common: !include rp-common.yaml
@@ -1,18 +0,0 @@
# Pico W that falls back to its AP; logs the AP client count when it changes (appeek.hpp). Set a fresh name per build
# with -s name so no saved network carries over.
substitutions:
ap_ssid: rp2webap
rp2:
board: rpipicow
esphome:
includes: [appeek.hpp]
packages:
hwtest: !include ../../templates/dut-fallback-ap.yaml
interval:
- interval: 2s
then:
- lambda: |-
static int last = -1;
int n = appeek::ap_clients();
if (n != last) ESP_LOGI("test", "AP clients %d", n);
last = n;
@@ -1,11 +0,0 @@
# Pico W on the station network with an active bluetooth_proxy (name set with -s name).
rp2:
board: rpipicow
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
rp2_ble_tracker:
bluetooth_proxy:
active: true
packages:
common: !include rp-common.yaml
@@ -1,13 +0,0 @@
# Shared by every station and Ethernet build: encrypted API, web_server and a restart button on top of the
# diagnostics package (5 Hz state traffic, uptime, heap, reset reason). Substitution: name (set with -s name).
packages:
diagnostics: !include ../../templates/diagnostics.yaml
api:
encryption:
key: !secret api_key
reboot_timeout: 0s
web_server:
port: 80
button:
- platform: restart
name: Restart
@@ -1,80 +0,0 @@
"""API soak: subscribe states and logs for SECONDS, reconnect on drops, report the state count, uptime resets
(reboots), reset reason and crash or assert lines. usage: soak.py HOST SECONDS LOGFILE env: API_KEY
Exits 1 on a drop, an uptime reset, a crash or assert line, no states at all or no uptime reading."""
import asyncio
import contextlib
import pathlib
import re
import sys
import time
from aioesphomeapi import LogLevel
from aioesphomeapi.model import SensorState, TextSensorState
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from apiconn import connect, log_text, stop_event # noqa: E402
BAD = re.compile(r"CRASH|panic|assert|HardFault|LWIP|lock not held", re.IGNORECASE)
async def main(host: str, secs: float, logf: str) -> None:
end = time.monotonic() + secs
states = drops = reboots = 0
last_up = None
reasons: set[str] = set()
bad: list[str] = []
with pathlib.Path(logf).open("a", encoding="utf-8") as out:
def w(line: str) -> None:
out.write(f"{time.strftime('%T')} {line}\n")
while time.monotonic() < end:
stopped, on_stop = stop_event()
cli = await connect(host, tries=60, timeout=15, on_stop=on_stop)
info = await cli.device_info()
w(f"connected {info.name} {info.esphome_version} {info.compilation_time}")
ents, _ = await cli.list_entities_services()
names = {e.key: e.object_id for e in ents}
def on_state(s, names: dict[int, str] = names) -> None:
nonlocal states, last_up, reboots
states += 1
n = names.get(s.key, "")
if isinstance(s, SensorState) and n == "uptime" and not s.missing_state:
if last_up is not None and s.state + 5 < last_up:
reboots += 1
w(f"UPTIME RESET {last_up} -> {s.state}")
last_up = s.state
if isinstance(s, TextSensorState) and n == "reset_reason" and s.state:
reasons.add(s.state)
def on_log(m) -> None:
line = log_text(m)
w(line)
if BAD.search(line):
bad.append(line)
cli.subscribe_states(on_state)
cli.subscribe_logs(on_log, log_level=LogLevel.LOG_LEVEL_DEBUG)
with contextlib.suppress(TimeoutError):
await asyncio.wait_for(stopped.wait(), max(0.0, end - time.monotonic()))
if stopped.is_set():
drops += 1
w("DROPPED")
with contextlib.suppress(Exception):
await cli.disconnect()
print(
f"states={states} drops={drops} uptime_resets={reboots} last_uptime={last_up} "
f"reset_reason={sorted(reasons)} bad_lines={len(bad)}"
)
for b in bad[:10]:
print("BAD", b)
if last_up is None:
print("no uptime state seen, so reboots were not checked")
if drops or reboots or bad or not states or last_up is None:
sys.exit("FAIL")
print("PASS")
asyncio.run(main(sys.argv[1], float(sys.argv[2]), sys.argv[3]))
@@ -1,13 +0,0 @@
#!/bin/zsh
# sseabc.sh HOST TAG: 40 s SSE streams with (A) the API soak, (B) page loads every 5 s, (C) nothing else; state events
# per 5 s. Diagnostic: it prints counts (and the soak's PASS or FAIL line) for reading, with no verdict of its own.
# env: TREE or PY, API_KEY (or apikey.txt here)
D=${0:A:h}; H=$1; T=$2; PY=${PY:-${TREE:?set TREE or PY}/venv/bin/python}
[ -n "$API_KEY" ] || export API_KEY=$(cat $D/apikey.txt)
bins() { awk 'NR==1{t0=$1} /event: state/ {c[int(($1-t0)/5)]++} END {for(i=0;i<8;i++) printf "%d ", c[i]; print ""}' $1; }
(curl -s -N -m 40 http://$H/events | $PY -I $D/ts.py > $D/$T-A.txt) & $PY -I $D/soak.py $H 40 $D/$T-A-soak.log | tail -1; wait
echo "A sse+api states $(grep -c 'event: state' $D/$T-A.txt) per5s: $(bins $D/$T-A.txt)"
(curl -s -N -m 40 http://$H/events | $PY -I $D/ts.py > $D/$T-B.txt) & (for i in 1 2 3 4 5 6 7; do curl -s -o /dev/null -m 10 http://$H/; sleep 5; done); wait
echo "B sse+pages states $(grep -c 'event: state' $D/$T-B.txt) per5s: $(bins $D/$T-B.txt)"
curl -s -N -m 40 http://$H/events | $PY -I $D/ts.py > $D/$T-C.txt
echo "C sse alone states $(grep -c 'event: state' $D/$T-C.txt) per5s: $(bins $D/$T-C.txt)"
@@ -1,40 +0,0 @@
#!/bin/zsh
# sserun.sh HOST TAG SECS MODE(alone|api|pages) [N] : N sequential SSE streams (curl -m SECS each) with a pcap, a 1 s
# netstat poll and optional API log stream or page loads; after each stream ends, a fresh /events and GET / probe.
# Exits 1 when the API log stream or the API check after the streams (api, apipages) failed.
# env: TREE or PY, IFACE (default en0), API_KEY or apikey.txt here; tcpdump must be allowed to capture (bpf group on macOS)
setopt null_glob
D=${0:A:h}; H=$1; T=$2; S=$3; M=$4; N=${5:-1}
PY=${PY:-${TREE:?set TREE or PY}/venv/bin/python}; IFACE=${IFACE:-en0} # the host interface that reaches the device
cd $D
rm -f $T-*.txt $T.pcap $T-api*.log
tcpdump -i $IFACE -n -s 200 -w $T.pcap host $H and port 80 2>$T-tcpdump.err & TP=$!
sleep 1; kill -0 $TP 2>/dev/null || { echo "FAIL: tcpdump did not start: $(cat $T-tcpdump.err)"; exit 1; }
(while true; do echo "$(date +%s) $(netstat -anp tcp | grep -F "$H.80 " | tr -s ' ' | tr '\n' '|')"; sleep 1; done) > $T-netstat.txt 2>&1 & NP=$!
sleep 1
TOT=$(( (S+12)*N + 10 ))
[[ $M == api || $M == apipages ]] && { API_KEY=${API_KEY:-$(cat apikey.txt)} $PY -I apilog.py $H $TOT $D/$T-api.log > $T-apisum.txt & AP=$!; sleep 3 }
[[ $M == pages || $M == apipages ]] && { (for i in $(seq 1 $((TOT/5))); do echo "$(date +%s) $(curl -s -o /dev/null -w '%{http_code} %{time_total}' -m 10 http://$H/)"; sleep 5; done) > $T-pages.txt & PP=$!; }
for i in $(seq 1 $N); do
F=$T-sse$i.txt
( curl -s -N -m $S http://$H/events; echo "CURL_EXIT $?" ) | $PY -I ts.py > $F
awk -v i=$i 'NR==1{t0=$1} /event: state/{c++; last=$1} /event: log/{l++} /CURL_EXIT/{e=$3; te=$1} END{printf "stream %d: states=%d last_state=+%.1fs logs=%d curl_exit=%s at +%.1fs\n", i, c, last-t0, l, e, te-t0}' $F | tee -a $T-summary.txt
echo " probe fresh_events(8s)=$(curl -s -N -m 8 http://$H/events | grep -c 'event: state') get_root=$(curl -s -o /dev/null -w '%{http_code}/%{size_download}B/%{time_total}s' -m 10 http://$H/)" | tee -a $T-summary.txt
done
RC=0
# a failed API log run must say so in the summary, or an api run reads like one without API traffic
if [[ -n $AP ]]; then
wait $AP; ARC=$?
if [ $ARC = 0 ]; then cat $T-apisum.txt | tee -a $T-summary.txt
else echo "api log FAILED rc=$ARC" | tee -a $T-summary.txt; RC=1; fi
fi
[[ -n $PP ]] && kill $PP 2>/dev/null
if [[ $M == api || $M == apipages ]]; then
OUT=$(API_KEY=${API_KEY:-$(cat apikey.txt)} $PY -I apilog.py $H 8 $D/$T-apiafter.log); ARC=$?
if [ $ARC = 0 ]; then echo "api-after: $OUT" | tee -a $T-summary.txt
else echo "api-after FAILED rc=$ARC" | tee -a $T-summary.txt; RC=1; fi
fi
# a tcpdump that died mid-run leaves a short pcap that pcapsum.py would read as fewer connections
kill -0 $TP 2>/dev/null || { echo "pcap capture ended early, see $T-tcpdump.err" | tee -a $T-summary.txt; RC=1; }
kill $TP $NP 2>/dev/null; wait 2>/dev/null
exit $RC
@@ -1,52 +0,0 @@
#!/bin/zsh
# staflow.sh NAME CONFIG BLE(0/1): USB flash CONFIG (picow.yaml, pico2w.yaml) as NAME, then over Wi-Fi: API soak with
# page loads, SSE alone, OTA, restart, a short soak and (BLE=1) a GATT hold through the proxy. Serial captured
# throughout. PASS needs both soaks to pass, every page load to return 200, state events on the SSE stream, a reboot
# (lower Uptime over REST) after the OTA and after the restart, the GATT hold (BLE=1), no crash or assert line and a
# capture that lasted the run; exits 1 otherwise.
# env: TREE, PY, PICO_SN (the Pico's USB serial number), PEER_MAC (the ble_notify server, for BLE=1); apikey.txt here
D=${0:A:h}; N=$1; C=$2; BLE=${3:-0}; S=$D/..
T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}; SN=${PICO_SN:?set PICO_SN}
FAILS=0; fail() { echo "FAIL: $*"; FAILS=$((FAILS + 1)); }
export API_KEY=$(cat $D/apikey.txt)
$S/pio_build.sh compile $N $D/$C || exit 1
PORT=$($PY $S/ports.py --wait 2e8a --serial $SN --timeout 30) || { echo "FAIL: no pico"; exit 1; }
$S/pio_build.sh upload $N $D/$C $PORT || exit 1
PORT=$($PY $S/ports.py --wait 2e8a --serial $SN --timeout 60) || { echo "FAIL: pico gone after the upload"; exit 1; }
L=$D/$N-serial.log
$PY $S/serial_capture.py $PORT 1100 $L 2> $D/$N-cap.err &
CAP=$!; trap 'kill $CAP 2>/dev/null' EXIT
H=$($S/resolve.sh $N) || exit 1; echo "$H" > $D/$N-host.txt; sleep 5
(for i in $(seq 1 36); do curl -s -o /dev/null -w "%{http_code}\n" -m 10 http://$H/ ; sleep 5; done > $D/$N-web.txt) &
WEB=$!
$PY -I $D/soak.py $H 180 $D/$N-soak.log || fail "the 180 s API soak"
wait $WEB
echo "web: $(sort $D/$N-web.txt | uniq -c | tr '\n' ' ')"
[ "$(grep -c -v '^200$' $D/$N-web.txt)" = 0 ] && [ -s $D/$N-web.txt ] || fail "page loads other than 200"
timeout 30 curl -s -N http://$H/events > $D/$N-sse.txt
SSE=$(grep -c 'event: state' $D/$N-sse.txt); echo "sse 30s alone: states $SSE pings $(grep -c 'event: ping' $D/$N-sse.txt)"
[ "$SSE" -gt 0 ] || fail "no state events on the SSE stream"
# the Uptime sensor over REST (web_server entity URLs use the entity name); empty when there is no answer
upt() { curl -s -m 5 http://$H/sensor/Uptime | $PY -c 'import json, sys; print(int(json.load(sys.stdin)["value"]))' 2>/dev/null; }
# wait up to 120 s for the device to answer with an uptime lower than U0 (it rebooted)
rebooted() { local u; for _ in $(seq 1 60); do u=$(upt); [ -n "$1" ] && [ -n "$u" ] && [ "$u" -lt "$1" ] && return 0; sleep 2; done; return 1; }
U0=$(upt); [ -n "$U0" ] || fail "no Uptime reading over REST"
$S/pio_build.sh upload $N $D/$C $H || fail "the OTA"
rebooted $U0 || fail "no reboot seen within 120 s after the OTA"
# let the uptime grow past 30 s first, so the first reading after the restart is clearly lower
for _ in $(seq 1 30); do U0=$(upt); [ -n "$U0" ] && [ "$U0" -ge 30 ] && break; sleep 2; done
$PY -I $S/api_button.py $H "$API_KEY" press Restart > /dev/null || fail "pressing Restart"
rebooted $U0 || fail "no reboot seen within 120 s after the restart"
$PY -I $D/soak.py $H 30 $D/$N-after.log || fail "the soak after OTA and restart"
if [ $BLE = 1 ]; then
echo "--- ble"; timeout 400 $PY -I $D/gatthold.py $H ${PEER_MAC:?set PEER_MAC} 180 || fail "the GATT hold"
fi
sleep 3
kill -0 $CAP 2>/dev/null || fail "the capture ended before the run did (see $D/$N-cap.err)"
[ "$(grep -a -c -v '^\[[0-9:.]*\]\[capture\]' $L)" -gt 0 ] || fail "no firmware lines in $L"
kill $CAP; wait $CAP 2>/dev/null; trap - EXIT
CRASH=$(grep -a -c -i -E 'CRASH|panic|HardFault|assert|lock not held' $L)
echo "serial: crash/assert lines $CRASH, boots $(grep -a -c 'Log initialized\|ESPHome version' $L), port losses $(grep -a -c 'port lost' $L), lines $(wc -l < $L)"
[ "$CRASH" = 0 ] || fail "$CRASH crash or assert lines"
[ $FAILS = 0 ] || exit 1
echo PASS
@@ -1,62 +0,0 @@
"""stallctr.py PCAP DEV_IP APILOG: for each /events connection print last data and FIN wall times, and the atcp counter
line just before the last data, just after it (about +1.5 s), and about 7 s later (after the FIN). APILOG comes from
apilog.py with counter log lines tagged [atcp."""
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from pcapsum import packets # noqa: E402
def main(pcap: str, dev: str, logf: str) -> None:
conns: dict[str, dict] = {}
for k in packets(pcap, dev):
c = conns.setdefault(
k["port"], {"t0": k["t"], "ev": False, "last": None, "fin": None}
)
if "GET /events" in k["line"]:
c["ev"] = True
if k["from_dev"] and k["len"] > 0:
c["last"] = k["t"]
if k["from_dev"] and "F" in k["flags"] and c["fin"] is None:
c["fin"] = k["t"]
logs = []
for line in pathlib.Path(logf).read_text(encoding="utf-8").splitlines():
if "[atcp" in line:
t, rest = line.split(" ", 1)
logs.append((float(t), rest.strip().split("]: ", 1)[-1]))
def at(t: float) -> tuple[float, str] | None:
best = None
for lt, s in logs:
if lt <= t:
best = (lt, s)
return best
events = sum(1 for c in conns.values() if c["ev"] and c["last"] is not None)
print(f"{events} /events connections with data, {len(logs)} atcp counter lines")
if not events or not logs:
sys.exit(
"FAIL: nothing to line up (no /events connection in the pcap or no [atcp line in the API log)"
)
for p, c in conns.items():
if not c["ev"] or c["last"] is None:
continue
fin = (
f"FIN dev +{c['fin'] - c['last']:.2f}s after last data"
if c["fin"]
else "no dev FIN"
)
print(f"conn {p}: last data at +{c['last'] - c['t0']:.2f}s, {fin}")
for lbl, t in (
("before", c["last"] - 0.01),
("+1.5s", c["last"] + 1.5),
("+7s", c["last"] + 7),
):
if a := at(t):
print(f" {lbl:7} {a[1]}")
if __name__ == "__main__":
main(*sys.argv[1:4])
@@ -1,8 +0,0 @@
"""Prefix each stdin line with a wall clock timestamp (ms)."""
import sys
import time
for line in sys.stdin.buffer:
sys.stdout.write(f"{time.time():.3f} {line.decode(errors='replace')}")
sys.stdout.flush()
@@ -1,5 +0,0 @@
substitutions:
name: sppr
rx_buf: "32768"
packages:
common: !include sp-common.yaml
@@ -1,67 +0,0 @@
# serial_proxy on UART A, simulated device (spsim.hpp) on UART B, cross-wired through the GPIO matrix
esphome:
name: ${name}
includes:
- spsim.hpp
on_boot:
priority: -100
then:
- lambda: |-
spsim::bus = id(sim_uart);
spsim::proxy_bus = id(proxy_uart);
esp32:
variant: esp32c3
board: esp32-c3-devkitm-1
framework:
type: esp-idf
logger:
hardware_uart: USB_SERIAL_JTAG
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
power_save_mode: none
api:
reboot_timeout: 0s
uart:
- id: proxy_uart
tx_pin:
number: GPIO4
allow_other_uses: true
rx_pin:
number: GPIO5
allow_other_uses: true
baud_rate: 1920
rx_buffer_size: ${rx_buf}
- id: sim_uart
tx_pin:
number: GPIO5
allow_other_uses: true
rx_pin:
number: GPIO4
allow_other_uses: true
baud_rate: 1920
rx_buffer_size: 1024
tx_buffer_size: 1024
serial_proxy:
- id: proxy
uart_id: proxy_uart
name: Sim Port
port_type: TTL
ezsp_proxy_tap:
serial_proxy_id: proxy
interval:
# the main loop cadence: a faster interval would also speed up the proxy's own loop and skew its latency
- interval: 16ms
then:
- lambda: spsim::poll();
- interval: 10s
then:
- lambda: 'ESP_LOGI("spsim", "HEAP free=%u min=%u", (unsigned) esp_get_free_heap_size(), (unsigned) esp_get_minimum_free_heap_size());'
@@ -1,424 +0,0 @@
"""Serial proxy client for spsim.hpp: subscribes over a raw plaintext API socket and checks every byte.
spclient.py HOST --baud B --mode reply|stream|ash [--pauses N --pause S --read S] [--duration S]
[--interval MS] [--protocol]
Reads only when told to, with a 4 KB receive buffer set before connect, so a pause fills the TCP
pipe toward the device quickly. Prints per-phase counters and a RESULT line.
"""
from __future__ import annotations
import argparse
import asyncio
import binascii
import socket
import sys
import time
from aioesphomeapi import api_pb2
from aioesphomeapi.core import MESSAGE_TYPE_TO_PROTO
TYPE_OF = {cls: num for num, cls in MESSAGE_TYPE_TO_PROTO.items()}
REPLY_SIZE = 88
DEBUG = False
def varint(v: int) -> bytes:
out = bytearray()
while True:
b = v & 0x7F
v >>= 7
if v:
out.append(b | 0x80)
else:
out.append(b)
return bytes(out)
def read_varint(buf: bytearray, pos: int) -> tuple[int, int] | None:
v = shift = 0
while pos < len(buf):
b = buf[pos]
pos += 1
v |= (b & 0x7F) << shift
if not b & 0x80:
return v, pos
shift += 7
return None
def reply(n: int) -> bytes:
return (
bytes([0xA5])
+ n.to_bytes(4, "big")
+ bytes((n + j) % 251 for j in range(REPLY_SIZE - 5))
)
class ReplyCheck:
"""Expects reply(0), reply(1), ... back to back; counts complete and broken replies."""
def __init__(self) -> None:
self.buf = bytearray()
self.next = 0
self.complete = 0
self.broken = 0
self.out_of_order = 0
self.received = 0
self.junk = 0 # leftovers of the baud switch before reply 0
def feed(self, data: bytes) -> None:
self.received += len(data)
self.buf += data
if (
self.complete == 0
and self.next == 0
and not self.buf.startswith(reply(0)[: len(self.buf)])
):
p = self.buf.find(b"\xa5\x00\x00\x00\x00")
cut = p if p != -1 else max(len(self.buf) - 4, 0)
self.junk += cut
del self.buf[:cut]
self._scan(False)
def _scan(self, final: bool) -> None:
buf = self.buf
while len(buf) >= REPLY_SIZE:
if buf[:REPLY_SIZE] == reply(self.next):
del buf[:REPLY_SIZE]
self.complete += 1
self.next += 1
continue
found = None
p = buf.find(0xA5, 1)
while p != -1 and p + REPLY_SIZE <= len(buf):
k = int.from_bytes(buf[p + 1 : p + 5], "big")
if buf[p : p + REPLY_SIZE] == reply(k):
found = (p, k)
break
p = buf.find(0xA5, p + 1)
if found is None:
if not final:
return
self.broken += 1
del buf[:]
return
p, k = found
if k < self.next:
self.out_of_order += 1
del buf[: p + REPLY_SIZE]
continue
self.broken += max(k - self.next, 1)
del buf[:p]
self.next = k
def finish(self) -> None:
self._scan(True)
def summary(self) -> str:
return (
f"complete={self.complete} broken={self.broken} out_of_order={self.out_of_order} "
f"received={self.received - self.junk} junk={self.junk} next={self.next}"
)
class AshCheck:
"""Parses ASH DATA frames from spsim and checks the sequence numbers."""
def __init__(self) -> None:
self.frame = bytearray()
self.esc = False
self.valid = 0
self.bad = 0
self.gaps = 0
self.missing_frames = 0
self.out_of_order = 0
self.last = -1
self.received = 0
def feed(self, data: bytes) -> None:
self.received += len(data)
for b in data:
if b == 0x7E:
self._frame()
self.frame.clear()
self.esc = False
elif b == 0x7D:
self.esc = True
else:
self.frame.append(b ^ 0x20 if self.esc else b)
self.esc = False
def _frame(self) -> None:
f = self.frame
if not f:
return
if len(f) != 27 or binascii.crc_hqx(bytes(f[:25]), 0xFFFF) != int.from_bytes(
f[25:27], "big"
):
self.bad += 1
return
seq = int.from_bytes(f[1:5], "big")
self.valid += 1
if self.last >= 0:
if seq <= self.last:
self.out_of_order += 1
elif seq != self.last + 1:
self.gaps += 1
self.missing_frames += seq - self.last - 1
self.last = seq
def summary(self) -> str:
return (
f"valid_frames={self.valid} bad_frames={self.bad} gaps={self.gaps} "
f"missing_frames={self.missing_frames} out_of_order={self.out_of_order} "
f"received={self.received} last_seq={self.last}"
)
class Client:
def __init__(self, check) -> None:
self.check = check
self.buf = bytearray()
self.reading = asyncio.Event()
self.reading.set()
self.last_data = time.monotonic()
self.responses: list[str] = []
self.setup_failed: list[str] = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096)
s.setblocking(False)
self.sock = s
self.collect = True
async def send(self, msg) -> None:
payload = msg.SerializeToString()
frame = b"\x00" + varint(len(payload)) + varint(TYPE_OF[type(msg)]) + payload
await asyncio.get_running_loop().sock_sendall(self.sock, frame)
async def acked(self, msg, want: str, timeout: float = 3.0) -> None:
"""Send msg and wait for a response starting with want ("hello", "type=N")."""
n = len(self.responses)
await self.send(msg)
end = time.monotonic() + timeout
while time.monotonic() < end:
if any(r.startswith(want) for r in self.responses[n:]):
return
await asyncio.sleep(0.02)
print(f"no {want} response within {timeout:.0f} s", flush=True)
self.setup_failed.append(want.strip())
async def write(self, data: bytes) -> None:
await self.send(api_pb2.SerialProxyWriteRequest(instance=0, data=data))
async def reader(self) -> None:
loop = asyncio.get_running_loop()
while True:
await self.reading.wait()
data = await loop.sock_recv(self.sock, 4096)
if not data:
print("CONNECTION CLOSED by device", flush=True)
return
self.buf += data
while (m := self._parse()) is not None:
await self._handle(*m)
def _parse(self):
buf = self.buf
if not buf:
return None
assert buf[0] == 0, f"indicator {buf[0]}"
if (a := read_varint(buf, 1)) is None:
return None
size, pos = a
if (b := read_varint(buf, pos)) is None:
return None
mtype, pos = b
if len(buf) - pos < size:
return None
payload = bytes(buf[pos : pos + size])
del buf[: pos + size]
return mtype, payload
async def _handle(self, mtype: int, payload: bytes) -> None:
if mtype == TYPE_OF[api_pb2.PingRequest]:
await self.send(api_pb2.PingResponse())
elif mtype == TYPE_OF[api_pb2.SerialProxyDataReceived]:
data = api_pb2.SerialProxyDataReceived.FromString(payload).data
self.last_data = time.monotonic()
if self.collect:
if DEBUG:
print(
f"{time.monotonic():.2f} RX {len(data)} {data.hex()}",
flush=True,
)
self.check.feed(data)
elif mtype == TYPE_OF[api_pb2.SerialProxyRequestResponse]:
r = api_pb2.SerialProxyRequestResponse.FromString(payload)
self.responses.append(f"type={r.type} status={r.status} {r.error_message}")
elif mtype == TYPE_OF[api_pb2.HelloResponse]:
self.responses.append("hello")
elif mtype == TYPE_OF[api_pb2.DisconnectRequest]:
print("DISCONNECT REQUEST from device", flush=True)
async def configure(c: Client, baud: int) -> None:
await c.acked(
api_pb2.SerialProxyConfigureRequest(
instance=0, baudrate=baud, stop_bits=1, data_size=8, parity=0
),
f"type={api_pb2.SERIAL_PROXY_REQUEST_TYPE_CONFIGURE} ",
)
def data_verdict(check, mode: str, requests: int) -> str:
"""Reply mode must deliver every reply intact and in order. Stream mode and the ASH tap lose bytes over Wi-Fi on
every build (serial_proxy.md), so they are only judged on getting data at all."""
if check.received == 0:
return "loss:nothing-received"
if mode != "reply":
return "not-judged"
if check.broken or check.out_of_order or check.complete != requests:
return f"loss:{check.complete}/{requests}-complete"
return "ok"
async def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("host")
ap.add_argument("--port", type=int, default=6053)
ap.add_argument("--baud", type=int, default=1920)
ap.add_argument("--mode", choices=["reply", "stream", "ash"], default="reply")
ap.add_argument(
"--interval",
type=float,
default=600,
help="request interval in ms (reply mode)",
)
ap.add_argument(
"--duration", type=float, default=0, help="plain reading time in s, no pauses"
)
ap.add_argument("--pauses", type=int, default=0)
ap.add_argument("--pause", type=float, default=10)
ap.add_argument("--read", type=float, default=15)
ap.add_argument(
"--protocol",
action="store_true",
help="put the port in PROTOCOL mode (tap active)",
)
ap.add_argument("--debug", action="store_true")
a = ap.parse_args()
global DEBUG # noqa: PLW0603
DEBUG = a.debug
check = AshCheck() if a.mode == "ash" else ReplyCheck()
c = Client(check)
loop = asyncio.get_running_loop()
await loop.sock_connect(c.sock, (a.host, a.port))
print(
f"SO_RCVBUF={c.sock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)}",
flush=True,
)
rtask = asyncio.create_task(c.reader())
def reader_done(t: asyncio.Task) -> None:
if not t.cancelled() and (e := t.exception()) is not None:
print(f"READER FAILED {type(e).__name__}: {e}", flush=True)
rtask.add_done_callback(reader_done)
await c.acked(
api_pb2.HelloRequest(
client_info="spclient", api_version_major=1, api_version_minor=10
),
"hello",
)
await c.acked(
api_pb2.SerialProxyRequest(
instance=0, type=api_pb2.SERIAL_PROXY_REQUEST_TYPE_SUBSCRIBE
),
f"type={api_pb2.SERIAL_PROXY_REQUEST_TYPE_SUBSCRIBE} ",
)
# Bring the simulator to the target baud from whichever rate it is on, then the proxy
c.collect = False
for b in (1920, 115200):
await configure(c, b)
await c.write(b"\x7eB%d\x7e" % a.baud)
await asyncio.sleep(0.6)
await configure(c, a.baud)
await c.write(b"\x7eX\x7e")
await asyncio.sleep(0.3)
await c.acked(
api_pb2.SerialProxySetModeRequest(
instance=0,
mode=api_pb2.SERIAL_PROXY_MODE_PROTOCOL
if a.protocol
else api_pb2.SERIAL_PROXY_MODE_RAW,
),
f"type={api_pb2.SERIAL_PROXY_REQUEST_TYPE_SET_MODE} ",
)
await asyncio.sleep(
1.0
) # bytes left over from the baud switches drain before collecting
c.collect = True
print(f"setup responses: {c.responses}", flush=True)
stop = asyncio.Event()
requests = 0
async def requester() -> None:
nonlocal requests
while not stop.is_set():
await c.write(b"\x7eR\x7e")
requests += 1
await asyncio.sleep(a.interval / 1000)
if a.mode == "reply":
wtask = asyncio.create_task(requester())
else:
await c.write(b"\x7eS\x7e" if a.mode == "stream" else b"\x7eA\x7e")
wtask = None
t0 = time.monotonic()
if a.duration:
end = t0 + a.duration
while time.monotonic() < end:
await asyncio.sleep(min(30, end - time.monotonic()))
print(f"t={time.monotonic() - t0:.0f}s {check.summary()}", flush=True)
for i in range(a.pauses):
await asyncio.sleep(a.read)
print(
f"t={time.monotonic() - t0:.0f}s before pause {i + 1}: {check.summary()}",
flush=True,
)
c.reading.clear()
await asyncio.sleep(a.pause)
c.reading.set()
if a.pauses:
await asyncio.sleep(a.read)
stop.set()
if wtask:
await wtask
await asyncio.sleep(1.0)
await c.write(b"\x7eX\x7e")
await asyncio.sleep(3)
# Drain: until nothing arrives for 3 s
while time.monotonic() - c.last_data < 3:
await asyncio.sleep(0.5)
if isinstance(check, ReplyCheck):
check.finish()
# a reader that died (closed connection, bad frame) ends the counts early; say so on the RESULT line
reader = "stopped" if rtask.done() else "ok"
setup = "failed:" + ",".join(c.setup_failed) if c.setup_failed else "ok"
data = data_verdict(check, a.mode, requests)
print(
f"RESULT mode={a.mode} baud={a.baud} requests={requests} {check.summary()} reader={reader} setup={setup} data={data}",
flush=True,
)
rtask.cancel()
c.sock.close()
return 1 if c.setup_failed or reader != "ok" or data.startswith("loss") else 0
if __name__ == "__main__":
sys.exit(asyncio.run(main()))
@@ -1,219 +0,0 @@
#pragma once
// Simulated serial device for serial_proxy tests, on a UART cross-wired to the proxy's UART.
// Commands arrive through the proxy framed as 7E <text> 7E:
// R queue one 88 byte reply S stream replies back to back
// A stream ASH DATA frames every 50 ms and time the tap's ACKs
// X stop, log SIMDONE totals, reset the counters
// B<baud> switch this UART to <baud> (the client then reconfigures the proxy)
// Reply n: A5, n (u32 BE), then 83 bytes (n + j) % 251.
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "esphome/components/uart/uart_component.h"
#include <esp_heap_caps.h>
#include <esp_system.h>
namespace spsim {
using namespace esphome;
static const char *const TAG = "spsim";
static constexpr size_t REPLY_SIZE = 88;
static constexpr uint32_t ASH_PERIOD_MS = 50;
inline uart::UARTComponent *bus = nullptr;
// the proxy's own UART: its RX backlog shows bytes held back while the client is blocked
inline uart::UARTComponent *proxy_bus = nullptr;
inline uint32_t backlog_max = 0;
enum Mode : uint8_t { IDLE, REPLY, STREAM, ASH };
inline Mode mode = IDLE;
inline uint32_t queued = 0, replies = 0, bytes = 0, requests = 0;
inline uint8_t out[512];
inline size_t out_len = 0, out_pos = 0;
// ASH timing
inline uint32_t ash_seq = 0, ash_sent = 0, acks = 0, ack_lat_sum = 0, ack_lat_max = 0, last_ash = 0;
inline uint32_t sent_at[8];
inline bool waiting[8];
inline uint32_t win_acks = 0, win_lat_sum = 0, win_lat_max = 0, win_unacked = 0;
// command parser
inline uint8_t cmd[32];
inline size_t cmd_len = 0;
inline uint32_t last_status = 0;
inline void make_reply(uint32_t n) {
out[0] = 0xA5;
put_be32(out + 1, n);
for (size_t j = 0; j < REPLY_SIZE - 5; j++)
out[5 + j] = (n + j) % 251;
out_len = REPLY_SIZE;
out_pos = 0;
}
inline size_t ash_put(uint8_t *p, uint8_t b) {
switch (b) {
case 0x7E:
case 0x7D:
case 0x11:
case 0x13:
case 0x18:
case 0x1A:
p[0] = 0x7D;
p[1] = b ^ 0x20;
return 2;
default:
p[0] = b;
return 1;
}
}
// DATA frame: control (frame number << 4), data = seq (u32 BE) + 20 pattern bytes, CRC-CCITT BE, flag
inline void make_ash(uint32_t seq) {
uint8_t body[1 + 24 + 2];
const uint8_t frm = seq & 7;
body[0] = frm << 4;
put_be32(body + 1, seq);
for (int j = 0; j < 20; j++)
body[5 + j] = (seq * 3 + j) & 0xFF;
uint16_t crc = crc16be(body, 25, 0xFFFF);
body[25] = crc >> 8;
body[26] = crc;
size_t n = 0;
for (uint8_t b : body)
n += ash_put(out + n, b);
out[n++] = 0x7E;
out_len = n;
out_pos = 0;
sent_at[frm] = millis();
if (waiting[frm])
win_unacked++;
waiting[frm] = true;
}
inline void log_done() {
ESP_LOGI(TAG,
"SIMDONE mode=%u requests=%u replies=%u bytes=%u ash_sent=%u acks=%u lat_avg=%u lat_max=%u heap=%u min=%u",
mode, requests, replies, bytes, ash_sent, acks, acks ? ack_lat_sum / acks : 0, ack_lat_max,
(unsigned) esp_get_free_heap_size(), (unsigned) esp_get_minimum_free_heap_size());
}
inline void reset() {
mode = IDLE;
queued = replies = bytes = requests = 0;
out_len = out_pos = 0;
ash_seq = ash_sent = acks = ack_lat_sum = ack_lat_max = 0;
win_acks = win_lat_sum = win_lat_max = win_unacked = 0;
for (auto &w : waiting)
w = false;
}
inline void on_ack(uint8_t num) {
// ACK num is the next frame expected, so it acknowledges num - 1
const uint8_t frm = (num - 1) & 7;
if (!waiting[frm])
return;
waiting[frm] = false;
const uint32_t lat = millis() - sent_at[frm];
acks++;
ack_lat_sum += lat;
ack_lat_max = std::max(ack_lat_max, lat);
win_acks++;
win_lat_sum += lat;
win_lat_max = std::max(win_lat_max, lat);
}
inline void on_frame() {
if (cmd_len == 3 && (cmd[0] & 0xF8) == 0x80) {
on_ack(cmd[0] & 7);
return;
}
if (cmd_len == 0)
return;
switch (cmd[0]) {
case 'R':
requests++;
if (mode == IDLE)
mode = REPLY;
queued++;
break;
case 'S':
mode = STREAM;
break;
case 'A':
reset();
mode = ASH;
break;
case 'X':
log_done();
reset();
break;
case 'B': {
cmd[cmd_len] = 0;
char *end = nullptr;
uint32_t baud = strtoul((const char *) cmd + 1, &end, 10);
if (baud == 0 || *end != '\0') {
ESP_LOGW(TAG, "bad baud command '%s'", (const char *) cmd + 1);
break;
}
bus->flush();
bus->set_baud_rate(baud);
bus->load_settings(false);
ESP_LOGI(TAG, "SIMBAUD %u", baud);
reset();
break;
}
default:
ESP_LOGW(TAG, "unknown command %02X len %u", cmd[0], cmd_len);
}
}
inline void poll() {
uint8_t b;
while (bus->available() && bus->read_byte(&b)) {
if (b == 0x7E) {
on_frame();
cmd_len = 0;
} else if (cmd_len < sizeof(cmd) - 1) {
cmd[cmd_len++] = b;
}
}
const uint32_t now = millis();
for (;;) {
if (out_pos < out_len) {
size_t room = bus->available_for_write();
if (room == 0)
break;
size_t n = std::min(room, out_len - out_pos);
bus->write_array(out + out_pos, n);
out_pos += n;
bytes += n;
if (out_pos < out_len)
break;
}
if (mode == REPLY && queued > 0) {
queued--;
make_reply(replies++);
} else if (mode == STREAM) {
make_reply(replies++);
} else if (mode == ASH && now - last_ash >= ASH_PERIOD_MS) {
last_ash = now;
make_ash(ash_seq++);
ash_sent++;
} else {
break;
}
}
if (proxy_bus != nullptr)
backlog_max = std::max<uint32_t>(backlog_max, proxy_bus->available());
if (now - last_status >= 1000) {
last_status = now;
if (mode == ASH) {
ESP_LOGI(TAG, "ASHWIN sent=%u acks=%u win_acks=%u lat_avg=%u lat_max=%u unacked=%u backlog_max=%u", ash_sent,
acks, win_acks, win_acks ? win_lat_sum / win_acks : 0, win_lat_max, win_unacked, backlog_max);
backlog_max = 0;
win_acks = win_lat_sum = win_lat_max = win_unacked = 0;
} else if (mode != IDLE) {
ESP_LOGI(TAG, "SIMSTAT requests=%u replies=%u bytes=%u queued=%u backlog_max=%u heap=%u", requests, replies,
bytes, queued, backlog_max, (unsigned) esp_get_free_heap_size());
backlog_max = 0;
}
}
}
} // namespace spsim
@@ -1,40 +0,0 @@
#!/bin/bash
# suite.sh BUILD TREE: flash spBUILD.yaml (a copy of example-run.yaml) from TREE, capture the board, run every case
# (CASES="a b" picks some), print the client RESULT and the simulator's SIMDONE totals per case.
# env: PORT (the board's console), PY, PIO_CORE (default ./pio)
D=$(cd "$(dirname "$0")" && pwd); S=$(dirname "$D"); cd "$D" || exit 1
B=${1:?build}; TREE=${2:?tree}; PORT=${PORT:?set PORT}; PY=${PY:-$TREE/venv/bin/python}
pkill -f "[s]erial_capture.py $PORT "; sleep 1
TREE=$TREE PY=$PY bash "$S/pio_build.sh" upload "sp$B" "$D/sp$B.yaml" "$PORT" || exit 1
CAP=$D/$B-suite-cap-$(date +%H%M%S).txt
nohup $PY "$S/serial_capture.py" "$PORT" 7200 "$CAP" > /dev/null 2>&1 &
IP=$(bash "$S/resolve.sh" "sp$B" 40) || exit 1
sleep 10
grep -a HEAP $CAP | tail -1 | sed 's/^/BOOT /'
FAILED=()
run() { # run LABEL CLIENT-ARGS...
local L=$1; shift
[[ ${CASES:-all} == all || " $CASES " == *" $L "* ]] || return 0
local N
N=$(( $(wc -l < "$CAP") + 1 )) # first capture line of this case
local RC
timeout 1200 $PY spclient.py $IP "$@" > $B-$L.txt 2>&1; RC=$?
[ $RC = 0 ] || FAILED+=("$L")
sleep 2
echo "== $L (client exit $RC): $(grep RESULT $B-$L.txt || echo 'no RESULT line')"
echo " $(tail -n +$N $CAP | grep -a SIMDONE | tail -1 | sed 's/.*SIMDONE//' | grep . || echo 'no SIMDONE in this case')"
echo " $(tail -n +$N $CAP | grep -a -E 'SIMSTAT|ASHWIN' | sed 's/.*backlog_max=\([0-9]*\).*/\1/' | sort -n | tail -1 | sed 's/^/peak backlog /')"
grep -a -c -E "CONNECTION CLOSED|DISCONNECT" $B-$L.txt | sed 's/^/ disconnects /'
}
run normal1920 --baud 1920 --mode reply --interval 600 --duration 180
run normal115200 --baud 115200 --mode stream --duration 120
run pause1920 --baud 1920 --mode reply --interval 600 --pauses 12 --pause 10 --read 15
run pause115200 --baud 115200 --mode reply --interval 20 --pauses 12 --pause 5 --read 8
run tap115200 --baud 115200 --mode ash --protocol --pauses 10 --pause 5 --read 8
run normal115200r --baud 115200 --mode reply --interval 20 --duration 120
sleep 11
grep -a HEAP $CAP | tail -1 | sed 's/^/END /'
CR=$(grep -a -c -E "rst:|Guru|panic|abort\(\)|Backtrace" "$CAP"); echo "crash lines $CR"
[ "$CR" = 0 ] || FAILED+=("crash")
grep -a -q HEAP "$CAP" || FAILED+=("capture-empty") # the sim logs HEAP every 10 s
[ ${#FAILED[@]} = 0 ] || { echo "FAILED: ${FAILED[*]}"; exit 1; }
@@ -1,59 +0,0 @@
# ESP32 Pico kit: trf7962a driven by a fake chip (trfsim.hpp) behind the SPI delegates; the phase table in trfsim.hpp
# runs from on_boot (name set with -s name). The 1 ms interval tick is the validated timing source; keep it.
esphome:
name: ${name}
includes: [trfsim.hpp]
on_boot:
- priority: 800
then:
- lambda: trfsim::install(id(spibus), 5, 4);
- priority: -100
then:
- lambda: trfsim::late_pin_setup();
- delay: 2s
- script.execute: scenarios
esp32:
board: pico32
framework:
type: esp-idf
logger:
level: DEBUG
spi:
id: spibus
clk_pin: GPIO18
mosi_pin: GPIO23
miso_pin: GPIO19
trf7962a:
id: nfcc
cs_pin: GPIO5
irq_pin: GPIO4
vin: 3.3v
rf_power: half
on_tag:
then:
- lambda: 'ESP_LOGI("ev", "EV on_tag %s type=%s", x.c_str(), tag.get_tag_type().c_str());'
on_tag_removed:
then:
- lambda: 'ESP_LOGI("ev", "EV on_tag_removed %s", x.c_str());'
binary_sensor:
- platform: nfc
nfcc_id: nfcc
name: tagA
uid: E0-04-01-00-00-00-00-01
on_state:
- lambda: 'ESP_LOGI("ev", "EV bs_tagA %s", x ? "ON" : "OFF");'
interval:
- interval: 1ms
then:
- lambda: trfsim::tick();
script:
- id: scenarios
then:
- lambda: |-
ESP_LOGI("ev", "SETUP failed=%d", id(nfcc).is_failed());
trfsim::stats("boot");
- repeat:
count: !lambda return trfsim::NUM_PHASES;
then:
- delay: !lambda return trfsim::start_phase(iteration);
- lambda: 'trfsim::stats(trfsim::PHASES[trfsim::NUM_PHASES - 1].name); ESP_LOGI("ev", "DONE");'
Loaded 100 of 722 files, more files were not shown because too many files have changed in this diff. Show more