Compare commits

...
455 Commits
Author SHA1 Message Date
Jesse Hills e27614fda3 Merge pull request #22833 from esphome/bump-2026.11.0b6
2026.11.0b6
2026-11-17 22:24:55 +13:00
J. Nick Koston 8426d04138 [api] Make the event order backpressure test wait until the pipe is full (#22112) 2026-11-17 21:09:01 +13:00
Jesse Hills 4a39ca1b71 Fix 2026-11-17 20:54:40 +13:00
Jesse Hills 4a218fdbd8 Remove extra test 2026-11-17 20:47:40 +13:00
Jesse Hills d8fc1cd214 Bump version to 2026.11.0b6 2026-11-17 18:54:23 +13:00
J. Nick Koston 1e030b7371 [modem] Set the APN while the SIM is powered down (#22817) 2026-11-17 18:54:20 +13:00
J. Nick Koston 3b113f2c39 [wifi] Join the next network after a failed hidden network probe on ESP32 (#22764) 2026-11-17 18:54:20 +13:00
J. Nick Koston 73468592a9 [remote_base] Fix the Haier and Mirage remote_receiver binary sensors failing to compile 2026-11-17 18:54:06 +13:00
Jonathan Swoboda a1b456150d [esp32][libretiny] Make delay() wait at least the requested time (#22822) 2026-11-17 18:53:11 +13:00
J. Nick Koston 865a883abb [remote_base] Fix the canalsatld binary sensor and trigger build 2026-11-17 18:53:11 +13:00
J. Nick Koston 357a6717c8 [core] Release only the lwIP core lock a LwIPLock took (#22683) 2026-11-17 18:53:11 +13:00
J. Nick Koston bcb434e05e [esp32_ble] Stop Bluedroid re-running a failed queued MTU or execute write request (#22670) 2026-11-17 18:53:11 +13:00
J. Nick Koston fb65fcc5f6 [esp32_power_management] Clamp the tick step after light sleep so it cannot trip vTaskStepTick (#22637) 2026-11-17 18:53:11 +13:00
J. Nick Koston b5e379a9d4 [uart] Stop ESP8266 software serial TX from tripping the Wi-Fi watchdog at 57600 baud (#22641) 2026-11-17 18:53:11 +13:00
J. Nick Kostonandpre-commit-ci-lite[bot] 05286dfd5d [api] Send queued entity states before DisconnectRequest on shutdown (#22625)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-11-17 18:53:11 +13:00
J. Nick Koston 36184f09aa [zephyr] Count micros() in microseconds and busy-wait in delayMicroseconds() (#22612) 2026-11-17 18:53:11 +13:00
Adam Matthews 449933891e [wifi] Clear the error flag when the adapter restart is skipped (#22797) 2026-11-17 18:53:11 +13:00
Jonathan Swoboda a5bfa6dac3 [esp32_ble] Apply the Bluedroid workarounds to the ESP-IDF 6.1 releases that need them (#22806) 2026-11-17 18:53:11 +13:00
Jonathan Swoboda 5aaa5b0552 [esp32_ble] Replace Bluedroid's sscanf callers on ESP-IDF 6 too (#22805) 2026-11-17 18:53:11 +13:00
J. Nick Koston 9ab090a818 [i2c] Refuse RP2040 writes larger than the Wire buffer instead of leaving the bus stuck (#22791) 2026-11-17 18:53:10 +13:00
Jesse Hills 84079c07e2 Merge pull request #22804 from esphome/bump-2026.11.0b5
2026.11.0b5
2026-11-17 10:27:35 +13:00
J. Nick Koston b7dbf17469 [core] Brace the fast loop check in the unit test main (#22640) 2026-11-17 09:54:53 +13:00
Jesse Hills b91750c325 [tests] Add RawApiClient.read_frame for the serial proxy backpressure test
The serial proxy test from #22687 calls RawApiClient.read_frame, which was
added on dev as part of the store_yaml feature (#16445) and is not on this
release branch. Take tests/integration/raw_api_client.py from that PR so the
test can run; no firmware code changes.
2026-11-17 09:33:39 +13:00
J. Nick Koston 92d2a457fa [epaper_spi] Stop the fast loop after the fill tests (#22638) 2026-11-17 09:00:52 +13:00
Jesse Hills a1fecebb09 Bump version to 2026.11.0b5 2026-11-17 07:30:12 +13:00
J. Nick Koston 32b9d4cbe7 [web_server_base] Bump ESPAsyncWebServer to 3.12.1 (#22682) 2026-11-17 07:30:09 +13:00
Chris c53401a28d [ethernet] Notify IP state listeners from the main loop (#22657) 2026-11-17 07:30:09 +13:00
Miguel Angel Nubla 6b7d17c762 [wifi] Leave the AP before restarting on ESP32 (#22715) 2026-11-17 07:30:09 +13:00
J. Nick Koston 93a3306d82 [libretiny] Free closed TCP connections after about 1 s instead of 120 s (#22696) 2026-11-17 07:30:09 +13:00
J. Nick Koston 54d3477240 [bluetooth_connection] Keep the top half of 32-bit GATT UUIDs on RP2 (#22679) 2026-11-17 07:30:09 +13:00
J. Nick Koston 5f9d83d293 [async_tcp] Use the esphome-libs RPAsyncTCP fork so SSE streams do not stall on RP2040 (#22686) 2026-11-17 07:30:09 +13:00
J. Nick Koston 43864283b4 [web_server_base] Check Basic auth without linking the library's Digest code (#22684) 2026-11-17 07:30:09 +13:00
J. Nick Koston 4efbb38b86 [core] Lock the scheduler against lwIP callbacks on RP2 (#22688) 2026-11-17 07:30:09 +13:00
Keith Burzinski 045374965f [serial_proxy] Keep received bytes when the client's connection is blocked (#22687) 2026-11-17 07:30:09 +13:00
Craig Andrews 39a939720f [epaper_spi] Point the UC8279 gate-count error at the height (#22628) 2026-11-17 07:30:09 +13:00
esphome[bot] a79e51e784 Bump bundled esphome-device-builder to 1.28.1 (#22630)
Co-authored-by: esphome[bot] <115708604+esphome[bot]@users.noreply.github.com>
2026-11-17 07:29:59 +13:00
Chris 517f0d6d48 [usb_host] Respect explicit control transfer size (#22629) 2026-11-17 07:29:14 +13:00
Craig Andrews 1327d0ddc5 [epaper_spi] Mark the frame drawn after fill() (#21505) 2026-11-17 07:29:14 +13:00
J. Nick Koston 2adb544e7a [uart] Stop ESP8266 software serial TX from tripping the Wi-Fi watchdog above 19200 baud (#22603) 2026-11-17 07:29:14 +13:00
J. Nick Koston 48905beb96 [zephyr] Add ISR pin_mode so dht links on nRF52 2026-11-17 07:29:14 +13:00
J. Nick Koston ed401814bf [dht] Negate sign-and-magnitude negative temperatures instead of inverting them (#22615) 2026-11-17 07:29:14 +13:00
J. Nick Koston 0245db6285 [host] Add the empty ISRInternalGPIOPin::pin_mode (#22616) 2026-11-17 07:29:14 +13:00
J. Nick Koston 07ee0f9f04 [logger] Fix LibreTiny task log messages landing unaligned and out of step (#22594) 2026-11-17 07:29:14 +13:00
Jesse HillsandJ. Nick Koston 3d34ad572b [api] Send the platform of each wizard entity (#22580)
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-11-17 07:29:13 +13:00
Jesse Hills b03870b551 Merge pull request #22583 from esphome/bump-2026.11.0b4
2026.11.0b4
2026-11-12 16:26:56 +13:00
Jesse Hills 4a965b8b32 Bump version to 2026.11.0b4 2026-11-12 15:42:05 +13:00
J. Nick Koston d826a19eb1 [esp32_ble] Sort GATT discovery responses by handle for ESP-IDF 5.5.6 and 6.0.3 (#22576) 2026-11-12 15:42:02 +13:00
J. Nick Koston fb54ec51c1 [gpio] Lock interrupts per slot on the one_wire bus (#22452) 2026-11-12 15:42:02 +13:00
J. Nick Koston 04b6c0d4ca [esp32_ble] Keep bond keys when a bonded device re-encrypts on ESP-IDF 5.5.6 (#22559) 2026-11-12 15:42:02 +13:00
J. Nick Koston abf282dd08 [esp32_ble_tracker] Scan at the short window while the wifi AP is running (#22566) 2026-11-12 15:41:58 +13:00
J. Nick Koston e097958ad9 [remote_transmitter] Lock interrupts only near each edge on ESP8266 (#22453) 2026-11-12 15:41:24 +13:00
jabla 8a8ad4d8da [zigbee] Rejoin only after the parent missed several polls (#22405) 2026-11-12 15:41:24 +13:00
J. Nick Koston 09b82388c9 [uart] Lock interrupts per bit in ESP8266 software serial TX at 19200 baud and below (#22450) 2026-11-12 15:41:23 +13:00
J. Nick Koston ea5407925a [wifi] Apply power save when the AP starts without networks (#22564) 2026-11-12 15:41:20 +13:00
J. Nick Koston 97732df3a5 [esp32_ble][ble_device_base][improv_ble] Send advertising as raw packets and keep Improv in the advertising packet (#22499) 2026-11-12 15:40:20 +13:00
Francesco Pace 04482ae0d4 [espectre] Update to SDK 3.2.0 (#22570) 2026-11-12 15:40:20 +13:00
Clyde Stubbs ca0dd8e292 [mipi_dsi] Keep the panel running while flash is written (#22535) 2026-11-12 15:40:20 +13:00
J. Nick Koston e75ac64cc9 [esp8266] Skip other devices' known mDNS answers without allocating (Arduino core 3.1.2-esphome.4) (#22533) 2026-11-12 15:40:20 +13:00
PolarGooseandJ. Nick Koston 212c0c1ea4 [dsmr] Update dsmr_parser to 1.11.0 (#22530)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-12 15:40:20 +13:00
Jonathan Swoboda 3e2f9bf296 [ota] Skip the auth request when the password is empty at run time (#22485) 2026-11-12 15:40:20 +13:00
J. Nick Koston b997866e86 [esp32_ble_server] Size the BLE2902 value buffer to its 2 byte value (#22454) 2026-11-12 15:40:20 +13:00
J. Nick Koston ae89db98e4 [core] Inline InterruptLock on ESP8266 (#22455) 2026-11-12 15:40:19 +13:00
Kevin Ahrendt e9bb102c1f [sendspin] Add bits_per_sample to the media source (#22313) 2026-11-12 15:40:19 +13:00
Jesse Hills 26c4f8d40e Merge pull request #22442 from esphome/bump-2026.11.0b3
2026.11.0b3
2026-11-09 14:04:52 +13:00
Jesse Hills c097fe388e Bump version to 2026.11.0b3 2026-11-09 13:36:04 +13:00
J. Nick Koston 21267d7421 [libretiny] Interrupt on both edges for any edge pins on RTL8710B (#22403) 2026-11-09 13:36:03 +13:00
J. Nick Koston 582adc950a [libretiny] Run millis(), micros() and delays on real time on RTL8710B (#22404) 2026-11-09 13:36:03 +13:00
J. Nick Koston 613319f984 [i2c] Mask I2C interrupts after an error on classic ESP32 (#22396) 2026-11-09 13:36:02 +13:00
J. Nick Koston 4ad3cc7c0e [light] Keep power estimation state in codegen static storage (#22370) 2026-11-09 13:36:02 +13:00
J. Nick Koston a033260639 [libretiny] Read pins in interrupts without detaching the interrupt on Realtek (#22400) 2026-11-09 13:36:02 +13:00
24f23ba3db [i2s_audio] Fix APLL clock source on ESP32-P4 (#22402)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-11-09 13:36:02 +13:00
Roman PriesolandJ. Nick Koston 674d593f75 [wifi] Create the IPv6 link-local through lwIP on connect (#22364)
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-11-09 13:36:02 +13:00
Jonathan Swoboda c1771e002b [ld2410][ld2412][ld2420] Drop device classes from unitless gate and light entities (#22374) 2026-11-09 13:36:02 +13:00
Jonathan Swoboda 5529e87a40 [tsl2591][seeed_mr24hpc1] Drop device classes from unitless sensors (#22375) 2026-11-09 13:36:02 +13:00
J. Nick Koston 54cae78a42 [ht16k33_char] Name the I2C bus in the component test (#22372) 2026-11-09 13:36:02 +13:00
J. Nick Koston e77a3bc54d [core] Add cg.static_buffer for config-sized static buffers (#22326) 2026-11-09 13:36:02 +13:00
guillempages af7f95a01b [ht16k33] Rename display_off method (#22352) 2026-11-09 13:36:02 +13:00
daf48ce4f2 [vl53l0x] Recover from a failed I2C read instead of stalling (#19235)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: Tekla Bania <[EMAIL]>
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Signed-off-by: Tekla Bania <8668038+teklabania@users.noreply.github.com>
Signed-off-by: Tekla Bania <[EMAIL]>
2026-11-09 13:36:02 +13:00
Jesse Hills 3cfe8231c7 Merge pull request #22320 from esphome/bump-2026.11.0b2
2026.11.0b2
2026-11-06 15:38:06 +13:00
Keith BurzinskiandClaude Fable 5.1 59c3dd35c0 [nfc] Fix out-of-bounds read in NDEF record parsing (#22276)
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-06 14:32:54 +13:00
Jesse Hills 1ff084be84 Bump version to 2026.11.0b2 2026-11-06 14:11:43 +13:00
Dckiller 041da28d53 [xiaomi_body_scale] Handle the S400 Pro 0x7FF no-weight marker (#22317) 2026-11-06 14:11:42 +13:00
J. Nick Koston 27a724c157 [mqtt] Keep retained messages from overflowing the ESP32 event queue at connect (#22248) 2026-11-06 14:11:42 +13:00
Jesse Hills 5f62432ef0 [api] Let components give wizard entities a stable role (#22295) 2026-11-06 14:11:42 +13:00
Jonathan Swoboda 21fb3c4791 [sun] Pick the next sunrise or sunset from the right day for any longitude (#22308) 2026-11-06 14:11:42 +13:00
tomaszduda23andClaude ebeb3774d3 [nrf52] Download the pinned nrfutil launcher by its versioned file name (#22314)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-06 14:11:41 +13:00
J. Nick Koston 3bb0bc104b [esp32_ble] Silence the PACKED redefined warning from Bluedroid's private headers (#22296) 2026-11-06 14:11:41 +13:00
Jonathan Swoboda a9e3e32382 [esp32_hosted] Bump esp_hosted to 3.1.0 and fix the host restart after a coprocessor OTA (#22306) 2026-11-06 14:11:41 +13:00
J. Nick Koston e3816ac4bb [wifi] Retry at once when a scan leaves no hidden network to try (#21747) 2026-11-06 14:11:41 +13:00
J. Nick Koston e8415cdd87 [web_server_base] Apply the web server's allowed origins check to every handler (#21972) 2026-11-06 14:11:41 +13:00
J. Nick Koston b8e1699137 [wifi] Treat open networks as open in RTL87xx scan results (#21750) 2026-11-06 14:11:41 +13:00
J. Nick Koston b5fbd12b00 [wifi] Ignore the scan inside a join on RTL87xx (#21749) 2026-11-06 14:11:41 +13:00
J. Nick Koston 0acba6cc48 [wifi] Log why a join failed on RTL87xx (#21751) 2026-11-06 14:11:41 +13:00
J. Nick Koston 485b7cc4a2 [schema] Keep sibling extends when shrink inlines one schema (#22287) 2026-11-06 14:11:41 +13:00
J. Nick Koston 9a357ca9f3 [libretiny] Record abort() as a crash and reboot (#22288) 2026-11-06 14:11:41 +13:00
J. Nick Koston b9f598ff71 [core] Keep a trigger's only extra key in the language schema (#21801) 2026-11-06 14:11:41 +13:00
J. Nick Koston 183065c351 [mqtt] Cap incoming message size with max_payload_size (#22278) 2026-11-06 14:11:41 +13:00
Jonathan Swoboda 49ee4914ce [docker] Bump base image to 2026.11.0 (#22275) 2026-11-06 14:11:41 +13:00
dependabot[bot] d9dca1adf8 Bump zeroconf from 0.152.0 to 0.153.0 (#22273)
Signed-off-by: dependabot[bot] <support@github.com>
2026-11-06 14:11:41 +13:00
fb4c241bf4 [sm2135] Fix light turning off when switching color modes (#19438)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-06 14:11:41 +13:00
J. Nick Koston bfb9ca984c [logger] Report the RP2 crash record when a host opens the USB port (#22266) 2026-11-06 14:11:41 +13:00
J. Nick Koston 8d6fb44dd6 [mdns] Bump espressif/mdns to 1.15.0 (#22267) 2026-11-06 14:11:41 +13:00
J. Nick Koston ca12f6e3f3 [rp2040_pio_led_strip] Compute the PIO clock divider with its fraction (#22265) 2026-11-06 14:11:36 +13:00
J. Nick Koston 0721604da4 [rp2040_pio_led_strip] Size the DMA channel arrays for RP2350 (#22153) 2026-11-06 14:05:23 +13:00
J. Nick Koston 849aef0c10 [rp2040_pio_led_strip] Fail setup instead of panicking when no state machine or DMA channel is free (#22152) 2026-11-06 14:03:53 +13:00
J. Nick Koston 8ea8cacd95 [tfluna] Drop signal_strength device class from the signal strength sensor (#22260) 2026-11-06 14:03:53 +13:00
J. Nick Koston 5e15fef5a8 [core] Dump typed_schema types that have no keys of their own (#22258) 2026-11-06 14:03:53 +13:00
J. Nick Koston 0164f1a431 [ld2410][ld2412] Drop signal_strength device class from the gate threshold numbers (#22259) 2026-11-06 14:03:53 +13:00
J. Nick Koston 8ad61941f8 [esp32_ble] Fix build on Windows when Bluedroid's private headers are not reachable (#22257) 2026-11-06 14:03:52 +13:00
bff389208f [deep_sleep] Fix ESP32-P4 deep sleep (#22246)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-11-06 14:03:52 +13:00
Jonathan Swoboda 3ae0a0174b [bme280_base][bmp280_base] Compensate raw 0x80000 when the channel is enabled (#22236) 2026-11-06 14:03:52 +13:00
psewar 4f0b216b55 [voice_assistant] Do not treat "playback has not started" as "playback finished" (#19408) 2026-11-06 14:03:52 +13:00
Jesse Hills 49f3133c4f Merge pull request #22247 from esphome/bump-2026.11.0b1
2026.11.0b1
2026-11-04 22:32:37 +13:00
J. Nick Koston 6c8c105449 [bme68x_bsec2] Share BSEC test double types with bme680_bsec to fix the all-components C++ unit test build (#22245) 2026-11-04 16:08:58 +13:00
Jesse Hills 9a5a8f9822 Bump version to 2026.11.0b1 2026-11-04 14:20:07 +13:00
J. Nick Koston 9dea935499 [web_server_base] Count the HTTP server's sockets in one place (#21971) 2026-11-04 13:50:59 +13:00
J. Nick Koston 2d73971fcc [web_server_idf] Send a default header once when a response sets it (#21974) 2026-11-03 18:28:29 -06:00
J. Nick Koston 5d511a1bd1 [sim800l] Pass callback strings by const reference (#22203) 2026-11-03 18:17:08 -06:00
14b190ab8f [esp32_rmt] Check that RMT components fit the chip's RMT channels (#22172)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-03 18:11:19 -06:00
J. Nick Koston c50a5a0879 [core] Give apply action lambdas their arguments by value again (#22011) 2026-11-04 13:02:32 +13:00
J. Nick Koston 75b9f8de1c [esp32_ble_client] Ignore a disconnect event from the previous link during a new connection (#21918) 2026-11-04 12:59:16 +13:00
J. Nick Koston 7637cdc162 [web_server] Keep a custom js_url/css_url on AP only WiFi (#21879) 2026-11-04 12:58:34 +13:00
J. Nick Koston 891ebdaaaa [espota2] Make the probe deadline test deterministic (#22234) 2026-11-03 17:50:38 -05:00
J. Nick Koston a01b213ab4 [bme68x_bsec2] Add unit tests for publishing readings (#22189) 2026-11-03 17:49:42 -05:00
J. Nick Koston a21268f641 [bme680_bsec] Add unit tests for publishing readings (#22190) 2026-11-03 17:49:13 -05:00
J. Nick Koston 7813ea1c7f [sim800l] Add integration test for the on_* automation arguments (#22202) 2026-11-03 17:48:31 -05:00
J. Nick Koston 82a375907d [xl9535] Use update_register and status_comm_result for pin access (#22217) 2026-11-03 17:47:13 -05:00
J. Nick Koston 9591e34722 [lps22] Use update_register for the one-shot trigger (#22219) 2026-11-03 17:46:18 -05:00
J. Nick Koston 408bd8820a [cap1188] Use update_register and check the touch status read (#22220) 2026-11-03 17:45:32 -05:00
J. Nick Koston 07a175692a [components] Replace local byte-order write helpers with put_be and put_le (#22212) 2026-11-03 22:14:32 +00:00
J. Nick Koston 94d0113f66 [core] Add put_be and put_le helpers to write integers into byte buffers (#22211) 2026-11-03 16:02:02 -06:00
09d3b645a3 [i2s_audio] Fix sample-rate-dependent microphone DC correction (#22130)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-11-03 21:45:41 +00:00
Adam Matthews 940f87056d [cse7766] Log the clamped power factor and reactive power at verbose level (#22224) 2026-11-03 14:00:28 -06:00
dependabot[bot] 6f284d171a Bump docker/setup-buildx-action from 4.4.0 to 4.4.1 in the docker-actions group (#22229)
Signed-off-by: dependabot[bot] <support@github.com>
2026-11-03 13:48:16 -06:00
dependabot[bot] a7a4473b32 Bump filelock from 4.2.4 to 4.2.6 (#22228)
Signed-off-by: dependabot[bot] <support@github.com>
2026-11-03 13:48:06 -06:00
dependabot[bot] 8092a23553 Bump pytest-codspeed from 5.0.3 to 5.0.4 (#22227)
Signed-off-by: dependabot[bot] <support@github.com>
2026-11-03 13:47:57 -06:00
dependabot[bot] 1a260e4c57 Bump zeroconf from 0.151.5 to 0.152.0 (#22226)
Signed-off-by: dependabot[bot] <support@github.com>
2026-11-03 13:47:48 -06:00
dependabot[bot] 8a30af4ad1 Bump platformdirs from 4.14.0 to 4.14.2 (#22225)
Signed-off-by: dependabot[bot] <support@github.com>
2026-11-03 13:47:41 -06:00
cad297866f [speaker] Reduce startup buffering for announcements (#21091)
Co-authored-by: andytrofimov <26643796+andytrofimov@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-03 14:04:36 -05:00
Petapton ff254ae9d8 [daikin_madoka] Add new Daikin Madoka integration (#5951) 2026-11-03 16:00:39 +00:00
J. Nick Koston f5ab5febb4 [wifi] Keep manual IP settings in flash (#21708) 2026-11-02 16:39:40 -10:00
J. Nick Koston 3d95a0ba33 [libretiny] Report the previous boot's crash on RTL8710B (#21752) 2026-11-02 16:39:17 -10:00
J. Nick Koston d8bfae306f [core] Add AutomationList for hubs that trigger their own automations (#21788) 2026-11-02 16:38:22 -10:00
J. Nick Koston 78d2fdbfc0 [wifi] Keep scans working after a join with a BSSID on RTL87xx (#21754) 2026-11-02 16:37:33 -10:00
J. Nick Koston 4af8e50dca [ai] Point reviewers at existing helpers (#22178) 2026-11-02 21:24:24 -05:00
J. Nick Koston 93d00b5920 [rx8111] Keep the scheduled event poll out of the unit tests (#22179) 2026-11-02 21:24:03 -05:00
J. Nick Koston 3d4e20f574 [components] Build enum options with options(prefix=) in ld600x and rx8111 (#22180) 2026-11-02 21:23:22 -05:00
J. Nick Koston be3113e7d5 [m5stack_unit_bldc] Declare child entities with the SUB_* macros (#22181) 2026-11-02 21:23:02 -05:00
J. Nick Koston e236c741db [core] Add setup_check() (#22177) 2026-11-02 21:22:44 -05:00
iskyguy ed4db4b20e [sht4x] Expose serial number as a text sensor (#22176) 2026-11-02 14:20:42 -10:00
iskyguy 51db039f59 [sht4x] Increase serial number response wait to 10 ms (#22183) 2026-11-02 13:45:30 -10:00
dependabot[bot] a24b994a5e Bump esphome/workflows/.github/workflows/lock.yml from 2026.10.2 to 2026.10.3 (#22168)
Signed-off-by: dependabot[bot] <support@github.com>
2026-11-02 16:05:58 -06:00
dependabot[bot] 912e9dedae Bump esphome/workflows/.github/workflows/stale.yml from 2026.10.2 to 2026.10.3 (#22169)
Signed-off-by: dependabot[bot] <support@github.com>
2026-11-02 16:05:44 -06:00
dependabot[bot] 47a526d35c Bump astral-sh/setup-uv from 10.3.2 to 10.3.3 in /.github/actions/restore-python (#22167)
Signed-off-by: dependabot[bot] <support@github.com>
2026-11-02 15:40:35 -06:00
Jesse Hills 389e782e78 Merge branch 'release' into dev 2026-11-03 10:30:47 +13:00
Jesse Hills 9a78022ded Merge pull request #22174 from esphome/bump-2026.10.2
2026.10.2
2026-11-03 10:30:22 +13:00
Jesse Hills c11c788d25 Revert "[lvgl] Make a scrollable container automatically clickable (#22094)"
This reverts commit 8e87cfc17e.
2026-11-03 10:11:19 +13:00
Clyde Stubbs d516fd5c92 [http_request] Fix macOS host build with the precompiled header (#21705) 2026-11-03 10:00:14 +13:00
Clyde StubbsandClaude 8e87cfc17e [lvgl] Make a scrollable container automatically clickable (#22094)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-03 09:59:38 +13:00
Jesse Hills f0c4dc67e7 Bump version to 2026.10.2 2026-11-03 09:51:12 +13:00
J. Nick Koston 863cb54982 [ota] Work around the LibreTiny OTA issue that bricks RTL8710B on a compressed update (#22111)
Squash of #22111 for the release branch, with the conflicts resolved:
release has no UpdateLock in the LibreTiny OTA backend, so abort() has no
lock check and a successful end() clears wrote_; release negotiates inline
in perform_ota(), so the RTL8710B check is made there.
2026-11-03 09:50:22 +13:00
J. Nick Koston 64b621f8f1 [bluetooth_proxy] Release held connections when a new client replaces the subscriber (#22077) 2026-11-03 09:43:51 +13:00
Jonathan Swoboda 7d29bdf177 [host] Offer the built program as a download in the Device Builder (#22114) 2026-11-03 09:43:51 +13:00
J. Nick Koston 86a0cdfb7a [core] Start the Apple Silicon cc1plus wrapper through sh when the Python path has a space (#21967) 2026-11-03 09:43:51 +13:00
cf5519615a [esp32][audio_http] Keep TLS 1.3 working (#21786)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-03 09:43:51 +13:00
dependabot[bot] 741310ef30 Bump prek from 0.5.7 to 0.5.9 (#22165) 2026-11-02 10:43:23 -10:00
dependabot[bot] f96c0c7d0e Bump CodSpeedHQ/action from 5.6.0 to 5.6.1 (#22166) 2026-11-02 10:40:54 -10:00
dependabot[bot] b18b7fe7a1 Bump astral-sh/setup-uv from 10.3.2 to 10.3.3 (#22170) 2026-11-02 10:40:34 -10:00
Jesse HillsandJ. Nick Koston 6ea4ed0868 [CI] Adopt gh actions-lock for workflow action pinning (#22138)
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-11-03 08:50:25 +13:00
Jesse Hills a78a80c0d1 [epaper_spi] Fix SSD1681 partial updates alternating between two images (#22145) 2026-11-03 07:01:17 +13:00
Jakub SztanderaandJ. Nick Koston 4206de5ed0 [ledc] Correct PWM duty scaling (#22160)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-02 11:04:48 -06:00
J. Nick Koston ae54e8b696 [esp32_ble] Parse Bluedroid hex strings without sscanf (#22081) 2026-11-02 09:23:36 -06:00
J. Nick Kostonandpre-commit-ci-lite[bot] b252c90a5b [api] Add tests for Home Assistant state subscriptions (#22155)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-11-02 09:39:21 -05:00
J. Nick Koston d68674597e [const] Move shared charger config keys to components/const (#22161) 2026-11-02 09:34:38 -05:00
J. Nick Koston 57a5e54118 [uptime] Keep the text sensor format in flash (#22147) 2026-11-02 09:34:00 -05:00
J. Nick Koston 69d96a4707 [ota] Work around the LibreTiny OTA issue that bricks RTL8710B on a compressed update (#22111) 2026-11-02 04:33:18 -10:00
J. Nick Koston 52fedcbe97 [components] Log byte dumps with format_hex_pretty_to (#22149) 2026-11-02 09:01:31 -05:00
J. Nick Koston d2b635cd92 [uptime] Add unit tests for the uptime text sensor format (#22146) 2026-11-02 09:00:36 -05:00
J. Nick Koston 6d5305f1fe [ci] Show why a C++ unit test build raised (#22140) 2026-11-02 09:00:16 -05:00
esphome[bot] 354660cafc [ci] Refresh integration test durations (#22150) 2026-11-01 19:54:11 -10:00
chunckus-aurelius e5f6dbe6bf [motion] Add shared tap and double tap support (#22144) 2026-11-02 16:35:11 +11:00
Giorgio Aresu ab95d504fa [mipi_rgb] Update pins for ZX3D95CE01S-TR-4848 (#22134) 2026-11-02 11:55:40 +11:00
Francesco Pace 2c5cb6b063 [espectre] Update to SDK 3.1.0; add runtime config entities and CSI diagnostics (#22132) 2026-11-01 13:29:40 -10:00
Jesse Hills 23e66187a0 [epaper_spi] Add Good Display GDEY029T94 2.9" model (#22128) 2026-11-02 12:18:13 +13:00
esphome[bot] acaf582bf6 Bump aioesphomeapi from 46.25.0 to 46.25.1 (#22137) 2026-11-01 22:59:41 +00:00
2019ebb49f [ht16k33_char] Add support for HT16K33 based character displays (#8520)
Co-authored-by: Djordje Mandic <6750655+DjordjeMandic@users.noreply.github.com>
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-01 12:38:23 -10:00
J. Nick Koston dddacfa239 [libretiny] Flag a BK7238 board layout its bootloader will not apply updates from (#21743) 2026-11-01 12:16:26 -10:00
Ardumine 174016df57 [udp] Add Zephyr/nRF52 IPv6 support (#17838) 2026-11-01 12:15:21 -10:00
J. Nick Koston 4d50e1ba22 [bluetooth_proxy] Release held connections when a new client replaces the subscriber (#22077) 2026-11-01 12:04:02 -10:00
J. Nick Koston 956a633c48 [core] Explain a failed clone of a missing or private repository (#22074) 2026-11-01 12:03:44 -10:00
J. Nick Koston 8a62328276 [core] Let module platforms inherit their component's FILTER_SOURCE_FILES (#22072) 2026-11-01 12:03:27 -10:00
J. Nick Koston 041979d406 [core] Move owning_args from nextion into automation (#21893) 2026-11-01 17:02:44 -05:00
J. Nick Koston 956fff4b44 [my9231][sm16716] Reject channels past num_channels (#21855) 2026-11-01 12:02:31 -10:00
J. Nick Koston 415eb22a2c [output] Let final_validate_unique_channel check a hub's channel count (#21854) 2026-11-01 12:02:31 -10:00
J. Nick Koston eec1a0a690 [core] Add StringRef::find for std::string and StringRef needles (#21895) 2026-11-01 12:02:00 -10:00
J. Nick Koston a4ed37bd79 [canbus] Add an integration test for on_frame filtering (#21792) 2026-11-01 17:00:08 -05:00
J. Nick Koston 9317c021f5 [interval] Compile the startup delay out of intervals that don't use it (#21799) 2026-11-01 16:59:52 -05:00
J. Nick Koston 84b4ffeddb [binary_sensor] Put the settle filter flag in the base class padding (#21800) 2026-11-01 16:58:57 -05:00
J. Nick Koston 3ac882b097 [sensor] Test delta filter with min and max together and a percentage max (#21812) 2026-11-01 16:58:23 -05:00
J. Nick Koston 4027857ab2 [cst816][ft5x06] Remove unused button listener declarations (#22065) 2026-11-01 16:52:35 -05:00
J. Nick Koston c16f6d21ef [sdp3x] Print the model once in dump_config and quiet the runtime logs (#22045) 2026-11-01 16:49:18 -05:00
J. Nick Koston 730dda3d54 [components] Publish child entities guarded by a bare pointer check with PUBLISH_STATE (#22082) 2026-11-01 21:48:54 +00:00
J. Nick Koston 7ed387b660 [thermostat] Build triggers, settings and mode checks from tables (#22050) 2026-11-01 16:48:07 -05:00
J. Nick Koston ae0850f159 [components] Declare entity pointers with the SUB_* macros (#22051) 2026-11-01 16:47:33 -05:00
J. Nick Koston bfb4ad7b02 [ade7880] Build the channels from a table in code generation (#22076) 2026-11-01 16:44:25 -05:00
J. Nick Koston b76f491eef [core] Add tests for component.update, suspend and resume codegen (#21985) 2026-11-01 16:38:35 -05:00
J. Nick Koston 0ac52f42ad [core] Add tests for how apply actions call user lambdas (#22007) 2026-11-01 16:38:23 -05:00
J. Nick Koston 481b39787f [api] Add tests for user service code generation (#22009) 2026-11-01 16:38:07 -05:00
J. Nick Koston fd0ca9316a [mqtt] Add tests for mqtt.publish_json code generation (#22025) 2026-11-01 16:37:52 -05:00
J. Nick Koston f60abbf84f [components] Publish the remaining child entities with PUBLISH_STATE (#22079) 2026-11-01 16:36:42 -05:00
J. Nick Koston e4715443b0 [components] Add tests for the touchscreen key binary sensors (#22063) 2026-11-01 16:35:47 -05:00
J. Nick Koston 5ebf08d70e [thermostat] Add tests pinning validation messages and codegen order (#22049) 2026-11-01 16:35:08 -05:00
J. Nick Koston 3a5cbb423c [light] Use cg.add_optional for optional setters in cwww, rgbww and tuya (#22048) 2026-11-01 16:34:52 -05:00
J. Nick Koston 87b7205397 [thermopro_ble] Add parser unit tests (#22047) 2026-11-01 16:34:32 -05:00
J. Nick Koston d85b41be44 [script] Add tests for script code generation and synchronous scripts (#22036) 2026-11-01 16:34:08 -05:00
J. Nick Koston efe7a5a7de [binary_sensor] Add tests for the click and double click triggers (#22031) 2026-11-01 16:33:51 -05:00
J. Nick Koston 12ae7a2487 [api] Add tests pinning homeassistant.action and event code generation (#22030) 2026-11-01 16:33:35 -05:00
J. Nick Koston 2bf52e72ec [tmp102][packet_interface] Use the global App in the test fixtures (#22083) 2026-11-01 16:31:59 -05:00
J. Nick Koston df519ca14c [pipsolar] Publish an unknown state instead of a bogus value for missing fields (#22084) 2026-11-01 16:31:34 -05:00
J. Nick Koston c22f1d64c5 [components] Use the global App in the remaining test fixtures (#22085) 2026-11-01 16:29:41 -05:00
J. Nick Koston f3c828b71f [socket] Size Zephyr's poll table from the socket budget (#22089) 2026-11-01 16:29:11 -05:00
J. Nick Koston 506cafd7ef [core] Build the follow entity publish statement from codegen expressions (#22103) 2026-11-01 16:24:02 -05:00
Jesse Hills 5c780ed5f5 [mipi_spi] Remove redundant pca9554 requires from Waveshare SPD2010 model (#22125) 2026-11-02 10:19:26 +13:00
Jonathan Swoboda 19ea009546 [host] Offer the built program as a download in the Device Builder (#22114) 2026-11-01 15:25:54 -05:00
Jonathan Swoboda 4219a48408 [host] Add use_address so OTA and logs can reach a host device (#22115) 2026-11-01 15:25:17 -05:00
tomaszduda23andClaude 2cdcdd82f8 [nrf52] Deprecate framework versions older than 2.9.2 (#22122)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-01 21:11:26 +01:00
Craig AndrewsandScott Gusler 45116a8f3e [epaper_spi] - Add support for the XSRUPB-7.5in-bwr panel (#19654)
Co-authored-by: Scott Gusler <812172+mutilator@users.noreply.github.com>
2026-11-02 07:06:34 +11:00
tomaszduda23andClaude 3bd76e1176 [nrf52] Warn when the Adafruit bootloader is older than 0.11.0 (#22119)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-01 21:01:22 +01:00
tomaszduda23andClaude dc324dd2cb [nrf52][zephyr] Fix building LVGL on nRF52 (#21554)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-01 21:00:34 +01:00
Jesse Hills e5e068ff20 [mipi_spi] Add generic SPD2010 model and SenseCAP Watcher board (#21354) 2026-11-02 08:56:23 +13:00
Clyde StubbsandClaude 0548ad7a72 [lvgl] Make a scrollable container automatically clickable (#22094)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-01 08:47:34 -10:00
Giorgio Aresu 27aa91bb9d [mipi_rgb] Add GC9503V and ZX3D95CE01S-TR-4848 (#21588) 2026-11-01 20:19:31 +11:00
Remco van Essenandclydebarrow 7ae4ff99ce [runtime_image] Decode progressive and SOF1 JPEGs with JPEGDEC (#21784)
Co-authored-by: clydebarrow <2366188+clydebarrow@users.noreply.github.com>
2026-11-01 20:08:43 +11:00
Mark Dietzer 36c666c8a9 [usb_host] Size the USB FIFO for periodic packets on the ESP32-P4 (#21739) 2026-10-31 18:24:20 -10:00
J. Nick Koston bf86c11e44 [lis3dh][esp32_hosted] Move CONF_ACTIVE_HIGH to the shared component constants (#22088) 2026-10-31 17:48:18 -10:00
chunckus-aurelius e5f2060262 [lis2dw12][msa3xx] Move the tap constants to the shared component constants (#22087) 2026-10-31 17:08:19 -10:00
ishai-levy 107a573ffb [es8388] Add configurable ADC PGA gain (#21363) 2026-10-31 17:07:23 -10:00
david-collett d902d1e84f [esp32_ble_server] Add secure connection support (#17562) 2026-10-31 17:05:56 -10:00
andytrofimov da6ab5ec1e [audio] Release partial HTTP audio reads during synthesis gaps (#21090) 2026-10-31 17:02:13 -10:00
Jeff Brown e8fe6984b7 [light] Tidy up addressable light setup (#22078) 2026-10-31 15:38:15 -10:00
William HowellandJ. Nick Koston d4d3df819c [fujitsu_general] Add buttons for the vane step and economy commands (#14271)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-01 00:25:22 +00:00
Clyde Stubbs fc921d0a96 [rtttl] Fade speaker notes in and out to stop clicks (#22075) 2026-11-01 11:25:09 +11:00
Clyde Stubbs 910c42a8bc [mipi_dsi] fix fill(), minimise DMA underruns (#21638) 2026-11-01 11:06:37 +11:00
fea23e7dec [light] Refactor ESPColorView and related types (#21577)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-31 13:59:23 -10:00
Clyde Stubbs 76912c3a9b [rtttl] Build speaker samples from a sine table (#22073) 2026-11-01 10:58:16 +11:00
195749fb02 [ledc] Add hardware duty dithering for supported ESP32 variants (#21320)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-31 13:54:32 -10:00
J. Nick Koston cc65a82a1e [components] Turn platform packages with only __init__.py into modules (#22061) 2026-10-31 13:24:00 -10:00
4a16cf1783 [m5stack_unit_bldc] Add M5Stack M5Unit-BLDC platform support (#18086)
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-31 13:22:11 -10:00
9dd043160a [rtttl] Build speaker samples in single precision (#22059)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-31 13:21:03 -10:00
J. Nick Koston 62264c9695 [ms8607] Use the global App in the lifecycle test (#22071) 2026-10-31 13:09:10 -10:00
90e3f57adb Bump aioesphomeapi from 46.24.0 to 46.25.0 (#22046)
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: bdraco <663432+bdraco@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-31 11:47:00 -10:00
Greg CormierandJ. Nick Koston c81754be78 [xgzp68xx] Add XGZP6899DC variant (#21779)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-31 10:01:44 -10:00
ccf437271e [ms8607] Fix a crash without a humidity sensor and skip unconfigured readings (#16487)
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-31 09:56:46 -10:00
dependabot[bot] 63d2800aae Bump pytest from 9.1.1 to 9.2.0 (#22040)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-31 19:54:56 +00:00
dependabot[bot] 942ca93b6d Bump platformdirs from 4.13.6 to 4.14.0 (#22042)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-31 19:54:53 +00:00
dependabot[bot] bb05854474 Update tzdata requirement from >=2026.5 to >=2026.6 (#22041)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-31 19:54:31 +00:00
Mikkel Jeppesen 5f5a81434d [panasonic_ir] Add Panasonic AC IR climate component (#21631) 2026-10-31 07:02:55 -10:00
Jonathan Swoboda b576063d15 [ethernet] Bump ESP-IDF ethernet driver components (#21982) 2026-10-31 10:25:11 -04:00
J. Nick Koston c1a068220f [core] Add tests for on_boot code generation and ordering (#21988) 2026-10-31 08:47:46 -04:00
J. Nick Koston 9aceee001e [display] Add tests for display.page.show code generation (#21995) 2026-10-31 08:47:13 -04:00
J. Nick Koston 176ab8433e [deep_sleep] Add tests for deep_sleep.enter code generation (#21997) 2026-10-31 08:46:31 -04:00
J. Nick Koston b6460a1904 [light] Add tests for dim_relative and effect next/previous code generation (#21999) 2026-10-31 08:46:12 -04:00
J. Nick Koston 05949b7e3a [remote_base] Add tests for transmit_raw and rc_switch transmit code generation (#22000) 2026-10-31 08:45:49 -04:00
John 1f70f86b47 [atm90e32] Add configurable thresholds (#15244) 2026-10-30 22:50:06 -10:00
c50d09ee1d [atm90e32] Verify gain calibration writes (#18731)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-30 22:05:01 -10:00
Rick van Hattem e87e7abbcd [ld6004] Add switch platform (#19845) 2026-10-30 19:45:28 -10:00
Rick van Hattem f60408208e [ld6004] Add number platform (#19843) 2026-10-30 19:35:36 -10:00
Rick van Hattem 1d94b351ff [ld6004] Add button platform (#19846) 2026-10-31 05:16:37 +00:00
esphome[bot] 563ba82a95 Bump aioesphomeapi from 46.23.0 to 46.24.0 (#21983) 2026-10-30 19:14:17 -10:00
Rick van Hattem 7995cecca9 [ld6004] Add select platform (#19844) 2026-10-30 19:09:37 -10:00
Clyde StubbsandClaude Opus 5.5 d47582b0c9 [core] Generate if, choose, while and repeat as C++ control flow (#21980)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 15:53:33 +11:00
Clyde StubbsandClaude Opus 5.5 3a0520245d [core] Run callback automations directly when every action is inline (#21979)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 15:53:33 +11:00
Clyde StubbsandClaude Opus 5.5 ea40fba54e [core] Merge adjacent simple actions into one generated function (#21978)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 15:53:33 +11:00
2563605fe7 [ld6004] Add text_sensor platform (#19842)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-30 18:03:18 -10:00
J. Nick Koston 96dc1fbaf3 [sm10bit_base] Clean up the driver base (#21843) 2026-10-30 17:41:53 -10:00
7ee82fbc90 [ld6004] Add sensor platform (#19841)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-30 17:40:09 -10:00
J. Nick Koston c82e275eee [sensor][binary_sensor] Pin the output of stateless sensor filters and binary sensor delay filters (#21828) 2026-10-30 23:24:40 -04:00
J. Nick Koston f999c4ed1b [ruuvitag][atc_mithermometer][pvvx_mithermometer][thermopro_ble] Publish optional parse results with publish_optional (#21924) 2026-10-30 23:20:49 -04:00
J. Nick Koston 867b51941c [components] Use PROGMEM_STRING_TABLE for pressure sensor oversampling and filter names (#21931) 2026-10-30 23:20:27 -04:00
J. Nick Koston 1297771d5b [gcja5] Do not publish frames that fail the checks (#21936) 2026-10-30 23:19:18 -04:00
J. Nick Koston fe0e67bdd7 [xiaomi] Publish optional parse results with publish_optional in the plant, motion and other sensors and binary sensors (#21946) 2026-10-30 23:18:33 -04:00
0af702a0af [ld6004] Add Hi-Link LD6004 radar with binary_sensor platform (#19840)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-30 17:05:22 -10:00
J. Nick Koston 09d8477557 [xiaomi] Publish optional parse results with publish_optional in the thermometers (#21923) 2026-10-30 16:03:16 -10:00
J. Nick Koston bb458503c9 [core] Add publish_optional for optional entity values (#21921) 2026-10-30 16:03:16 -10:00
J. Nick Koston c01bc17bc8 [cm1106] Drop the duplicate helpers.h include (#21976) 2026-10-30 15:26:31 -10:00
Rick van Hattem 135943911b [ld600x] Share platform schemas and code generation with ld6002b (#19839) 2026-10-30 15:17:08 -10:00
J. Nick Koston 3870ca0031 [output] Use ApplyButton for the output button (#21907) 2026-10-30 14:44:54 -10:00
J. Nick Koston e5871655b2 [mitsubishi_cn105] Make the unit tests build with Apple clang (#21900) 2026-10-30 14:21:38 -10:00
J. Nick Koston a5b6c69201 [hte501][tee501] Check I2C transfer results (#21929) 2026-10-30 14:21:25 -10:00
J. Nick Koston c08aff9300 [bp5758d] Keep the channel values in fixed arrays (#21905) 2026-10-30 14:20:24 -10:00
J. Nick Koston f6fc942c4c [network] Fix inet_ntop link failure on Zephyr (#21909) 2026-10-30 14:19:48 -10:00
J. Nick Koston 7d750279ef [components] Add parser tests for a01nyub, a02yyuw, jsn_sr04t, gcja5, pm1006 and sds011 (#21920) 2026-10-30 19:53:45 -04:00
J. Nick Koston 2b0bcf646e [output] Let final_validate_unique_channel take the channel key (#21899) 2026-10-30 19:53:09 -04:00
J. Nick Koston 2913537baf [ota] Add tests for the OTA on_* automations (#21902) 2026-10-30 19:52:18 -04:00
J. Nick Koston ba25efc791 [uart] Use ApplyButton for the UART button (#21906) 2026-10-30 19:49:52 -04:00
J. Nick Koston 0f1192feb2 [components] Declare child entities with SUB_* macros (4/8) (#21773) 2026-10-30 19:47:55 -04:00
J. Nick Koston 02c4512749 [ezo] Add tests for the command text, reply callbacks and address change (#21865) 2026-10-30 19:47:09 -04:00
J. Nick Koston ad7d246a45 [syslog] Pack the settings into one word (#21896) 2026-10-30 19:46:22 -04:00
J. Nick Koston 89360efb38 [hte501][tee501] Decode temperature as a signed 16-bit value (#21930) 2026-10-30 19:43:04 -04:00
J. Nick Koston c2a2ddb490 [tee501] Drop the stray read before the identification command (#21928) 2026-10-30 19:41:43 -04:00
J. Nick Koston 471b67079f [ccs811] Round environment data once (#21927) 2026-10-30 19:39:34 -04:00
J. Nick Koston 844dd58b03 [mhz19] Keep reading after the uptime counter wraps (#21926) 2026-10-30 19:38:20 -04:00
J. Nick Koston 8b35e2ad16 [sensor] Add source_value for reading a compensation input (#21937) 2026-10-30 19:31:40 -04:00
J. Nick Koston 918488c8d6 [climate] Use celsius_to_fahrenheit in toshiba and daikin_brc (#21944) 2026-10-30 19:29:18 -04:00
J. Nick Koston ae85d85bc4 [senseair] Use discard_available to drain after a bad preamble (#21945) 2026-10-30 19:28:29 -04:00
J. Nick Koston 96836eab3d [components] Pass the failure reason to mark_failed in ee895, hte501, tee501 and mt6701_i2c (#21943) 2026-10-30 19:25:05 -04:00
J. Nick Koston 02e4d6d8b1 [components] Use sum_bytes for checksums in ufm01, bq76972, cm1106, pzem004t and pd_pioneer (#21942) 2026-10-30 19:23:50 -04:00
4b79dc5c99 [ld600x] Move the LD6002B component into a shared LD600XComponent base (#19837)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-30 23:16:02 +00:00
J. Nick Koston 67456e9dd6 [core] Start the Apple Silicon cc1plus wrapper through sh when the Python path has a space (#21967) 2026-10-30 13:09:24 -10:00
J. Nick Koston 7ac9a86861 [components] Use encode_uint16 and encode_uint24 in more drivers (#21941) 2026-10-30 18:56:05 -04:00
J. Nick Koston 2589cc6aea [components] Use encode_uint16 in sensor drivers (#21940) 2026-10-30 18:55:42 -04:00
J. Nick Koston 801e36f666 [components] Use encode_uint16 and encode_uint24 in 13 more drivers (#21949) 2026-10-30 18:47:26 -04:00
Clyde Stubbs 8a4d76be32 [mipi_rgb] Update pins for Lilygo boards (#21917) 2026-10-30 12:19:06 -10:00
5f916e3d49 [ld600x] Add shared TinyFrame parser and use it in ld6002b (#19836)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-30 12:17:36 -10:00
aronkandClaude Opus 5.5 81b8e36e96 [xiaomi_ble] Add LYWSD02MMC product ID 0x16E4 (#21955)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 11:04:04 -10:00
huangkongshengandJ. Nick Koston 6e5d9c1ad7 [core] Reject empty domain/object parts in cv.entity_id (#21964)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Signed-off-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
2026-10-30 10:56:14 -10:00
huangkongshengandJ. Nick Koston 7d2a039696 [core] Measure cv.ssid length in UTF-8 bytes, not characters (#21965)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Signed-off-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
2026-10-30 10:55:49 -10:00
huangkongshengandJ. Nick Koston c79e0b8f95 [sun] Reject garbage and truncated latitude/longitude instead of parsing 0.0 (#21876)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Signed-off-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
2026-10-30 10:55:24 -10:00
huangkongsheng e3888e2fa1 [time] Fix cron ranges wrapping around the end of the scale (#21961) 2026-10-30 10:51:16 -10:00
huangkongshengandJ. Nick Koston f35a0c4fef [core] Validate strings in cv.percentage_int instead of passing them through (#21877)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Signed-off-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
2026-10-30 10:46:14 -10:00
huangkongshengandJ. Nick Koston bf8ae4e306 [mipi] Document that init sequence delays require a time unit (#21873)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Signed-off-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
2026-10-30 10:41:08 -10:00
huangkongshengandJ. Nick Koston 07a3f39760 [core] Reject trailing garbage in cv.dimensions (#21963)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Signed-off-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
2026-10-30 10:40:37 -10:00
huangkongshengandJ. Nick Koston 9b2fcced64 [time] Reject invalid '/' step and offset in cron expressions (#21962)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Signed-off-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
2026-10-30 10:28:07 -10:00
dependabot[bot] a897f55e36 Bump platformdirs from 4.13.5 to 4.13.6 (#21970)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-30 10:03:45 -10:00
dependabot[bot]andesphome[bot] 2f84fd81a0 Bump ruff from 0.17.2 to 0.17.3 (#21969)
Co-authored-by: esphome[bot] <115708604+esphome[bot]@users.noreply.github.com>
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-30 10:03:33 -10:00
Clyde Stubbs 044fd267b6 [ufire_ec][ufire_ise] Move CONF_TEMPERATURE_SENSOR to the shared component constants (#21919) 2026-10-30 07:10:56 -10:00
Sebastian Muszynski a178954b11 [mqtt] Add value and command templates to time, date and datetime dis… (#21956) 2026-10-30 06:56:25 -10:00
00c15ddda2 [zephyr_mcumgr] Add SMP UDP OTA transport for nRF52 (#17245)
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: tomaszduda23 <tomaszduda23@gmail.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-30 00:45:31 -10:00
b4048bfb6f [wifi] Handle intentional ESP32 disconnects during roaming (#21758)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-29 19:43:17 -10:00
848231f59e [airton_serial] Add Airton serial climate component (#21872)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-29 19:31:37 -10:00
5d2961e96b [mitsubishi_cn105] Hold the climate action through wind-down and keep the AUTO direction (#20819)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-29 19:01:09 -10:00
08e41587ae [ledc] Fix pulse truncation when setting zero duty (#21179)
Co-authored-by: Tomas Matheson <tomas.matheson@icloud.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: Keith Burzinski <kbx81x@gmail.com>
2026-10-29 22:16:44 -05:00
129b3f248a [mitsubishi_cn105] Add climate action support (#21650)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-29 17:05:46 -10:00
FuNK3YandClaude Opus 5.5 1a325304ed [dlms_meter] Allow multiple dlms_meter instances (#21585)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 16:42:25 -10:00
Boris KrivonogandJ. Nick Koston 957fe02ebc [mitsubishi_cn105] Add the horizontal vane to the vane trigger and action (#21870)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-29 15:56:40 -10:00
96d6627daf [ir_rf_base] Reject infrared and radio_frequency entities sharing a key (#21886)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-29 15:54:50 -10:00
Jonathan Swoboda 349945225c [esp32][ota][esp32_ble_tracker] Prepare for ESP-IDF 6.2 (#21891) 2026-10-29 19:50:31 -04:00
be857de642 [ld2410] Add automatic background noise correction (#21460)
Co-authored-by: Anunay Kulshrestha <1544855+anunayk@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-29 12:36:51 -10:00
ee9ea7e62f [mitsubishi_cn105] Add horizontal vane direction select (#21863)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-29 10:46:35 -10:00
dependabot[bot] b155e4ba0b Bump clang-tidy from 23.1.3 to 23.1.4 (#21884)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-29 19:42:39 +00:00
dependabot[bot] 68b01ba754 Bump pytest-asyncio from 1.4.0 to 1.4.1 (#21883)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-29 09:32:06 -10:00
J. Nick Koston 95973f0d38 [matrix_keypad][rc522][rdm6300][sx1509][wiegand] Build hub triggers with two automations each in tests (#21787) 2026-10-29 11:07:47 -04:00
J. Nick Koston 2d41bd5cea [time] Add tests for on_time schedules and time jump handling (#21793) 2026-10-29 11:06:39 -04:00
J. Nick Koston 5d2772c216 [sun] Add unit tests for on_sunrise and on_sunset crossing (#21802) 2026-10-29 11:05:44 -04:00
J. Nick KostonandJonathan Swoboda 2ce14405ec [components] Publish child entities with PUBLISH_STATE (5/5) (#21852)
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
2026-10-29 11:04:43 -04:00
J. Nick KostonandJonathan Swoboda 8fd654e295 [components] Publish child entities with PUBLISH_STATE (4/5) (#21851)
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
2026-10-29 11:03:43 -04:00
J. Nick KostonandJonathan Swoboda fa28726789 [components] Publish child entities with PUBLISH_STATE (3/5) (#21810)
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
2026-10-29 11:02:26 -04:00
J. Nick KostonandJonathan Swoboda 8401d59ca1 [components] Publish child entities with PUBLISH_STATE (2/5) (#21809)
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
2026-10-29 10:51:21 -04:00
J. Nick KostonandJonathan Swoboda f838978a70 [components] Publish child entities with PUBLISH_STATE (1/5) (#21808)
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
2026-10-29 10:38:39 -04:00
J. Nick Koston f5a97e61bf [ld2420] Remove the unfinished gate energy sensor plumbing (#21850) 2026-10-29 10:15:53 -04:00
J. Nick Koston d8eec3c460 [ble_client] Cover text sensor on_notify in the build test (#21820) 2026-10-29 10:13:28 -04:00
J. Nick Koston dedccca940 [ci] Add GPIO hold, BLE, light sleep, manual IP, web handler, LD2450, BK72xx flash, Prometheus and OTA upload flows to the hardware-test skill (#21724) 2026-10-29 10:12:45 -04:00
J. Nick Koston 7cde8beb0d [wifi] Run the connection retry phases in a host unit test (#21746) 2026-10-29 10:12:22 -04:00
J. Nick Koston b59018147e [sensor] Fix codegen crash for a delta baseline given as a number (#21811) 2026-10-29 10:11:56 -04:00
J. Nick Koston 807dfa3abb [sensor][number] Add tests for the on_value_range trigger (#21814) 2026-10-29 10:08:53 -04:00
J. Nick Koston 9aa035a01e [ble_device_base] Cover the service and manufacturer data advertise triggers (#21822) 2026-10-29 10:08:12 -04:00
J. Nick Koston f3cb6039f2 [esp32_rmt_led_strip] Reorder members to fill base class tail padding (#21838) 2026-10-29 10:06:05 -04:00
J. Nick Koston d7e6051489 [modbus_controller] Drop the unused Component base from the outputs (#21857) 2026-10-29 10:04:12 -04:00
J. Nick Koston ce7b2506bb [vbus] Drop the unused Component base from the custom sub-sensors (#21859) 2026-10-29 10:03:29 -04:00
J. Nick Koston 585cc99331 [template] Drop the unused Component base from the template event (#21860) 2026-10-29 10:03:07 -04:00
J. Nick Koston 4cfa8780ee [hydreon_rgxx] Remove the empty binary sensor component (#21862) 2026-10-29 10:02:43 -04:00
J. Nick Koston a0e317d9f9 [core] Add PUBLISH_STATE (#21805) 2026-10-29 10:02:06 -04:00
J. Nick Koston a8aa4e6497 [components] Declare child entities with SUB_* macros (9/10) (#21848) 2026-10-29 10:01:06 -04:00
J. Nick Koston 4e725ea6d3 [components] Declare child entities with SUB_* macros (10/10) (#21849) 2026-10-29 10:00:45 -04:00
Jonathan Swoboda 5071968eb9 [ci] Compile each build path ESPHome ships on Windows on a Windows runner (#21791) 2026-10-28 22:46:10 -04:00
Jonathan Swoboda e6bebc298f [nrf52] Patch west build so a project on another Windows drive than the SDK builds (#21798) 2026-10-28 22:00:56 -04:00
Jonathan Swoboda 8831c0dc0d [platformio] Use ccache for compiles PlatformIO moved to a response file on Windows (#21819) 2026-10-28 21:59:54 -04:00
J. Nick Koston 9166980740 [remote_base] Drop the unused Component base from RawTrigger (#21796) 2026-10-28 21:09:41 -04:00
J. Nick Koston 7e575ef16d [http_request] Remove the unused HttpRequestResponseTrigger (#21797) 2026-10-28 21:09:29 -04:00
J. Nick Koston 6d9f4421a8 [components] Declare child entities with SUB_* macros (1/8) (#21770) 2026-10-28 20:34:55 -04:00
J. Nick Koston 8854e1eb94 [components] Declare child entities with SUB_* macros (2/8) (#21771) 2026-10-28 20:34:25 -04:00
J. Nick Koston d597be77ac [components] Declare child entities with SUB_* macros (3/8) (#21772) 2026-10-28 20:34:04 -04:00
J. Nick Koston f56a4db60f [components] Declare child entities with SUB_* macros (5/8) (#21774) 2026-10-28 20:33:25 -04:00
J. Nick Koston 362e73313c [components] Declare child entities with SUB_* macros (6/8) (#21775) 2026-10-28 20:33:03 -04:00
J. Nick Koston 6e92bb301d [components] Declare child entities with SUB_* macros (7/8) (#21776) 2026-10-28 20:32:50 -04:00
J. Nick Koston 644bd8995a [components] Declare child entities with SUB_* macros (8/8) (#21777) 2026-10-28 20:32:47 -04:00
J. Nick Koston 3caff2b80b [hdc1080][hdc2010][hdc2080][hdc302x] Declare child sensors with SUB_SENSOR (#21778) 2026-10-28 20:32:16 -04:00
TomandJ. Nick Koston 4814377805 [pcf85063] Read 12-hour mode and set 24-hour mode on every write (#21221)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-28 13:51:07 -10:00
Kevin AhrendtandJ. Nick Koston d0bafef28c [sendspin] Add the source role, streaming a microphone to the server (#21696)
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-28 23:41:38 +00:00
Bascht74 e8cf0cfd06 [core][socket] Add an idle timeout to TcpClientLink (#21365) 2026-10-28 13:23:59 -10:00
88f6135171 [esp32][audio_http] Keep TLS 1.3 working (#21786)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-28 23:22:43 +00:00
Kevin Ahrendt 055faab7e3 [sound_level] Allow more than one microphone channel (#21760) 2026-10-28 13:22:13 -10:00
Kevin Ahrendt f74d8b3ca2 [i2s_audio] Let stop() cancel a microphone start that has not run yet (#21759) 2026-10-28 13:21:37 -10:00
Jonathan Swoboda d5539d358a [core][nrf52] Drop build flags holding ';', keep linker groups whole, and quote nRF52 build flags (#21699) 2026-10-28 18:14:36 -04:00
d1c1f10be8 [binary_sensor] Add on_raw_value trigger (#21126)
Co-authored-by: Philip Poten <philip@poten.at>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-28 10:06:32 -10:00
tomaszduda23 185d2a4fe2 [nrf52] clean-up comments (#21769) 2026-10-28 19:36:37 +00:00
techdregs 3d3c624309 [rx8111] Add optional binary sensors (#21744) 2026-10-28 09:30:19 -10:00
tomaszduda23 3e884e1227 [nrf52] apply ThreadModel.MULTI_ATOMICS (#21761) 2026-10-28 20:03:03 +01:00
lobo67 f762e397be [cs5460a] Fix nested SPI enable() deadlock on ESP32 (#21753) 2026-10-28 08:48:37 -10:00
Arthur Komatsu fceec6cf95 [http_request] Close the connection when an OTA download is refused (#21762) 2026-10-28 18:46:13 +00:00
Wei-Lun LiandClaude Opus 5.5 23fa94bee1 [core] Reject a 0 K color temperature instead of crashing (#21756)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 08:18:54 -10:00
tomaszduda23andClaude 01fc4432ef [nrf52] do not show cdc_acm in device builder (#21737)
Co-authored-by: Claude <noreply@anthropic.com>
2026-10-28 16:33:28 +01:00
Javier Torres 0544ec9cd2 [voice_assistant] Ensure microphone is stopped at STT_END (#21755) 2026-10-28 07:26:14 -04:00
Kevin AhrendtandJ. Nick Koston f565ad0286 [i2s_audio] Stamp microphone buffers with the DMA capture time (#21664)
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-28 07:05:19 -04:00
n-IA-hane 10ce6b9faa [speaker_source] Stop pending sources without advancing the playlist (#19501) 2026-10-27 19:46:17 -10:00
Raphael Hehl a99bca0a23 [esp32_camera] Add capture_delay and capture triggers for single images (#21614) 2026-10-27 19:45:01 -10:00
Nicolas Liaudat 647c9b8b28 [esp32_camera] Add sensor windowing (digital zoom) (#20480) 2026-10-27 18:39:55 -10:00
Bogdan Dumitru 1acd6a64d4 [ld2450] Detect a lost radar link (#21734) 2026-10-28 04:27:58 +00:00
Petar Petrov d58c809e9b [vnc] Add VNC password authentication (#20626) 2026-10-27 18:14:42 -10:00
68fdc2c1bc [ring_buffer] Respect waits for oversized partial writes (#21058)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-28 03:47:49 +00:00
f8fbcb8886 [ecocomfort2] Add the configuration entities (Part 3) (#20783)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-27 17:46:54 -10:00
J. Nick KostonandJonathan Swoboda 28fb5125a6 [binary_sensor] Reset filters when the state becomes unknown (#21740)
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
2026-10-27 17:15:18 -10:00
J. Nick Koston 02eab7b269 [libretiny] Report the previous boot's crash on LN882H (#21728) 2026-10-27 16:56:46 -10:00
441d7ec20c [rx8111] Add event timestamp text sensor and capture storage modes (#21604)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-27 16:52:50 -10:00
J. Nick Koston 3d7ec081f8 [i2c] Print the bus scan results from one shared helper (#21718) 2026-10-27 22:50:05 -04:00
J. Nick Koston 3f1ca2fc9a [bluetooth_connection] Hold the RP2 service table in a RAMUniquePtr (#21730) 2026-10-27 22:49:27 -04:00
J. Nick Koston 6309f63a44 [core] Read the OS from sys.platform instead of querying it at import (#21736) 2026-10-27 22:48:31 -04:00
J. Nick Koston f2880d2a37 [components] Declare hub entity pointers with the SUB_* macros (#21726) 2026-10-27 22:47:47 -04:00
Jonathan SwobodaandJ. Nick Koston 6f9e92a9e3 [zephyr_ble_server] Keep the stored connection right when disconnect runs first (#21723)
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-27 16:19:47 -10:00
Kevin Ahrendt 5e51abb438 [resampler] Carry capture times through the resampler microphone (#21682) 2026-10-27 16:04:45 -10:00
ce2e025d84 [delta_wallbox] Swapped the power and energy readings (#21628)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-27 14:54:45 -10:00
072c9556eb [core] Allow esphome upload without a configuration (#21738)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-27 14:48:47 -10:00
Jonathan Swoboda 02502b7af2 [core][scheduler] Log a new interval before taking the scheduler lock (#21721) 2026-10-27 19:58:36 -04:00
Jordan Zucker 205ef9407f [prometheus] Add prometheus datetime metrics (#9941) 2026-10-27 13:09:01 -10:00
Adam Vigneaux d552396650 [tinyusb] Only declare the IAD device class when a class needs it (#21719) 2026-10-27 22:20:50 +00:00
J. Nick Koston a101d57476 [runtime_image] Hold the JPEG decoder state in a RAMUniquePtr (#21717) 2026-10-27 11:37:24 -10:00
Bogdan Dumitru 195cb3b2b4 [ld2450] Allow a presence_timeout of 0 (#21733) 2026-10-27 11:23:59 -10:00
Bohdan 8529b7a59c [bk72xx_ble] Add BK7238 support (#21735) 2026-10-27 21:22:24 +00:00
Bogdan Dumitru 4e63342350 [ld2450] Write an edited polygon zone to flash right away (#21732) 2026-10-27 10:51:57 -10:00
Fabio Pugliese Ornellas 3784a3d56a [ld2450] Add a text sensor with the position of each target (#21416) 2026-10-27 10:50:35 -10:00
Bogdan Dumitru 848d1ac4e8 [ld24xx] Show radar MAC addresses that have the multicast bit set (#21731) 2026-10-27 10:45:00 -10:00
c3348789eb [gree] Add IR receiver support and YB1FA model (#18435)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: Leonardo Rivera <leodrivera@gmail.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-27 09:28:11 -10:00
6ea4d976c2 [tas58xx] Add mixer mode select (#21637)
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-27 09:20:00 -10:00
ebd5a8bb18 [debug] Log per-thread CPU usage on nRF52 (#13938)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-27 08:46:22 -10:00
J. Nick Koston 6ac63ac495 [pcm5122] Use Apply switches for the power switches (#21677) 2026-10-27 08:44:38 -10:00
J. Nick Koston 7d5bfb8fa3 [sendspin] Use an Apply switch for the enabled switch (#21673) 2026-10-27 08:33:58 -10:00
Jesse Hills 4cd4ddb981 Merge branch 'release' into dev 2026-10-28 07:33:31 +13:00
Jesse Hills 4ea26ed65f Merge pull request #21707 from esphome/bump-2026.10.1
2026.10.1
2026-10-28 07:33:05 +13:00
J. Nick Koston 747921faa8 [bq25186] Use an Apply switch for the PG/GPO switch (#21675) 2026-10-27 08:29:48 -10:00
J. Nick Koston f8056c3a30 [bq25186] Test the PG/GPO switch (#21654) 2026-10-27 08:29:48 -10:00
J. Nick Koston 85c241391e [core] Add publish="on_success" for Apply entities whose hub call can fail (#21663) 2026-10-27 08:29:47 -10:00
J. Nick Koston 9cccb42c6f [ci] Add the Xiaomi BLE, WPA3 AP, BLE terminate, I2C slave, OTA timing and RTL8720C crash flows to the hardware-test skill (#21636) 2026-10-27 08:08:52 -10:00
J. Nick Koston 81d451aa63 [text_sensor] Add throttle, throttle_with_priority and timeout filters (#21669) 2026-10-27 08:00:44 -10:00
J. Nick Koston c3506bd7b9 [ci] Persist a bounded integration test ccache seed (#21701) 2026-10-27 08:00:22 -10:00
J. Nick Koston 449c511606 [ci] Build integration tests without debug symbols, re-run failures with them (#21702) 2026-10-27 08:00:21 -10:00
J. Nick Koston 0ec8e58772 [libretiny] Report the previous boot's crash on RTL8720C (#21648) 2026-10-27 10:04:19 -04:00
J. Nick Koston 1ee8762006 [esp32_ble] Warn once for repeated connection parameter update failures (#21698) 2026-10-27 09:43:27 -04:00
J. Nick Koston c865b551ee [web_server] Make web OTA's request handler part of its component (#21711) 2026-10-27 09:29:46 -04:00
J. Nick Koston 6e416952c8 [ethernet] Keep manual IP settings in flash (#21712) 2026-10-27 09:28:19 -04:00
J. Nick Koston 96b8bae876 [tests] Drive the clock in the UDP OTA ping test (#21715) 2026-10-27 09:22:00 -04:00
J. Nick Koston 1e8f084741 [ci] Stop saving an empty apt cache when the install fails (#21713) 2026-10-27 19:34:58 +13:00
Jesse Hills 6595df0cab Bump version to 2026.10.1 2026-10-27 16:17:54 +13:00
J. Nick Koston 73894b2490 [core] Turn off the precompiled header with ccache older than 4.7 (#21627) 2026-10-27 16:17:53 +13:00
Jonathan Swoboda 9bef20d8dc [core] Avoid division by zero in Color::random_color() (#21623) 2026-10-27 16:17:53 +13:00
Jonathan Swoboda 0e440500a2 [core] Generate valid C++ for infinite float values (#21625) 2026-10-27 16:17:53 +13:00
minimicro34 badfa84fe0 [esp32_ble] Ignore unhandled BLE key GAP events (#21457) 2026-10-27 16:17:53 +13:00
J. Nick Koston e686ecf76e [core] Resolve version-less library dependencies like PlatformIO (#21317) 2026-10-27 16:17:53 +13:00
Jonathan Swoboda 64fb4e06b5 [ledc] Reset the peripheral through the HAL on targets without the legacy periph API (#21397) 2026-10-27 16:17:53 +13:00
Jonathan Swoboda cb82c9031a [core] Keep the color codes of a filtered build output line (#21396) 2026-10-27 16:17:53 +13:00
J. Nick KostonandJonathan Swoboda ca74ab9873 [climate] Add StringRef overloads for ClimateCall::set_fan_mode and set_preset (#21359)
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
2026-10-27 16:17:53 +13:00
J. Nick Koston 86fc740b65 [http_request] Copy a manifest URL set at run time and keep the config literal by pointer (#21373) 2026-10-27 16:17:53 +13:00
J. Nick Koston 450bb52f65 [mqtt] Resend the fan state when its first publish fails (#21328) 2026-10-27 16:17:35 +13:00
J. Nick Koston ed3615ec69 [light] Add a StringRef overload for LightCall::set_effect (#21358) 2026-10-27 16:15:01 +13:00
J. Nick Koston a5f25ebe2d [core] Emit generated lambda code after the user includes (#21307) 2026-10-27 16:12:58 +13:00
Jonathan Swoboda 7a4775de3d [esp32_hosted] Keep the OTA watchdog timeout through the coprocessor end call (#21300) 2026-10-27 15:48:16 +13:00
2077 changed files with 75237 additions and 16677 deletions

No files matched your search

+26
View File
@@ -70,6 +70,21 @@ await automation.build_callback_automation(
`build_parent_callback_automation`, `build_trigger_callback`, `build_callback_automations` and
`build_trigger_automations` cover the other shapes; see their docstrings in `esphome/automation.py`.
When every action in a callback automation is inline (see Actions below), no `Automation` or action objects
are generated: the callback calls one generated function, at the same RAM cost as a hand-written lambda. A
custom forwarder blocks this unless its filter is also given as `params`, `forward` and `when`, so always pass
them together:
```python
automation.CallbackAutomation(
CONF_ON_IDLE,
"add_on_state_callback",
forwarder=StateEnterForwarder.template(State.IDLE),
params=[(State, "state")],
forward=[],
when=f"state == {State.IDLE}",
)
```
**C++: no trigger class needed.** The callback registration method must be templatized to accept both
`std::function` and lightweight forwarder structs (which avoid heap allocation):
```cpp
@@ -101,6 +116,8 @@ void add_on_state_callback(std::function<void(bool)> &&callback) {
|------|----------------------|-------------|
| `CallbackManager<void(Ts...)>` | 12 bytes (empty `std::vector`) | Callbacks are always or almost always registered |
| `LazyCallbackManager<void(Ts...)>` | 4 bytes (`nullptr`) | Callbacks are often not registered (common case) |
| `AutomationList<N, Ts...>` + `build_automation_lists` | 4 bytes per automation + count, none when unused | A hub fires its own `on_*` automations with no filter (4 B per automation vs 8 B per `Callback`) |
| `automation.new_automation(args, conf)` + the parent's own fixed table | the table entry (pointer plus its own data) | Like `AutomationList`, but each automation needs a stored value of its own, e.g. a threshold the parent compares against |
Both live in `esphome/core/helpers.h` and accept `std::function`, lambdas and forwarder structs through
their templatized `add()` method. `LazyCallbackManager` is a drop-in replacement for `CallbackManager` that defers allocation until the first
@@ -187,6 +204,15 @@ payload passes `automation.ApplyBytes(CONF_DATA, "send({})")` in the same call;
flash and a lambda's vector is forwarded as data and size. `TEMPLATABLE_VALUE` with `cg.templatable` stays
for actions whose `play()` has real logic beyond forwarding values.
Adjacent `register_apply_action` and `lambda:` actions in a list merge into one generated function and one
object, which saves 12 to 16 bytes of RAM per merged action. An action with its own C++ class ends the merged
run, so prefer `register_apply_action` wherever the action allows it. Because of this, `build_action_list` can
return fewer objects than the config has entries. A builder that wraps `apply_action_builder` may do other work
first, but must return its result unchanged and not use it. A builder that must generate its own statements, and
is registered with `automation.ApplyAction`, can call `apply_statements_action` and still merge; `script.execute`
is an example. `if`, `choose`, `while` and `repeat` whose bodies are all inline become C++ control flow in the
same function, and `register_apply_condition` and `lambda:` conditions become plain expressions there.
## Conditions
```cpp
+21
View File
@@ -69,6 +69,27 @@ performance nit, because it fragments a small shared heap. Flag:
typed as `std::function`, so lightweight forwarders avoid a heap allocation.
- Two-space indent, `using` over `typedef`, wrap at 120 columns.
## Use the existing helper
New components often hand-write code a helper already covers. Ask for the
helper; `AGENTS.md` section 4 and the `component-codegen` skill have the detail.
| Seen in the PR | Ask for |
| --- | --- |
| `if (this->x_sensor_ != nullptr) this->x_sensor_->publish_state(v);` | `PUBLISH_STATE(this->x_sensor_, v);` (`esphome/core/entity_base.h`) |
| set warning / `return` / clear warning around a bus result | `if (!this->status_comm_result(ok)) return;` |
| hand-written `set_x_sensor()` plus `x_sensor_` member | `SUB_SENSOR(x)`, `SUB_BINARY_SENSOR`, `SUB_TEXT_SENSOR`, `SUB_SWITCH`, ... |
| `if CONF_X in config: s = await sensor.new_sensor(config[CONF_X])` plus setter | `sensors = sensor.sub_sensors(config)` then `await sensors(CONF_X, hub.set_x_sensor)` |
| hand-written `{"a": MyEnum.MY_ENUM_A, ...}` dict | `MyEnum.options("a", "b", prefix="MY_ENUM_")` |
| loops on `available()` / `read_byte()` | UART `read_available(on_byte)`, `discard_available()`, `LineReader<N>`, `FrameReader<N, HEADER...>` |
| hand-rolled CRC, checksum or bit loop | `crc8`, `crc16`, `xor_bytes`, `sum16_bytes`, `encode_uint16`, ... (`esphome/core/helpers.h`) |
| integer split into buffer bytes by hand (`buf[0] = v >> 8; buf[1] = v;`) | `put_be16`/`24`/`32`, `put_le16`, `put_le32` (`esphome/core/helpers.h`) |
| bare `mark_failed()`, or `ESP_LOGE` then `mark_failed()` | `this->mark_failed(LOG_STR("reason"))` or `LOG_STR(ESP_LOG_MSG_COMM_FAIL)` |
| button/switch/number/select C++ class that only calls the hub | `ApplyButton`, `ApplySwitch`, `ApplyNumber`, `ApplySelect` with `apply=` |
| action or condition class that only forwards to the parent | `register_apply_action` / `register_apply_condition` |
| enum-to-string `switch` returning literals | `PROGMEM_STRING_TABLE` with `get_log_str` / `get_progmem_str` |
| `if (x := config.get(CONF_X)) is not None: cg.add(var.set_x(x))` | `cg.add_optional(var.set_x, config.get(CONF_X))`, when the setter takes the value unchanged |
## Python conventions
- Type-annotate every new function signature (params and return), new dataclass
+5 -1
View File
@@ -177,7 +177,8 @@ async def to_code(config):
uses `button.ApplyButton` (`switch.ApplySwitch`, `number.ApplyNumber`, `select.ApplySelect`) in its schema
and `apply=` on the `sub_*` call. The body is a call on the hub with `entity` and `state`, `value` or
`index`/`option` in scope; on a switch, number or select `publish="before"` or `"after"` publishes the
state. `publish="momentary"` is only for legacy action switches (restart, factory reset): it publishes off
state, and `publish="on_success"` publishes only when the hub call returns true (a write the device can
refuse). `publish="momentary"` is only for legacy action switches (restart, factory reset): it publishes off
and runs the body only when turned on. Never use it for a new entity; an action is a button.
```python
switches = switch.sub_switches(config, parent=hub)
@@ -200,6 +201,9 @@ virtual listener base (a second vptr per entity).
- `uart.new_uart_component(config, *ctor_args)` (and `i2c.new_i2c_component`, `spi.new_spi_component`,
`modbus.new_modbus_client_component`, `ble_client.new_ble_node_component`) constructs, registers and
attaches in one call.
- A fixed buffer sized from the config is a file-scope static (BSS, not heap):
`buf = cg.static_buffer(config[CONF_ID], cg.uint8, size)`, named after its owner so `esphome analyze-memory`
counts it there; pass `buf` to the constructor.
- `display.add_writer(var, config)` sets the lambda.
- `MyEnum.options("on", prefix="MY_ENUM_")` builds an enum dict.
- `button.restart_button_schema(cls)` (and `factory_reset_`, `query_`) are button presets.
+2
View File
@@ -42,6 +42,8 @@ APIs.
// Or if size is constant:
std::array<uint8_t, 256> buffer;
```
When the size comes from the config, declare it with `cg.static_buffer()` in `to_code` and pass the pointer
to the constructor, so it lands in BSS (see the `component-codegen` skill).
2. **Compile-time-known fixed sizes with vector-like API:** use `StaticVector` from
`esphome/core/helpers.h` for compile-time fixed size with a `push_back()` interface (no dynamic
+18 -5
View File
@@ -67,9 +67,17 @@ driven, what the logs show, and the same flow on a `dev` build when a quirk coul
automations in the config itself.
7. **Analyze** with `grep -a -c` counts over the capture and keep an `-events.txt` extract of the lines
that matter. Decode crashes with the platform's `addr2line` (see `reference/boards.md`).
8. **Report** on the PR as a table: build SHA, board and framework, what was driven, counts, result,
plus the `dev` control row and the exact flow in a `<details>` block. No credentials, no port names,
no IP addresses.
8. **Report** on the PR. Every result comment starts with this two-line GitHub alert, then a blank line:
```
> [!NOTE]
> Automated testing results
```
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.
## Flashing by chip family
@@ -80,6 +88,7 @@ driven, what the logs show, and the same flow on a `dev` build when a quirk coul
| ESP32-S3, C3, C6, H2 native USB | `esphome upload --device /dev/cu.usbmodem*` | `logger: hardware_uart: USB_SERIAL_JTAG`. The USB console can wedge when the app takes over the console (0 bytes, esptool `No serial data received`); replug, or watch through `esphome logs --device <name>.local` |
| Pico W / Pico 2 W | `esphome upload --device <port>` (1200 baud touch); first flash ever via BOOTSEL and `--device /Volumes/RPI-RP2` or `RP2350` | port re-enumerates after upload: `ports.py --wait 2e8a` then capture |
| BW15 kit (RTL8720CF, rtl87xx) | `~/.platformio/penv/.libretiny/bin/python $SKILL/scripts/flash_rtl87xx_kit.py flash write -d <port> <build>/.pioenvs/<name>/*.uf2`. Plain `esphome upload` and plain ltchiptool time out because opening the port asserts DTR/RTS and holds the chip in reset | `serial_capture.py --released`, never `esphome logs` |
| BW12 and other AmebaZ modules (RTL8710BX, rtl87xx) on a plain USB-UART | `~/.platformio/penv/.libretiny/bin/python -m ltchiptool flash write -B 115200 -b 115200 -t 120 -d <port> <uf2>`, started first, then strap by hand: CEN to GND, TX2 to GND, release CEN, release TX2. Without `-B 115200` the system data read at 1.5 Mbaud fails on CH340s (`Data read error at 0x9000`) and nothing is written. A 1 MB image takes about 80 s. A development board with DTR and RTS wired to CEN and the download pin needs no strap | `serial_capture.py`; a reset pulse does not reach CEN on a plain adapter, so a capture starts mid-run |
| BK7238 / CB3S (bk72xx, RTS on CEN) | `~/.platformio/penv/.libretiny/bin/python $SKILL/scripts/flash_bk72xx.py flash write -d <port> <uf2>` (about 75 s) | logs are on UART2 by default; `logger: hardware_uart: UART1` puts them on the flashing adapter. `serial_capture.py --reset` gives a chip-enable reset; a plain open may or may not reset it, check for the bootloader banner |
| LN882H | ltchiptool forces 1 Mbaud for writes; weak adapters need `LN882H_YM_BAUDRATE` patched to 115200 in the penv's `ln882htool.py`; short BOOT to GND while the tool connects | OTA after the first flash |
| nRF52840 Dongle (PCA10059) | Nordic `nrfutil nrf5sdk-tools dfu usb-serial` on the bootloader port, or `dfu: true` in the config so the 1200 baud touch pin-resets into the bootloader; adafruit-nrfutil is refused | app has two CDC ports, ESPHome log on the second |
@@ -114,8 +123,8 @@ Per-topic scripts, each described in the matching `reference/recipes/<component>
(server with prefixed misbehaviour cases, PNG, JPEG, BMP and QOI generators, API drivers, first pass timer), `zwave_proxy/` (checksum verifier, device info), `usb_cdc_acm/`
(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 and
capture decoder), `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), `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), `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/` (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).
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), `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), `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/` (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), `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).
## Templates in `$SKILL/templates`
@@ -166,6 +175,10 @@ comment quotes the exact commits. Fetch `origin dev` before computing a merge ba
- The merge base comes from a freshly fetched `origin/dev`; a stale local `dev` puts dependency bumps into the
PR diff and builds the control from the wrong commit.
- A `.local` name can stop resolving in the middle of a run; keep the address from the boot log and drive by it.
- Never point `framework: source:` at a local `file://` copy of LibreTiny to try a patch: PlatformIO installs it over
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.
- `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.
@@ -88,6 +88,12 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
- The AmebaZ2 SDK sets `LWIP_TCPIP_CORE_LOCKING 0`.
- The `rtw_is_adapter_up` bus fault after `Disabling AP` happens on LibreTiny 1.13.0 and 1.14.0 alike
(2 of 4 and 3 of 3 runs in #21531); run at least four rounds per build before blaming a PR for it.
- On a fault the ROM handler (ram_vector_table entries 3 to 7) prints a dump of about 4 KB in 0.4 s and
then spins; only the watchdog resets the chip (10 s after `arch_init`, 1 s once the ESPHome crash
handler re-arms it). `.ram.bss.noinit*` (`.system_restore_data`) survives that reset. The core has no
FPU. For a crash that fires once, guard an `interval` lambda with
`!libretiny::crash_handler_has_data()`. For a handler mode (MSP) fault, point vector 16+11 (SDIOD,
unused) at a trapping function and set bit 11 in NVIC ISER and ISPR (0xE000E100, 0xE000E200).
## BK7238, WB3S, CB3S (BK7231N) (LibreTiny bk72xx, CH340, RTS on CEN)
@@ -125,9 +131,54 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
- The BK7238 bootloader prints `App verify failed! Need to recovery factory firmware.` on every boot with any
build; it is harmless. Even with the right layout an ESP32 client did not see the BK7238 fallback AP on
LibreTiny 1.13.0 or 1.14.0, so the wifisave hammer cannot run on it.
- Moving a BK7231N device (CB3S) that sits on its fallback AP to another network: join the host's Wi-Fi to
`<name>-fallback`, OTA to 192.168.4.1, then rejoin the host's own network. Moving it with `/wifisave` instead can
leave it in the captive portal's BLIND_RETRY state (no scan, `Beacon Timeout` every 46 s) until it reboots, and a
log-only serial adapter cannot reset it. Rejoining may change the host's address; update a syslog target that
points at the old one.
- Callbacks run on the `async_tcp` task and log lines can lose a byte. Wi-Fi connect takes tens of ms;
radio enable 160 to 278 ms, disable about 200 ms.
## BW12 and other AmebaZ boards (RTL8710BX, LibreTiny rtl87xx)
- On a bare module wired to a plain USB-UART (the bench's BW12), download mode is a hand strap: CEN to
GND, TX2 to GND, release CEN, release TX2. Such an adapter does not drive CEN, so neither ltchiptool nor
`serial_capture.py --reset` can reset the chip. A development board that wires DTR and RTS to CEN and the
download pin enters download mode from the tools, like the BW15 kit; the notes below on baud rates still apply.
- ltchiptool links at 1.5 Mbaud and reads the system data at 0x9000 at that rate before it writes at
115200. A CH340 drops bytes there (`Data read error at 0x9000`, `Timed out waiting for Quiet-Handshake`)
and the run gives up without writing. `-B 115200 -b 115200` moves the link to 115200 first and works.
Start the command with `-t 120` so it is already polling while the board is strapped.
- After a failed run the ROM may sit at another baud rate and no longer link; strap again.
- The device builder frontend's AmebaZ flasher follows ltchiptool (link and system read at 1.5 Mbaud),
so it can hit the same read failure on the same adapters.
- Power the module from the adapter's 5 V pin into its own regulator; the adapter's 3.3 V pin cannot
carry the Wi-Fi transmit peaks.
- Capture with `serial_capture.py --released`. With DTR and RTS asserted on the open port, a software
reboot (`App.safe_reboot()`, the restart button) lands in the ROM downloader (`UARTIMG_Download 2`)
and stays there until CEN is pulsed. After a flash the chip also waits in the ROM until CEN is pulsed.
- A full flash takes 50 to 220 s at 115200. While the board is on Wi-Fi, OTA (port 8892) saves the strap,
but the board's Wi-Fi latency (one to two seconds a ping) can make the upload time out.
- `sdk_silent: none` under `framework:` keeps the Wi-Fi driver's join log (`start auth to`, `auth success,
start assoc`, `association success`, `sta recv deauth reason code(N)`); LibreTiny mutes it during the
connect otherwise. `wifi_get_last_error()` after a failed `WiFi.begin()` gives the SDK's reason
(1 no network, 2 connect failed, 3 handshake failed, 6 auth failed); LibreTiny only logs `ret=-1`.
- Some modules ship with no RF calibration in efuse, only the chip ID and MAC. Dump the logical map with
the ROM's `EFUSE_LogicalMap_Read(buf)` (512 bytes): TX power indexes are at 0x10 to 0x1A, crystal trim
at 0xC9, MAC at 0x11A; 0xFF means the driver uses its default (trim 0x20). Linking with
`-Wl,-wrap,EFUSE_LogicalMap_Read_ACUT` lets a wrapper rewrite blank bytes before the driver parses
the map on each radio start. See `recipes/libretiny.md` for the per-boot trial harness used to A/B them.
- Scan results report WPA2-AES access points as `WPA PSK`: LibreTiny truncates `rtw_security_t` to
`uint8_t` before mapping it. Cosmetic. Open networks come out as `WIFI_AUTH_INVALID` (255) on both
AmebaZ and AmebaZ2, so `auth != WIFI_AUTH_OPEN` marks them encrypted.
- After a BSSID plus channel join, LibreTiny's `set_pscan_channel(ch, false)` leaves the driver with no
channel to scan, so the next SSID only join fails at once (no `start auth`). Calling
`wifi_set_pscan_chan` with channels 1 to 13 and `PSCAN_ENABLE` each before such a join fixes it and
keeps the BSSID fast path (BW15 BSSID join median 3.05 s with it, 4.68 s when joining with channel 0).
- A 4-way handshake that never finishes after association is reported as `RTW_WRONG_PASSWORD` on AmebaZ
even with the right password; AmebaZ2 reports a real wrong password as a 4-way handshake timeout.
- The driver also posts a SCAN_DONE (number 0) inside every join, on AmebaZ2 too.
## BW16 kit (RTL8720DN, AmebaD)
- The kit's own USB-C (CH340) is on LOG_UART and flashes fine. Its two-transistor circuit resets while
@@ -172,6 +223,12 @@ 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.
- 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
`interval:` lambda in an included header; results arrive on the OpenThread thread and log fine.
- A wrong network key on a real network's channel and PAN ID makes the device form its own partition as leader on
that PAN within about 30 s; take it off Thread at once. Never try guessed datasets against a network in use.
## Waveshare ESP32-S3-ETH with the OV5640 camera module
@@ -11,20 +11,20 @@ One file per component, named after it:
- [`espnow.md`](espnow.md): ESP8266 broadcast receive
- [`hdmi_cec.md`](hdmi_cec.md): two-board wire
- [`http_request.md`](http_request.md): update manifest URL changed at run time, every setter shape, a swap under a running check, non-blocking request actions with loop gap, queue, cancel and reboot checks, OTA request cases with basic auth and MD5 sources
- [`ld2450.md`](ld2450.md): polygon zones, zone number round trip through the radar's readback, ESP8266 loopback harness without a radar
- [`ld2450.md`](ld2450.md): polygon zones, zone number round trip through the radar's readback, ESP8266 loopback harness without a radar, presence hold and link loss on a frame stream, BT MAC readback
- [`ld2412.md`](ld2412.md): output pin level through the basic configuration command, held back writes
- [`libretiny.md`](libretiny.md): rtc preference emulation, BK72xx crash report on the next boot
- [`libretiny.md`](libretiny.md): rtc preference emulation, BK72xx and RTL8720C crash report on the next boot with a ROM dump matcher, BK7238 BLE bond store safety with a full flash backup and per partition diff, BK7238 OTA versus the board layout and bootloader
- [`modem.md`](modem.md): PPPoS modem component boot check with no modem attached, loop blocking and disable timing
- [`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
- [`nrf52.md`](nrf52.md): dongle board support, zephyr_ble_server connection slot under reordered callbacks
- [`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): overlap and lock, timeouts, deflate
- [`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
- [`rtsp_server.md`](rtsp_server.md): camera streaming on the Waveshare ESP32-S3-ETH
- [`scheduler.md`](scheduler.md): loop wake A/B
- [`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
- [`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
- [`zephyr.md`](zephyr.md): preferences on the nRF52840 dongle
- [`zephyr_coredump.md`](zephyr_coredump.md): crash and decode on nRF52 boards
- [`zwave_proxy.md`](zwave_proxy.md): frame checksums on a live proxy
@@ -36,5 +36,14 @@ One file per component, named after it:
- [`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 on the S3
- [`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
- [`xiaomi_ble.md`](xiaomi_ble.md): Xiaomi, ATC and PVVX parsing by injecting scan results into the ESP32 tracker or advertising them from a second ESP32, real AES-CCM frames, duplicate filter model
- [`ble_terminate.md`](ble_terminate.md): proxy disconnect against a peer with peripheral latency
- [`i2c_slave.md`](i2c_slave.md): fake I2C slave on a D1 mini, ESP32 hardware master as the control
- [`gpio_hold.md`](gpio_hold.md): GPIO hold through the ISR pin API, pad read back with no wiring, per chip pin notes
- [`ble_event_inject.md`](ble_event_inject.md): made up GAP and GATTC events fed into the ESP32 BLE handlers from a button
- [`light_sleep_gpio_wake.md`](light_sleep_gpio_wake.md): GPIO wakeup from auto light sleep with an LEDC wave that keeps running in sleep
- [`manual_ip_and_web_handlers.md`](manual_ip_and_web_handlers.md): station, AP and Ethernet manual IP, web handlers added late and web OTA with web_server, captive_portal or prometheus
- [`ble_server_security.md`](ble_server_security.md): esp32_ble_server pairing, encrypted and MITM characteristics, subscription before and after pairing, bond reuse per ESP-IDF version
- [`prometheus.md`](prometheus.md): date, time and datetime metrics in UTC and another time zone
@@ -0,0 +1,20 @@
# Injecting BLE GAP and GATTC events (#21698)
Some BLE paths (repeated connection parameter update failures, a disconnect in the middle of them) are hard to get
from a real peer on demand. `scripts/ble_event_inject` feeds made up events straight into the ESP32 BLE handlers.
- `ESP32BLE::gap_event_handler` and `gattc_event_handler` are protected statics and the class is `final`.
`cp_inject.hpp` reaches them through explicit template instantiation, where access checks do not apply. Its
`cpinject::run()` sends six labelled steps (`STEP1` to `STEP6`): four peers failing five times each, a success
followed by more failures, and disconnects between failures.
- `cp-inject.yaml` is a package for a copy of a proxy config: it adds the include, a VERBOSE logger with the busy
tags back at DEBUG, and an `Inject conn param events` button. Press it with `scripts/api_button.py` while a
log capture (`esphome logs ... --device <ip>` under `timeout`) runs, then count the warning and verbose lines per
step on the PR and on dev.
- The handlers push into a queue and event pool that take a single writer, normally the Bluetooth task. Injecting
from the main task while real events arrive can corrupt them, so the button stops the scan, waits for it to end,
injects and starts it again. Run it with no active proxy connections (no Home Assistant BLE client holding one).
- Fake disconnects use `gattc_if` 0xFE: every client and proxy connection filters on its own `gattc_if_`, so the
queued event reaches only the shared handler. Do not use 0xFF (`ESP_GATT_IF_NONE`), which every client accepts.
- The fake peers (`C0:FF:EE:00:00:0n`) are never connected, so a live proxy keeps serving its real connections;
put it back on its own config afterwards.
@@ -0,0 +1,26 @@
# esp32_ble_server pairing and encrypted characteristics (#17562)
`scripts/ble_server_security`: a classic ESP32 devkit runs the secure GATT server (`server.yaml`) and a second ESP32
(an S3 here) runs `ble_client` as the central (`client.yaml`). The server has a `read_encrypt` battery level
(`99.9`), a plain characteristic, a `write_encrypt` characteristic that logs what it receives, a `read_encrypt_mitm`
characteristic and a `read_encrypt` characteristic that notifies every 2 s. `run.sh TAG IO AUTH` builds both with the
pairing mode as substitutions, pairs once, reconnects twice, and `summary.py` prints PASS or FAIL. The server needs
`esp32_ble_server` security from #17562 or later: point `SERVER_TREE` at that checkout (the client builds from
`TREE`, dev is fine). `summary.py` needs each refused read to show an `Error reading char` reply, so a run where the
client never connected fails instead of passing.
- `ble_client` never starts pairing on its own (a phone does, after an `insufficient authentication` reply); the
client's `Pair` button calls `BLEClientBase::pair()`. Read errors show as `Error reading char at handle N, status=5`
(not authenticated: no bond) or `status=15` (not encrypted: bond known, link not encrypted yet).
- The `ble_client` text sensor subscribes once, at connect, before any pairing, so a protected characteristic refuses
it. The `Subscribe` button writes the CCCD again after pairing; `ble_client` drops its service list after discovery,
so it writes the characteristic handle + 1 (where ESP-IDF's GATT server puts the CCCD).
- Numeric comparison (`display_yes_no` with `sc_mitm_bond`) tells a fresh pairing from a bond reuse: the
`numeric comparison` line only appears on a fresh pairing. Just Works cannot show it.
- ESP-IDF 5.5.6 drops the bond on the second disconnect on both roles (`Deleting unpaired device`), so that reconnect
pairs from scratch; 5.5.5 keeps it (`-s idf 5.5.5`).
- The server keeps its bonds in NVS. One holding an authenticated bond for the client refuses a Just Works re-pairing
silently; erase the devkit's flash before switching from nc to jw.
- `summary.py` failed both modes at 58636914ab: `read_encrypt_mitm` was readable with no pairing, because
`BLEService::create_characteristic()` took an 8 bit `esp_gatt_char_prop_t` and dropped the MITM bits (1 << 8 and
1 << 9). Check the generated `create_characteristic` call and the property type when a flag above bit 7 is added.
@@ -0,0 +1,27 @@
# BLE terminate with peripheral latency (#20232)
`scripts/ble_terminate`: an ESP32-S3 `bluetooth_proxy` (active) over Ethernet as the central (`btproxy.yaml`) and a
classic devkit `esp32_ble_server` peer (`btpeer.yaml`). The peer asks for 50 ms / latency 10 / 6 s with
`esp_ble_gap_update_conn_params` 4 s after connect; earlier requests are overwritten by the proxy's own "medium
conn params" after service discovery. Read the proxy's `Conn params updated` line (VERBOSE, API logs) to confirm;
the peer side never logs the event. The proxy only connects to a device its scanner has seen, so `btdrive.py`
subscribes to raw advertisements first.
Measure the peer's own disconnect (`serial_capture.py --ms`) after the client's disconnect: about 0.2 to 0.8 s when
the terminate arrived, about 6 s (the supervision timeout) when it was lost. The client side disconnect time is the
API reply and says nothing. On dev the S3 lost 6 of 12; the PR lost 0 of 16.
`run.sh LABEL ROUNDS` writes `central_bda.hpp` from `PROXY_BT_MAC`, builds and flashes both boards, runs the rounds
and `an.py`, which prints PASS only when every round completed, every peer disconnect came within 3 s and the last
parameter update the proxy logged before each disconnect had latency=10 (a round without it did not test peripheral
latency and counts as inconclusive).
Controller build check: ESP-IDF 5.5.6 ships `libbtdm_app.a` byte for byte the same as 5.5.5 for esp32c3 and esp32s3
(build 51d9dfd). Without hardware:
```bash
strings -a <idf>/components/bt/controller/lib_esp32c3_family/<chip>/libbtdm_app.a | grep -E '^[0-9a-f]{7}$'
```
On a board: a button lambda logging `btdm_controller_get_compile_version()` (declared `extern "C"`) over the API,
since the ESP-IDF init line only reaches the UART.
@@ -0,0 +1,17 @@
# ESP32 GPIO hold through the ISR pin API (#21576)
`scripts/gpio_hold/hold_test.hpp` builds `ESP32InternalGPIOPin`s by hand, calls `to_isr()` and reads each pad back
with `gpio_get_level`: 20 ISR writes, a raw `gpio_set_level` control (a held pad must not change, an unheld one must)
and ISR `pin_mode` pulls (input must drop to `NONE` between pull changes, because the ISR path only applies pulls when
`FLAG_INPUT` toggles). It needs no wiring: unconnected pins read the pulls. Each pin runs held and unheld, then the
round logs `ROUND n PASS failures=0` or `FAIL`.
- `USE_GPIO_HOLD` comes from any pin with `hold_state: true`, so the configs add a `gpio` output on a spare pin.
- `gpio-hold-esp32.yaml` (classic devkit) runs three rounds 5 s after boot and has a `rerun` button;
`gpio-hold-esp32s3.yaml` (Waveshare ESP32-S3-ETH, where most pins go to the W5500, TF card, camera, WS2812 or
USB) runs a round every 15 s.
- C3: ESP-IDF 5.5 has `SOC_RTCIO_PIN_COUNT` 0, so `rtc_gpio_is_valid_gpio()` is false on every pin and only the
digital hold path runs.
- C6 (Waveshare ESP32-C6-GEEK, native USB): LP pads GPIO0 to 7 are RTC IO with hold. GPIO1, 2, 7, 20, 23 read high
and GPIO6 low whatever the pull (LCD, TF card or resistors); clean pins are 0, 3, 4, 5, 18, 19, 21, 22. Dev
already holds LP pads through `gpio_hal_hold_en`, so the PR and dev look the same there. H2 is untested.
@@ -0,0 +1,12 @@
# Fake I2C slave (#21586)
`scripts/i2c_slave`: a D1 mini running an Arduino `Wire` slave at 0x40 (`i2cslave.yaml` with `i2cslave.hpp`): a fake
HDC1080 plus a 256 byte register file, and reads of 0x7E and 0x7F stretch the clock for 0.5 and 5 ms. It needs
`libraries: [Wire]` and 160 MHz. With jumper wires only and the internal pull ups it works to about 50 kHz; it cannot
keep up with a true 100 kHz hardware master.
The master (`i2cbk.yaml`, a BK7238 on P26/P24, needs the software I2C bus from that PR) writes a counter, reads it
back with a repeated start, probes an absent address and reads both stretch registers every 2 s, logging `RW OK`
(the read back matches, the absent address NACKs and both stretched reads succeed) or `RW BAD` with running totals.
Control: the same blocks on a classic ESP32 devkit (SDA GPIO21, SCL GPIO22) with hardware I2C at 25 and 50 kHz got
every repeated start read right, so failures on a bit banged master at a similar real clock point at the master.
@@ -40,3 +40,29 @@ least 24 selects per build and read the raw bytes with `uart: debug: direction:
id) before blaming the parser; the API log stream drops lines under that dump volume, so some misses stay
unclassified.
Results: https://github.com/esphome/esphome/pull/21357#issuecomment-6333244886
## Frame stream harness: presence hold and link loss (#21733, #21734)
`scripts/ld2450/stream-harness.yaml` is a loopback harness that feeds the hub one periodic frame every 100 ms from a
mode global set by API buttons: no target, target 1 approaching, silent, or 12 garbage bytes per tick (what a radar
at another baud rate looks like). `has_target` has `filters: []` so the hub's own hold is what gets timed, and every
change logs `presence raw ON|OFF at <millis>`. Add `stream-connected.yaml` as a second package on builds whose ld2450
has the link watchdog (`connected` binary sensor).
- `holddrive.py HOST OUT`: for `presence_timeout` 5 and 0, three seconds of target frames, then empty frames; prints
the ms from the press to the off line, then sets 0 and 20 and reads the number back after a restart. On dev 0
still held 5 s and snapped back to 5; with #21733 it clears on the next empty frame (under 200 ms) and stays 0.
- `linkdrive.py HOST OUT`: steps through target frames, 10 s of silence, empty frames, 10 s of garbage, target
frames, then the hub's radar restart followed by 3.5 s and by 15 s of silence; prints every state change and link
log line with its time. Dev freezes every entity through silence and garbage. Run against a real radar too: a
radar restart and a Bluetooth toggle must not report a loss (the Apollo R PRO-1 ETH did not).
- A freshly booted ESP8266 delays API commands sent in its first seconds and then runs them back to back; the
drivers wait 8 s after connecting before timed presses.
## BT MAC sensors (#21731)
`scripts/ld2450/macdrive.py HOST OUT` reads every LD24xx BT MAC, Bluetooth and firmware entity, turns each Bluetooth
switch off, then on, and prints the values after each step. The MAC sensors are often `disabled_by_default` in
vendor configs but still publish over the API. On the Apollo R PRO-1 ETH both radars (LD2450 fw 2.04, LD2412 fw
1.26) have the multicast bit set in the first MAC byte, which dev showed as `unknown`. A radar MAC identifies a
device: quote only its first byte in PR text.
@@ -8,3 +8,7 @@
- On the ESP32-S3 give each RMT strip `rmt_symbols: 48`, or the first channel takes all 192 symbols.
- A board with a few WS2812 on a pin already defined as a light can be extended with `id: !extend <light id>` to
add effects; restore its own config afterwards.
- Loop cost of a strip (#19337): give each strip an `addressable_lambda` effect with `update_interval: 0ms` that
changes every pixel, and add `runtime_stats: log_interval: 30s`; compare the main loop and light times per pass,
leaving out the first period after boot. The strips need no LEDs attached. A classic ESP32 has 512 RMT symbols in
all, so three strips need `rmt_symbols: 128` each.
@@ -56,3 +56,107 @@ OTA-only board: copy the device's own config, add the probe include and the step
next to that config. A LibreTiny OTA is a 1.5 MB UF2 and takes minutes on a slow link, so do not wrap the
upload in a short timeout. Read the replayed report with `esphome logs ... --device <name>.local` (an API
client gets it on subscribe) or on the board's serial log port if it has one.
## RTL8720C crash report on the next boot (#21648)
`templates/rtl8720c-crash-buttons-dut.yaml` has one API button per case: `trap` (`__builtin_trap()`, usage fault),
`bus fault` (store to 0x70000000, imprecise, CFSR 0x400), `wild call` (call to 0xFFFFFFF1, MemManage fault with PC
0xFFFFFFF0 and LR in the caller), `isr trap` (a trap from a spare interrupt pended by software, hard fault), `hang`
(interrupts off, the watchdog resets it and nothing must be reported) and `restart`. Every boot logs
`boot reason N, crash record yes|no|n/a`; `n/a` means the handler is not built, as on a dev control build.
Flow per build: flash with `flash_rtl87xx_kit.py`, start one `serial_capture.py PORT 600 OUT --released --ms`, then
`scripts/libretiny_crash/rtl_drive.py HOST OUTDIR TREE YAML trap restart "bus fault" "wild call" "isr trap" hang restart`.
The `restart` after the first crash checks the report shows only once. Time each reset from the serial capture
(the ROM fault dump to the next `ROM Version` line), not from the API port: the board is back before an API client
notices it went away. Compare the reported PC with the `PC =` line of the ROM dump, and check the decoded lines in the
`caseN-*.txt` files. Pass the UF2 by name (`firmware.uf2`): the build directory holds a second identically sized copy.
Regression rerun of the same flow (#21728): `scripts/libretiny_crash/rtl_rom_vs_report.py CAPTURE` lists, for each ROM
fault dump in a `--ms` capture, the ROM's CFSR and PC, the ms to the next `ROM Version` banner and the Reason, CFSR, PC
and SP the next boot reported, so two builds compare line by line. The ROM lines start with a bare CR; split the
capture on newlines only. The imprecise bus fault's PC moves between builds (it is wherever the core was when the
fault was raised); compare it with that run's ROM dump, not with another build. SP stays the same per fault (8 word
frame, no FPU). On the BK7238 time the reboot from the button press to the next `BK7238_1.0.14` banner (0.6 to 0.7 s).
## BK7238 BLE and flash sector safety (#21735)
The Beken BLE bond store reads its partition at boot and erases that sector when the CRC does not match; before
LibreTiny 1.14 the partition was unmapped and pointed at sector 0, erasing the bootloader (#18646). To prove a change
like this safe on a board that cannot be recovered without a dump:
1. Take a full backup first: `scripts/bk72xx_flash/readback.sh full-before` (ltchiptool family `beken-7238`, about
190 s for 2 MB). Keep it until the board is back on a known build.
2. Serial flash a build without the feature, then deliver the feature build by OTA (the path users take). Use
`bk72xx: framework: sdk_silent: none` with `logger: hardware_uart: UART1`, so the SDK's own lines (bootloader
banner, `CRC fail, remove bonded info`) show up in the capture.
3. Soak with Wi-Fi up, OTA again from the new build, pulse CEN a few times (`serial_capture.py --reset`), and check
each boot comes back through the bootloader.
4. Read the whole chip again and run `scripts/bk72xx_flash/partdiff.py full-before.bin full-after.bin
<libretiny>/boards/_base/beken-72xx.json`: bootloader, calibration and userdata must be unchanged; app, download
and one KVS sector change normally.
Check what already sits in the target partition before the first boot: on an XH-WB3S that shipped with Tuya firmware,
0x1E1000 (the `ble_bonding` partition of the generic Beken layout) held the Tuya `diff2ya` record (magic `ba dc cd
ab`), which the bond store erased on its first boot. Nothing depended on it there, but say so in the results.
## BK7238 OTA and the board layout (issue #18222)
A BK7238 has one of two bootloaders, and the board in the YAML must match it: Beken OEM (`BK7238_1.0.14` in the
boot banner, `generic-bk7238`, OTA as RBL to `download` at 0x132000) or Tuya T1 2.0.0 (`generic-bk7238-tuya`,
`t1-*`, `download` at 0x12C000 plus a `diff2ya` record at 0x1E1000). `ltchiptool uf2 info` on `firmware.uf2` shows
the layout an image targets (`FAL_PTABLE`, `OTA_PART_INFO`). Measured on the OEM bootloader (2026-10-27):
| Running | Uploaded | Result |
|---|---|---|
| Tuya layout | Tuya layout | upload succeeds, bootloader prints `App verify failed! Need to recovery factory firmware.`, old build stays |
| Tuya layout | OEM layout | applied |
| OEM layout | Tuya layout | `End error: 9` (`UPDATE_ERROR_ACTIVATE`: no `RBL` at the running download offset), old build stays |
| OEM layout | OEM layout | applied |
Run it with a full backup first (`scripts/bk72xx_flash/readback.sh`), `sdk_silent: none` so the bootloader's lines
show, and each result checked against `build_info.json` over the API. A Tuya-layout build on an OEM-layout module
reads the RF calibration from 0x1E3000: copy the 0x1E0000 sector there for the test and erase it afterwards. The
Tuya OTA writes up to about 0x1EF000 and its own settings at 0x1E4000, so write those sectors back from the backup
and check with `partdiff.py`.
## RTL8710B Wi-Fi join diagnosis (issue #21742)
For a board that joins rarely: build `dev` with `sdk_silent: none`, log `wifi_get_last_error()` and
`rtw_join_status` after each failed `WiFi.begin()`, and dump the efuse map once (see the AmebaZ section in
`boards.md`). The driver log tells the stages apart: `start auth to` with nothing after it is the AP not answering,
`auth success, start assoc` then `association success` then error 3 is a failed 4-way handshake, and
`sta recv deauth reason code(6)` is the AP dropping the session mid-handshake. Tally per BSSID: if the share of
auth frames answered falls with distance while receive stays strong, the board's transmit path is weak.
A/B a value one boot at a time so time of day and AP state hit both sides equally. Keep the trial counter in a
`restore_value` global, set the value in an `on_boot` lambda at priority 600 (before Wi-Fi starts), and reboot
after a fixed window:
```yaml
esphome:
on_boot:
priority: 600
then:
- lambda: |-
// value under test, read by the code being measured
wifi::diag_value = (id(trial_idx) % 2) ? 0x3A : 0;
ESP_LOGW("trial", "TRIAL %d start value=0x%02X", id(trial_idx), wifi::diag_value);
- delay: 75s
- lambda: |-
bool ok = wifi::global_wifi_component->is_connected();
ESP_LOGW("trial", "TRIAL %d value=0x%02X result=%s", id(trial_idx), wifi::diag_value,
ok ? "JOINED" : "FAILED");
id(trial_idx)++;
App.safe_reboot();
```
Turn off `api:` and `wifi:` `reboot_timeout`, and leave out `ap:` unless the AP is the variable under test.
Do not cycle trials with `wifi.disable` and `wifi.enable`: doing that while connected reset the RTL8710B on the next
scan. Results from 2026-10-27, on one BW12 with blank efuse calibration: crystal trim `0x20`, `0x30` and `0x38`
all joined 20 of 20 trials, and boosted TX power indexes changed nothing against an AP that answered 0 of 43
auth frames.
Known LibreTiny behaviour seen here: after a join with a BSSID and channel, LibreTiny's partial-scan reset leaves
the next SSID-only join with nothing to scan (`RTW_NONE_NETWORK` in about 18 ms). That is a firmware bug, not
the board; passing channel 0 avoids it.
@@ -0,0 +1,16 @@
# GPIO wakeup from auto light sleep (#21074)
`scripts/light_sleep_wake` needs no wiring. LEDC on `LEDC_USE_RC_FAST_CLK` with
`sleep_mode = LEDC_SLEEP_MODE_KEEP_ALIVE` keeps toggling GPIO10 at 2 Hz through light sleep, and an
`ESP32InternalGPIOPin` interrupt (`ANY_EDGE`) on the same pad timestamps every edge in an IRAM handler.
`wakeprobe::report()` logs every 30 s: edges seen and expected, the shortest and longest gap, how many edges came
more than 20 ms off the half period, and the SLEEP share from `esp_pm_dump_locks()` (needs `profiling: true`).
- Native ESP-IDF builds need `include_builtin_idf_components: [esp_driver_ledc]`.
- After `ledc_channel_config` call `gpio_input_enable(pin)`, never `gpio_set_direction(INPUT_OUTPUT)`: that routes the
pad back to a plain GPIO output, the wave stops and the pad reads a constant 1.
- The C3 shares one LEDC clock across timers, so a board whose own config drives LEDs through `ledc` needs a test
config without them. Logging over the API works with `logger: baud_rate: 0`.
- Read the reports over the API with `esphome logs ... --device <ip>` under `timeout`. Run PR, dev, then the PR
again. On a C3 bulb dev caught every edge but handled 8 of 845 more than 20 ms late
(up to 45 ms), the PR none; both slept 57 to 58% of the time.
@@ -0,0 +1,31 @@
# Manual IP and web handler flows (#21708, #21709, #21711, #21712)
## Station manual IP (`scripts/manual_ip/run-sta.sh`)
Set `static_ip` to the board's own DHCP lease so nothing collides, and DNS2 to a server DHCP does not hand out
(9.9.9.9), so the dump and `dns_getserver()` prove the manual values are in use. A missing SSID with its own
`manual_ip` comes first, so the real network is a later table row and inherits the top level `manual_ip`. The probe
logs both DNS servers and resolves a name every 20 s; `ipaddr_ntoa` uses one static buffer, so it uses
`ipaddr_ntoa_r` to log two addresses in one line. PASS needs the address, both DNS servers, a lookup and a ping.
## AP manual IP (`scripts/manual_ip/run-ap.sh`)
The DUT has only a missing SSID, `ap_timeout: 10s` and `captive_portal:`, so its AP comes up on 10.42.7.1; the other
board joins as a client and fetches `http://10.42.7.1/` every 10 s. A D1 mini AP drops some client requests on dev
too, so compare failure counts with a dev run and do not expect zero.
## Ethernet manual IP
Same idea on an Ethernet board: its lease as `manual_ip` plus an outside DNS2 and the DNS probe from
`scripts/manual_ip/dnsprobe.hpp`; restart it over the API and check again.
## Web handlers (`scripts/web_handlers/run.sh`)
`webbase.yaml` adds a GET /probe handler from `on_boot` at priority -100 (the shape of an external component adding
a handler late) and takes a variant: `ws` (web_server), `cp` (captive_portal only, started on the station network by
a button calling `global_captive_portal->start()`) or `prom` (captive_portal and prometheus). The runner fetches
/probe and /, then uploads the same image through web OTA (`curl -F update=@<bin> http://ip/update`; ESP-IDF
`build/<name>.bin`, not `firmware.ota.bin`; ESP8266 `.pioenvs/<name>/firmware.bin`) and checks over the API that the
board is back on that build. On dev too, prometheus GET / gets no answer on ESP32 and 404 on ESP8266.
A background `(cd dir && cmd) &` does not change the parent shell's directory: give capture scripts absolute paths.
@@ -4,3 +4,27 @@
Test config: the two LEDs as inverted GPIO outputs, the button as an inverted pull-up binary sensor, a
10 s alive interval. To retest the nrfutil download path, move the cached `sdk-nrf/nrfutil` aside first.
## ItsyBitsy over UF2 when serial DFU fails (#20481)
Serial DFU to the ItsyBitsy nRF52840 fails about half the time ("Target is not in DFU mode"). Reliable path: a
1200 baud touch on the app port, wait for the `ITSY840BOOT` volume, convert `zephyr/zephyr.hex` with the SDK's
`zephyr/scripts/build/uf2conv.py -f 0xADA52840 -c` and copy the .uf2 to the volume (the copy ends in an I/O error
when the board reboots, which is normal). macOS BLE scans give UUIDs, not MAC addresses.
## zephyr_ble_server connection slot under reordered callbacks (#21723)
`scripts/zephyr_ble_server`: the ItsyBitsy runs `server.yaml` (one connection slot) and an ESP32 runs `client.yaml`,
which connects, drops the link 300 ms later and reconnects as soon as the server advertises again. `run.sh NAME 90`
flashes the UF2, counts the server's `Connected`/`Disconnected`/`Advertising` lines and the client's connects,
and ends with PASS (more than one server connection) or FAIL; an empty capture or a silent client fails the setup.
- The connect and disconnect callbacks each `defer()` to the main loop and the bug needs the disconnect handled
first, which cannot be forced over the air. Force it with a test-only patch on both trees: replace the connect
callback's `defer(...)` with `set_timeout(5000, ...)`. A leaked reference then shows as one connection and nothing
after it (the dump still lists the closed link); a fixed build keeps cycling (17 in 90 s on #21723).
- `dfu: true` makes the next flash a 1200 baud touch; an app built without it needs a double tap on RESET. The
Zephyr app enumerates as `2fe3:0100`, the bootloader as `239a:0051`, so find the board by its USB serial number.
- macOS is a poor central here: it keeps old bonds with a board (`Peer removed pairing information` on connect)
and clearing them is a system setting. Use an ESP32 `ble_client`; the server's random static address comes from
its own log.
@@ -6,3 +6,64 @@ All overlap orders (a web upload during a native OTA and the reverse) must be re
after an interrupted web upload waits about 14 s (ESP8266) or 7 s (ESP-IDF) for disconnect detection. A
refused web client on `web_server_idf` never gets the busy reply; the connection drops at reboot.
`pkill -f "a\|b"` does not alternate; use two pkills.
## OTA upload timing A/B (#21639, #21641, #21642)
`scripts/ota_timing/run.sh N PHASE...` times native OTA uploads per build (phase) and per board. It builds every
board from `TREE_<PHASE>`, does one warm-up upload per board (it installs the phase's build and is left out of the
results), checks over the API that each board reports the compile time from that build's `build_info.json`
(`apiinfo.py`), then runs N rounds of every mode on every board. Boards are interleaved per round so they share the
same air; put a nearby ESP32 on the same Wi-Fi in `BOARDS` as a network control. `summ.py` prints medians: never
judge from single runs, slow Wi-Fi gave 33 to 235 s for the same upload in one night.
- `otatime.py` drives `espota2.run_ota()` from the tree on `PYTHONPATH` and prints one `RESULT` line with the
`Update took` split, the compressed size, whether UDP was used and the time at each tenth of the upload.
An upload that leaves no `RESULT` line (board gone, script crash, timeout) is recorded as `rc: -1`, and `summ.py`
fails when a board and mode has fewer than N rows or an upload time cannot be read.
- Boards with an `api: encryption: key` also encrypt OTA: set `API_KEY` for `otatime.py` and `apiinfo.py`. LibreTiny
LN882H listens for OTA on 8820, not 8892; BK72xx and RTL87xx use 8892.
- Raw mode leaves `CLIENT_FEATURE_SUPPORTS_DEFLATE` out of the client's offer. Never switch deflate off after the
offer (`if deflate and 0:`): once the device accepted deflate it expects a deflate stream.
- `-tcp` modes make `espota2._loss_reason` return None, so the client asks to stay on TCP. Clearing
`CLIENT_FEATURE_SUPPORTS_UDP` instead desyncs the handshake (`receiving UDP token response: timed out`).
- LibreTiny trimmed UF2 (#21642): the CLI sends what `esphome.components.libretiny.uf2.device_ota_uf2()` returns for
`firmware.uf2`; that module only exists with #21642, so on older trees the full UF2 goes out. Compare the sizes
in the `Compressed to` lines, and rely on the API compile time check to show that the trimmed image booted.
`receiving chunk result: Unknown error from ESP` is error 0xFF sent by the device, not a dropped connection. The
device sends it for a decode or flash write error, and also when no data arrives for 105 s, so on a weak link it
usually means a stall. A failure about 105 s after the last progress, or the same error on a raw upload, points to
the link; to be sure, capture the device log (`Inflate err`, `Inflate overrun`, `No data received`).
Results: https://github.com/esphome/esphome/issues/21639#issuecomment-6409628227 (dev and LibreTiny 1.14.0 on a
CB3S), https://github.com/esphome/esphome/pull/21642#issuecomment-6412972562 (trimmed UF2 on CB3S, BK7238 and BW15),
https://github.com/esphome/esphome/pull/21641#issuecomment-6412976859 (new decoder on the same three).
## On-device inflate benchmark (#21639, #21641)
`scripts/ota_timing/inflate_bench`: `gen_streams.py NAME=IMAGE...` cuts a 128 KB slice from each image and writes
`bench_streams.hpp` with raw deflate streams (level 9, 4 KB and 32 KB windows). `bench.hpp` inflates every stream with
each ring size at least the encoder window, three times, and logs the best time plus input and output rates, then
`BENCHDONE`. `bench.sh CONFIG DEVICE` builds and uploads `bench-esp32s3.yaml` or `bench-bk72xx.yaml`, collects one pass
over syslog and fails when a case did not reach the end of its stream.
- LibreTiny defines `micros` as a macro, so the header calls `(esphome::micros)()`.
- Keep the streams near 130 KB on a BK7231N: an image with about 330 KB of extra incompressible data failed its
OTA with "Writing OTA data to flash memory failed". Use one image and `--windows 12` there.
- `bench.hpp` targets the decoder interface with `dest_limit`. #21641 drops it (the output runs into the window up
to `dest`); after that lands, remove the `dest_limit` line.
Results: https://github.com/esphome/esphome/issues/21639#issuecomment-6409786224
## Upload without a configuration (#21738)
`esphome upload --file IMAGE --device IP` with no YAML picks the OTA port from the image header and takes the password
from `--ota-password` or `ESPHOME_OTA_PASSWORD` and the key from `ESPHOME_OTA_KEY`. Test each chip family with its own
current image (`build/firmware.ota.bin` for ESP-IDF, `.pioenvs/<name>/firmware.bin` for ESP8266, `firmware.uf2` for
LibreTiny) and check the build over the API; switch one board between two builds to show a new image lands.
Point every case that should be refused before connecting at an unroutable address (192.0.2.1), never at a board: a
refusal prints no `Connecting to` line, and an image that slips through cannot reach a device. An ESP32-S3
`firmware.factory.bin` slipped through on 2026-10-27 (its bootloader header at offset 0 looks like an app), the device
reported `OTA successful` and its bootloader rejected the slot at boot; send the board its proper app image afterwards.
A factory image has the partition table magic `AA 50` at 0x8000 and the app at 0x10000.
@@ -0,0 +1,10 @@
# prometheus
## Date, time and datetime metrics (#9941)
`scripts/prometheus/prom-datetime.yaml` is a D1 mini with `web_server`, `prometheus` and three optimistic template
datetime entities; `prom-datetime-tz.yaml` adds an sntp time component with `HST10` (the zone applies without a sync).
`datetime_metrics.py HOST` prints the rows of `/metrics`, sets the entities over the API to 2040 values (past 2038 on
purpose) and prints them again with their UTC reading. Dates are local midnight in ms, times ms since midnight,
datetimes ms since the epoch, so a datetime set as an instant reads the same in both zones. It exits 1 when a time
or datetime row does not hold the value it set (dates depend on the zone and are only printed).
@@ -37,3 +37,44 @@ AP start (the fix in that PR), the first AP start failed on every boot with `esp
(DHCP server already started by the AP start event) and `Failed to enable NAT`, and the bridge only came up on the
retry 90 s later; a client that cannot find the SSID for the first minute on an older build is that. With the fix
the bridge is up 6 s after boot. Any change to the ESP-IDF AP start should also rerun the captive portal hammer.
## Reboot against a WPA2/WPA3 PMF access point (#21590)
- AP: `scripts/wpa3_ap/wdap.yaml` on a classic devkit. ESPHome `wifi: ap:` only, then an on_boot lambda switches it
to `WIFI_AUTH_WPA2_WPA3_PSK`, PMF capable, and registers a WIFI_EVENT handler that logs `STA JOIN` and
`STA LEAVE ... reason N` (the include header pulls in `esp_wifi.h`). It disables Wi-Fi after 420 s.
- AP leave reason 3 means the station sent a deauth; reason 2 means the AP found a stale association when the
station came back; several reason 2 before one join are rejected reconnects.
- DUTs (`wdbk.yaml` BK7238, `wdcb.yaml` CB3S, both on `wd-common.yaml`) list the AP at priority 10 and the house
network at 0, and reboot 30 s after joining the AP and 150 s after joining the house network. So they move to the
AP while it is up and fall back to the house network (where they can be flashed over the air) once its window
ends. `run.sh BUILD` flashes the AP, does OTA for the CB3S and a serial flash for the BK7238, then captures one AP
window; `an.py` prints each station's join and leave sequence and fails on a rejected reconnect, an AP that did
not switch to WPA2/WPA3 (`AP CONFIG FAILED`), a DUT missing from the AP events (`DUT_MACS`) or a BK7238 that never
joined the AP.
- Gotchas: the LibreTiny build directory has two `.uf2` files, so flash `firmware.uf2`. The BK7238 serial flash
sometimes fails to link while the chip is in a reboot loop; retry it 3 or 4 times. OTA fails if the DUT reboots
mid-upload; retry.
- Finding: BDK 3.0.78 rejects about 2 reconnects per reboot when the station left without a deauth; BDK 3.0.33
does not.
## WISP and ALWAYS_ON AP rig (#20077)
`scripts/wisp_ap`: the upstream is an ESP32-S3 with Ethernet running a WISP bridge (`wisp-upstream.yaml`) with its AP on
10.40.0.1/24 and web buttons `ap off` and `ap on`. Its subnet must not be 192.168.4.0/24, the DUT AP's default, or
nothing routes. The DUT is a classic devkit (`dut-wisp.yaml` or `dut-always-on.yaml`); the client is a D1 mini on
the DUT's AP (`wispcli.yaml`) logging its DNS server, a name lookup, a GET by name, the AP itself and a LAN file by
IP. `run.sh DUT START SECONDS T:STATE...` switches the upstream AP at the given times and `sum.py` groups the client
results by phase. Capture the D1 mini without `--reset` (a CH340 floods garbage after an RTS reset). Clients keep
the captive portal's DNS answer for its TTL.
## AP restart with WPA3 mixed and LIGHT power save (#21531)
`scripts/wifi_restart`: the WISP upstream (`wisp-upstream-wpa3.yaml`) switched to WPA2/WPA3 mixed by a script that
runs again after every `ap on`, DUTs (`rebk.yaml`, `recb.yaml` on `re-common.yaml`) with a static IP on the bridge's
subnet, a fallback AP, `power_save_mode: LIGHT` and syslog to the host through the NAT. `run.sh BUILD` switches the
AP off and on three times; `an.py` fails on a reboot, a crash or a DUT that is not back on syslog within 120 s of an
AP start. After 19 minutes the DUTs run `wifi.configure` to the house network; that keeps the static IP, so the next
OTA needs the host to have an address on the bridge's subnet as well (an interface alias). The CB3S log is on UART1
(TX1), so its configs need `logger: hardware_uart: UART1`. Runners must `pkill` only their own ports; a global pkill
stops the other runs' captures.
@@ -0,0 +1,38 @@
# Xiaomi BLE
## Xiaomi, ATC and PVVX parsing without the sensors (#21483)
No Xiaomi devices are needed, and one ESP32 cannot hear its own advertising, so the frames are injected into the
tracker as scan results: everything after the radio runs as normal.
- `scripts/xiaomi_ble/gen.py` writes `frames.hpp` and `expected.json`: plain MiBeacon (0x50), encrypted v5 23 byte
with MAC and 19 byte without, real AES-CCM (`cryptography` AESCCM, tag 4, AAD 0x11, nonce = MAC reversed + pid +
cnt + 3 byte ext counter), ATC (13 byte, big endian) and PVVX (15 byte, little endian) 0x181A frames, a corrupted
tag every other cycle and a counter 0 boot frame. It models the old shared duplicate counter (`base`) and the per
device one (`pr`) and prints the expected publish counts.
- `xbinject.yaml` (ESP-IDF devkit) includes `frames.hpp`; an `interval:` builds a `BLEScanResult` and calls
`global_esp32_ble_tracker->gap_scan_event_handler(r)`. `count.py` counts the `Got Xiaomi` blocks (sensor
publishes are not logged at DEBUG) and compares them with `expected.json`.
- On ESP32 the tracker's own triggers sit in `listeners_`, which runs before `neutral_listeners_` (the
ble_device_base devices), so an `on_ble_service_data_advertise` never sees what a Xiaomi listener did to the
shared data. Check that directly: `xb_rewrite_probe(id(xa))` builds an `ESPBTDevice` with `parse_scan_rst()`,
calls the component's `parse_device()` and logs the service data before and after (`[probe` lines).
- `run.sh inject pr|base` builds, flashes, captures and prints PASS when the counts match that build's model and,
on the PR build, the probe's service data is the same before and after `parse_device()`.
Base dropped a second device's frame with the same counter, the frame after a bad tag and a first frame with
counter 0, and rewrote the shared data in place; the PR fixed all of them.
## Over the air with a second ESP32
- Advertiser: an ESP32-S3 with Ethernet (OTA over Ethernet), `xbadv.yaml` with `adv_frames.hpp` from
`gen.py --ota`. Per frame: stop advertising, `esp_ble_gap_set_rand_addr`, `config_adv_data_raw`, start
non-connectable advertising with `own_addr_type` random, 20 ms interval, 250 ms dwell. Random static addresses
need the top two bits set, so these use C4:C1:38 instead of A4. `esp32_ble:` alone brings up the stack. The
web_server button starts a run: `curl -X POST -d "" http://<advertiser>/button/start/press` (no body gives 411).
Its `failed sends` sensor counts only GAP calls rejected when queued; a frame the controller drops later shows
up as missing publishes in `count.py`, the same as radio loss.
- Receiver: `xbrecv.yaml` on the devkit, passive scan with window = interval = 100 ms. `run.sh ota pr|base` (with
`ADV` set) flashes it, resets it with a capture and presses start 18 s later, so the counter 0 boot frame is the
first one it hears.
- Each frame arrives about 4 times; the counts matched the injection run exactly apart from one radio loss, so the
over the air comparison allows two missing publishes per tag.
@@ -0,0 +1,64 @@
"""Compare two full flash dumps of a BK72xx board per partition of its LibreTiny board layout.
usage: partdiff.py BEFORE.bin AFTER.bin LAYOUT.json
LAYOUT.json is a board base file from the LibreTiny platform (for example boards/_base/beken-72xx.json); its
"flash" map ("name": "0xSTART+0xLENGTH") names the partitions. Prints the 4 KB sectors that changed in each one,
plus any changed sector outside the map (a WARN, to check by hand). Exits 1 when the bootloader, calibration or
userdata partition changed.
"""
import json
import pathlib
import sys
before, after = (pathlib.Path(p).read_bytes() for p in sys.argv[1:3])
if len(before) != len(after):
sys.exit(
f"dump sizes differ: {len(before)} and {len(after)} bytes; compare two whole chip reads"
)
parts = []
for name, span in json.loads(pathlib.Path(sys.argv[3]).read_text(encoding="utf-8"))[
"flash"
].items():
start, length = (int(x, 16) for x in span.split("+"))
parts.append((start, start + length, name))
parts.sort()
PROTECTED = ("bootloader", "calibration", "userdata")
if missing := [n for n in PROTECTED if n not in {name for _, _, name in parts}]:
sys.exit(
f"the layout has no {', '.join(missing)} partition; use the Beken board base file"
)
if (end := max(e for _, e, _ in parts)) > len(before):
sys.exit(
f"the layout reaches {end:#x} but the dumps are {len(before):#x} bytes; read the whole chip"
)
SECTOR = 0x1000
covered = set()
protected = []
for start, end, name in parts:
changed = [
a
for a in range(start, end, SECTOR)
if before[a : a + SECTOR] != after[a : a + SECTOR]
]
covered.update(range(start, end, SECTOR))
if changed and name in PROTECTED:
protected.append(name)
listed = " ".join(hex(a) for a in changed[:4]) if 0 < len(changed) <= 4 else ""
print(
f"{name:12} {len(changed):4} of {(end - start) // SECTOR:4} sectors changed {listed}"
)
other = [
a
for a in range(0, len(before), SECTOR)
if a not in covered and before[a : a + SECTOR] != after[a : a + SECTOR]
]
print(
f"{'unmapped':12} {len(other):4} sectors changed {' '.join(hex(a) for a in other[:8])}"
)
if other:
print(
"WARN: sectors outside the layout changed; check what they held in the backup"
)
if protected:
sys.exit(f"FAIL: {', '.join(protected)} changed")
@@ -0,0 +1,19 @@
#!/bin/bash
# usage: readback.sh TAG [START LENGTH] read flash from a BK72xx over its adapter into TAG.bin (whole chip by default)
# env: PORT (adapter), FAMILY (ltchiptool family, default beken-7238), FLASH_BK (path to flash_bk72xx.py),
# LT (LibreTiny penv python, default ~/.platformio/penv/.libretiny/bin/python), SIZE (whole chip bytes, default
# 2097152). A whole 2 MB chip takes about 190 s. The read must come back at the expected size.
T=${1:?tag}; P=${PORT:?set PORT}; FB=${FLASH_BK:?set FLASH_BK}; LT=${LT:-$HOME/.platformio/penv/.libretiny/bin/python}
ARGS=(); [ -n "$2" ] && ARGS=(-s "$2" -l "${3:?length}")
WANT=$(( ${3:-${SIZE:-2097152}} ))
: > "$T.log"
ok=
for i in 1 2 3; do
echo "### try $i" >> "$T.log"
rm -f "$T.bin"
timeout 900 "$LT" "$FB" flash read -d "$P" "${ARGS[@]}" "${FAMILY:-beken-7238}" "$T.bin" >> "$T.log" 2>&1 &&
[ "$(wc -c < "$T.bin" | tr -d ' ')" = "$WANT" ] && ok=1 && break
sleep 3
done
[ -n "$ok" ] || { echo "FAIL: read $T (expected $WANT bytes, see $T.log)"; exit 1; }
shasum -a 256 "$T.bin"
@@ -0,0 +1,39 @@
# Add to a copy of a bluetooth_proxy config: packages: {cp_inject: !include cp-inject.yaml}
esphome:
includes:
- cp_inject.hpp
logger:
level: VERBOSE
logs:
esp32_ble_tracker: DEBUG
bluetooth_proxy: DEBUG
bluetooth_connection: DEBUG
api: DEBUG
api.service: DEBUG
api.connection: DEBUG
api.socket: DEBUG
scheduler: DEBUG
sensor: DEBUG
component: DEBUG
button:
- platform: template
name: Inject conn param events
# The handlers push into a queue that takes one writer only, the Bluetooth task. Stop the scan (and keep the
# proxy free of real connections) so nothing else writes while the button does.
on_press:
- esp32_ble_tracker.stop_scan:
- wait_until:
condition:
lambda: return !esp32_ble_tracker::global_esp32_ble_tracker->scan_running();
timeout: 5s
- delay: 1s
- lambda: |-
if (esp32_ble_tracker::global_esp32_ble_tracker->scan_running()) {
ESP_LOGE("cpinject", "scan still running after 5 s, nothing injected");
return;
}
cpinject::run();
- esp32_ble_tracker.start_scan:
continuous: true
@@ -0,0 +1,68 @@
#pragma once
// Feeds fabricated conn param update and disconnect events into ESP32BLE's static handlers.
// The event queue takes a single writer: call run() only while scanning is stopped and no connection is active.
#include <cstring>
#include "esphome/components/esp32_ble/ble.h"
#include "esphome/core/log.h"
namespace cpinject {
using GapFn = void (*)(esp_gap_ble_cb_event_t, esp_ble_gap_cb_param_t *);
using GattcFn = void (*)(esp_gattc_cb_event_t, esp_gatt_if_t, esp_ble_gattc_cb_param_t *);
GapFn steal_gap();
GattcFn steal_gattc();
// Explicit instantiation ignores access checks, which exposes the protected static handlers.
template<GapFn F> struct GapThief {
friend GapFn steal_gap() { return F; }
};
template<GattcFn F> struct GattcThief {
friend GattcFn steal_gattc() { return F; }
};
template struct GapThief<&esphome::esp32_ble::ESP32BLE::gap_event_handler>;
template struct GattcThief<&esphome::esp32_ble::ESP32BLE::gattc_event_handler>;
static const char *const TAG = "cpinject";
inline void peer(uint8_t n, uint8_t *bda) {
const uint8_t base[6] = {0xC0, 0xFF, 0xEE, 0x00, 0x00, 0x00};
memcpy(bda, base, 6);
bda[5] = n;
}
inline void update(uint8_t n, int status, int times) {
for (int i = 0; i < times; i++) {
esp_ble_gap_cb_param_t p{};
peer(n, p.update_conn_params.bda);
p.update_conn_params.status = (esp_bt_status_t) status;
p.update_conn_params.conn_int = 24;
p.update_conn_params.timeout = 400;
steal_gap()(ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT, &p);
}
}
inline void disconnect(uint8_t n) {
esp_ble_gattc_cb_param_t p{};
peer(n, p.disconnect.remote_bda);
p.disconnect.reason = ESP_GATT_CONN_TERMINATE_PEER_USER;
p.disconnect.conn_id = 0xEE;
// 0xFE matches no registered client, so the queued event is ignored by every connection.
steal_gattc()(ESP_GATTC_DISCONNECT_EVT, 0xFE, &p);
}
inline void run() {
ESP_LOGI(TAG, "STEP1 peers 1-4 fail 5x each (3 slots)");
for (uint8_t n = 1; n <= 4; n++)
update(n, 6, 5);
ESP_LOGI(TAG, "STEP2 peer 1 succeeds, then fails 3x");
update(1, 0, 1);
update(1, 6, 3);
ESP_LOGI(TAG, "STEP3 peer 2 disconnects, then fails 3x");
disconnect(2);
update(2, 6, 3);
ESP_LOGI(TAG, "STEP4 peer 4 fails 3x, slots still full");
update(4, 6, 3);
ESP_LOGI(TAG, "STEP5 peer 3 disconnects, peer 4 fails 3x");
disconnect(3);
update(4, 6, 3);
ESP_LOGI(TAG, "STEP6 done");
}
} // namespace cpinject
@@ -0,0 +1,156 @@
# Waveshare ESP32-S3 (any ESP32 with BLE) as the central. run.sh passes name, io, auth, idf and server (the
# server's BLE MAC from its esp32_ble dump) with -s. ble_client never pairs by itself: the Pair button calls pair().
esphome:
name: ${name}
esp32:
board: esp32-s3-devkitc-1
variant: esp32s3
flash_size: 16MB
framework:
type: esp-idf
version: ${idf}
logger:
hardware_uart: USB_SERIAL_JTAG
level: VERBOSE
logs:
esp32_ble_tracker: DEBUG
api: DEBUG
api.connection: DEBUG
api.service: DEBUG
api.socket: DEBUG
scheduler: DEBUG
component: DEBUG
wifi: DEBUG
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
api:
reboot_timeout: 0s
ota:
- platform: esphome
esp32_ble:
io_capability: ${io}
auth_req_mode: ${auth}
esp32_ble_tracker:
ble_client:
- mac_address: ${server}
id: cli
on_connect:
- logger.log: "CLI connected"
on_disconnect:
- logger.log: "CLI disconnected"
on_numeric_comparison_request:
- logger.log:
format: "CLI numeric comparison %06u"
args: ["(unsigned) passkey"]
- ble_client.numeric_comparison_reply:
id: cli
accept: true
text_sensor:
- platform: ble_client
ble_client_id: cli
id: secure_value
name: Secure value
service_uuid: "180F"
characteristic_uuid: "2A19"
update_interval: never
on_value:
- logger.log:
format: "CLI secure read: %s"
args: ["x.c_str()"]
- platform: ble_client
ble_client_id: cli
id: open_value
name: Open value
service_uuid: 5ec50000-0000-4000-8000-00000000f000
characteristic_uuid: 5ec50000-0000-4000-8000-00000000f001
update_interval: never
on_value:
- logger.log:
format: "CLI open read: %s"
args: ["x.c_str()"]
- platform: ble_client
ble_client_id: cli
id: mitm_value
name: Mitm value
service_uuid: 5ec50000-0000-4000-8000-00000000f000
characteristic_uuid: 5ec50000-0000-4000-8000-00000000f004
update_interval: never
on_value:
- logger.log:
format: "CLI mitm read: %s"
args: ["x.c_str()"]
- platform: ble_client
ble_client_id: cli
id: notify_value
name: Notify value
service_uuid: 5ec50000-0000-4000-8000-00000000f000
characteristic_uuid: 5ec50000-0000-4000-8000-00000000f003
notify: true
on_value:
- logger.log:
format: "CLI notification: %s"
args: ["x.c_str()"]
button:
- platform: template
name: Subscribe
on_press:
- lambda: |-
// ble_client drops its service list after discovery; ESP-IDF's GATT server puts the CCCD right after
// the characteristic value, so write handle + 1
uint16_t chr = id(notify_value)->handle;
if (chr == 0) { ESP_LOGW("CLI", "notify characteristic handle unknown"); return; }
auto reg = esp_ble_gattc_register_for_notify(id(cli)->get_gattc_if(), id(cli)->get_remote_bda(), chr);
if (reg != ESP_OK) { ESP_LOGW("CLI", "register_for_notify failed: %d", reg); return; }
uint8_t on[2] = {1, 0};
auto err = esp_ble_gattc_write_char_descr(id(cli)->get_gattc_if(), id(cli)->get_conn_id(), chr + 1, 2, on,
ESP_GATT_WRITE_TYPE_RSP, ESP_GATT_AUTH_REQ_NONE);
ESP_LOGI("CLI", "CCCD write to handle %u (char %u) sent, err %d", chr + 1, chr, err);
- platform: template
name: Pair
on_press:
- lambda: 'ESP_LOGI("CLI", "pair() returned %d", (int) id(cli)->pair());'
- platform: template
name: Read secure
on_press:
- component.update: secure_value
- platform: template
name: Read mitm
on_press:
- component.update: mitm_value
- platform: template
name: Read open
on_press:
- component.update: open_value
- platform: template
name: Write secure
on_press:
- ble_client.ble_write:
id: cli
service_uuid: 5ec50000-0000-4000-8000-00000000f000
characteristic_uuid: 5ec50000-0000-4000-8000-00000000f002
value: [0x68, 0x65, 0x6C, 0x6C, 0x6F]
- platform: template
name: Disconnect
on_press:
- ble_client.disconnect: cli
- platform: template
name: Connect
on_press:
- ble_client.connect: cli
- platform: template
name: Remove bond
on_press:
- ble_client.remove_bond:
id: cli
@@ -0,0 +1,60 @@
"""Press the client's buttons in order and log every client line about BLE security.
usage: drive.py CLIENT_HOST OUT STEP... STEP: a button name, or wait:SECONDS env: API_KEY
"""
import asyncio
import os
import pathlib
import re
import sys
import time
from aioesphomeapi import APIClient, ButtonInfo, LogLevel
HOST, OUT, STEPS = sys.argv[1], sys.argv[2], sys.argv[3:]
LOG = pathlib.Path(OUT).open("w", encoding="utf-8") # noqa: SIM115 open for the whole run
PATTERN = re.compile(
r"CLI|ble_client|ble_text_sensor|esp32_ble_client|[Aa]uth|[Ee]ncrypt|[Bb]ond|Error|status=|pair"
)
def note(s: str) -> None:
line = f"{time.strftime('%H:%M:%S')} {s}"
print(line)
LOG.write(line + "\n")
LOG.flush()
async def main() -> None:
c = APIClient(HOST, 6053, None, noise_psk=os.environ.get("API_KEY"))
for attempt in range(40):
try:
await c.connect(login=True)
break
except Exception as err: # noqa: BLE001
last_err = err
note(f"connect attempt {attempt + 1} failed: {err!r}")
await asyncio.sleep(2)
else:
raise last_err
ents, _ = await c.list_entities_services()
btn = {e.name: e.key for e in ents if isinstance(e, ButtonInfo)}
def on_log(m) -> None:
t = re.sub(r"\x1b\[[0-9;]*m", "", m.message.decode(errors="replace"))
if PATTERN.search(t):
note("LOG " + t.strip().replace("\n", " | "))
c.subscribe_logs(on_log, log_level=LogLevel.LOG_LEVEL_DEBUG)
for step in STEPS:
if step.startswith("wait:"):
await asyncio.sleep(float(step[5:]))
continue
note(f"PRESS {step}")
c.button_command(btn[step])
await asyncio.sleep(4)
await c.disconnect()
asyncio.run(main())
@@ -0,0 +1,33 @@
#!/bin/bash
# usage: run.sh TAG IO AUTH build and flash the server (serial) and the client (OTA), then pair once and reconnect twice
# Copy this directory into a scratch directory with a secrets.yaml (wifi_ssid, wifi_password) and run it there.
# IO/AUTH: none bond (Just Works) or display_yes_no sc_mitm_bond (numeric comparison, MITM).
# env: TREE (esphome checkout for the client), SERVER_TREE (checkout with esp32_ble_server security, #17562 or
# later; default TREE), SERVER_PORT (devkit serial port), CLIENT_HOST (client address), SERVER_BLE_MAC (from the
# server's esp32_ble dump), SC (path to serial_capture.py), IDF (default recommended), PY (default $TREE/venv/bin/python)
# A server keeps its bonds in NVS and refuses a weaker re-pairing: erase its flash before switching from nc to jw.
D=$(cd "$(dirname "$0")" && pwd); G=${1:?tag}; IO=${2:?io}; AUTH=${3:?auth}; T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}
P=${SERVER_PORT:?set SERVER_PORT}; C=${CLIENT_HOST:?set CLIENT_HOST}; MAC=${SERVER_BLE_MAC:?set SERVER_BLE_MAC}; SC=${SC:?set SC}
E=(-s io "$IO" -s auth "$AUTH" -s idf "${IDF:-recommended}")
ST=${SERVER_TREE:-$T}
build() { local t=$1; shift; (cd "$t" && PYTHONUNBUFFERED=1 timeout 1800 $PY -m esphome "$@"); }
ok=
for i in 1 2 3; do
build "$ST" -s name "bss-$G" "${E[@]}" run --no-logs "$D/server.yaml" --device "$P" > "$D/server-$G-upload.log" 2>&1 && ok=1 && break
sleep 5
done
[ -n "$ok" ] || { echo "FAIL: server build or flash (does SERVER_TREE have #17562?)"; exit 1; }
build "$T" -s name "bsc-$G" "${E[@]}" -s server "$MAC" run --no-logs "$D/client.yaml" --device "$C" > "$D/client-$G-upload.log" 2>&1 ||
{ echo "FAIL: client build or upload"; exit 1; }
rm -f "$D/server-$G.txt"
$PY "$SC" "$P" 330 "$D/server-$G.txt" --reset > /dev/null 2>&1 & CAP=$!
trap 'kill $CAP 2>/dev/null' EXIT
sleep 25
R=("Disconnect" "wait:3" "Connect" "wait:10" "Pair" "wait:5" "Read secure" "Read mitm")
$PY "$D/drive.py" "$C" "$D/client-$G.txt" "wait:6" "Remove bond" "Disconnect" "wait:3" "Connect" "wait:10" \
"Read secure" "Read mitm" "Write secure" "Subscribe" "wait:8" "Pair" "wait:6" "Read secure" "Read mitm" "Write secure" \
"Subscribe" "wait:10" "${R[@]}" "${R[@]}" > /dev/null || { echo "FAIL: driver"; exit 1; }
wait $CAP; CAPRC=$?; trap - EXIT
[ "$CAPRC" = 0 ] && [ -s "$D/server-$G.txt" ] || { echo "FAIL: server capture failed or empty (rc $CAPRC)"; exit 1; }
MODE=jw; [ "$IO" = none ] || MODE=nc
$PY "$D/summary.py" "$MODE" "$D/client-$G.txt" "$D/server-$G.txt"
@@ -0,0 +1,85 @@
# Classic ESP32 devkit as the secure GATT server. run.sh passes name, io (none or display_yes_no),
# auth (bond or sc_mitm_bond) and idf (recommended, or a version such as 5.5.5) with -s.
# Needs esp32_ble_server security from #17562 (read_encrypt, numeric comparison); build it with SERVER_TREE.
esphome:
name: ${name}
esp32:
board: esp32dev
framework:
type: esp-idf
version: ${idf}
logger:
level: DEBUG
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
api:
reboot_timeout: 0s
ota:
- platform: esphome
esp32_ble:
io_capability: ${io}
auth_req_mode: ${auth}
esp32_ble_server:
id: srv
on_connect:
- logger.log: "SRV client connected"
on_disconnect:
- logger.log: "SRV client disconnected"
on_numeric_comparison_request:
- logger.log:
format: "SRV numeric comparison %06u"
args: ["(unsigned) passkey"]
- ble_server.numeric_comparison_reply:
id: srv
address: !lambda return address;
accept: true
services:
- uuid: "180F"
characteristics:
- uuid: "2A19"
read: true
read_encrypt: true
value:
data: "99.9"
- uuid: 5ec50000-0000-4000-8000-00000000f000
characteristics:
- uuid: 5ec50000-0000-4000-8000-00000000f001
read: true
value:
data: "open"
- uuid: 5ec50000-0000-4000-8000-00000000f002
write: true
write_encrypt: true
on_write:
- lambda: 'ESP_LOGI("SRV", "secure write received: %s", std::string(x.begin(), x.end()).c_str());'
- uuid: 5ec50000-0000-4000-8000-00000000f004
read: true
read_encrypt_mitm: true
value:
data: "mitm"
- uuid: 5ec50000-0000-4000-8000-00000000f003
id: secure_notify
read: true
read_encrypt: true
notify: true
value:
data: "n0"
interval:
- interval: 2s
then:
- lambda: |-
static int n = 0;
char buf[12];
snprintf(buf, sizeof(buf), "n%d", ++n);
id(secure_notify)->set_value((const uint8_t *) buf, strlen(buf));
- ble_server.characteristic.notify:
id: secure_notify
@@ -0,0 +1,80 @@
"""Judge one run.sh run from the client log (drive.py output) and the server's serial capture.
usage: summary.py MODE CLIENT_LOG SERVER_CAPTURE MODE: jw (Just Works) or nc (numeric comparison, MITM)
Before the first Pair: the encrypted and MITM reads must each be tried and refused (an `Error reading char` reply),
no notification may arrive and no encrypted write may reach the server. After it: the encrypted read returns 99.9,
exactly one write (the paired one) reaches the server, the second Subscribe brings notifications, and the MITM-only
characteristic is readable only after an nc pairing. Prints the reconnect pattern and PASS or FAIL.
"""
import pathlib
import re
import sys
MODE = sys.argv[1]
cli = pathlib.Path(sys.argv[2]).read_text(encoding="utf-8").splitlines()
srv = re.sub(
r"\x1b\[[0-9;]*m",
"",
pathlib.Path(sys.argv[3]).read_bytes().decode(errors="replace"),
)
pair_at = next((i for i, line in enumerate(cli) if "PRESS Pair" in line), None)
if pair_at is None:
sys.exit("FAIL: no Pair step in the client log")
before, after = cli[:pair_at], cli[pair_at:]
subs = [i for i, line in enumerate(after) if "PRESS Subscribe" in line]
after_sub = after[subs[0] :] if subs else []
def count(lines: list[str], pat: str) -> int:
return sum(1 for line in lines if re.search(pat, line))
def outcome(lines: list[str], button: str, ok_pat: str) -> str:
"""'ok', 'refused' or 'none' for the first press of BUTTON.
The window runs to the next read, pair or connection step, since a reply can come after a write press. A value
wins over an error line: the error can belong to another characteristic read in the same window.
"""
start = next((i for i, line in enumerate(lines) if f"PRESS {button}" in line), None)
if start is None:
return "none"
window = []
for line in lines[start + 1 :]:
if re.search(r"PRESS (Read|Pair|Disconnect|Connect|Subscribe|Remove)", line):
break
window.append(line)
if any(re.search(ok_pat, line) for line in window):
return "ok"
return "refused" if any("Error reading char" in line for line in window) else "none"
secure_before = outcome(before, "Read secure", r"secure read: 9")
mitm_before = outcome(before, "Read mitm", r"mitm read: m")
mitm_after = outcome(after, "Read mitm", r"mitm read: m")
writes = srv.count("secure write received")
checks = {
f"encrypted read refused before pairing ({secure_before})": secure_before
== "refused",
f"MITM read refused before pairing ({mitm_before})": mitm_before == "refused",
"no notifications before pairing": count(before, r"notification: n") == 0,
"encrypted read after pairing": outcome(after, "Read secure", r"secure read: 99\.9")
== "ok",
# one Write secure press before Pair (must be refused) and one after it
f"only the paired write reached the server ({writes})": writes == 1,
"notifications after subscribing paired": count(after_sub, r"notification: n") > 0,
}
if MODE == "nc":
checks[f"MITM read after nc pairing ({mitm_after})"] = mitm_after == "ok"
else:
checks[f"MITM read still refused after Just Works ({mitm_after})"] = (
mitm_after == "refused"
)
for name, ok in checks.items():
print(f"{'ok ' if ok else 'FAIL'} {name}")
print(
f"server: {srv.count('Authentication complete')} authentications, {srv.count('SRV numeric comparison')} numeric "
f"comparisons, {srv.count('Deleting unpaired device')} bonds dropped by the stack"
)
print("PASS" if all(checks.values()) else "FAIL")
sys.exit(0 if all(checks.values()) else 1)
@@ -0,0 +1,90 @@
"""Match each proxy disconnect with the peer's own disconnect line and count the links the peer kept.
Usage: an.py DIR LABEL [ROUNDS] reads LABEL-drive.txt, LABEL-peer.txt (serial_capture --ms) and LABEL-proxy.txt
(esphome logs, VERBOSE). A round counts only when the last `Conn params updated` the proxy logged since the previous
disconnect shows latency=10; otherwise it is inconclusive. Exits 1 when the peer kept a link past 3 s (the terminate
was lost), a round was inconclusive, or fewer than ROUNDS rounds completed."""
import datetime as dt
from pathlib import Path
import re
import sys
D, label = Path(sys.argv[1]), sys.argv[2]
ROUNDS = int(sys.argv[3]) if len(sys.argv) > 3 else None
def read(name: str) -> list[str]:
return (
(D / f"{label}-{name}.txt")
.read_text(encoding="utf-8", errors="replace")
.splitlines()
)
def ptime(line: str) -> float | None:
"""Seconds since midnight from a leading [HH:MM:SS.mmm] stamp."""
m = re.match(r"\[(\d+):(\d+):(\d+)\.(\d+)\]", line)
return (
int(m[1]) * 3600 + int(m[2]) * 60 + int(m[3]) + int(m[4]) / 1000 if m else None
)
pdisc = [
t
for line in read("peer")
if "PEER DISCONNECT" in line and (t := ptime(line)) is not None
]
params = [
(t, int(m[1]))
for line in read("proxy")
if "Conn params updated" in line
and (m := re.search(r"latency=(\d+)", line))
and (t := ptime(line)) is not None
]
res = []
prev = -1.0
for line in read("drive"):
m = re.search(
r"R(\d+) .*DISC_CALL ([\d.]+) DISC_DONE ([\d.]+) \(\+([\d.]+)s\)", line
)
if not m:
if line.startswith("R"):
print(" ", line)
continue
# Both captures stamp local wall clock time; compare as seconds since midnight.
t = dt.datetime.fromtimestamp(float(m[2])).astimezone()
tc = t.hour * 3600 + t.minute * 60 + t.second + t.microsecond / 1e6
after = [p - tc for p in pdisc if -1 < p - tc < 12]
window = [lat for pt, lat in params if prev < pt <= tc]
res.append(
(
int(m[1]),
float(m[4]),
after[0] if after else None,
window[-1] if window else None,
)
)
prev = tc
for r, done, pd, lat in res:
peer = (
f"peer disconnect +{pd:.2f}s" if pd is not None else "peer disconnect not seen"
)
print(f" R{r:2} central done +{done:.3f}s {peer} latency at disconnect {lat}")
late = sum(1 for _, _, pd, lat in res if lat == 10 and (pd is None or pd > 3))
inconclusive = sum(1 for *_, lat in res if lat != 10)
print(
f"{label}: rounds {len(res)}, peer kept the link (>3 s or not seen) {late}, inconclusive {inconclusive}"
)
failed = []
if not res:
failed.append("no round completed")
if ROUNDS is not None and len(res) < ROUNDS:
failed.append(f"only {len(res)} of {ROUNDS} rounds completed")
if late:
failed.append(f"{late} links kept")
if inconclusive:
failed.append(
f"INCONCLUSIVE: {inconclusive} rounds had no latency=10 update before the disconnect"
)
print(f"PASS: {label}" if not failed else f"FAIL: {label}: " + "; ".join(failed))
sys.exit(1 if failed else 0)
@@ -0,0 +1,100 @@
"""Connect to the peer through the proxy, read its services, idle, disconnect; print host timestamps per round.
Usage: btdrive.py PROXY KEY PEER_MAC ROUNDS IDLE_S"""
import asyncio
import sys
import time
from aioesphomeapi import APIClient, APIConnectionError
async def main(host: str, key: str, peer: str, rounds: int, idle: float) -> int:
addr = int(peer.replace(":", ""), 16)
cli = APIClient(host, 6053, None, noise_psk=key)
await cli.connect(login=True)
info = await cli.device_info()
print(f"proxy {info.name} bt_mac {info.bluetooth_mac_address}", flush=True)
seen = 0
def adv(msg) -> None:
nonlocal seen
seen += sum(a.address == addr for a in msg.advertisements)
# The proxy only connects to a device its scanner has seen.
cli.subscribe_bluetooth_le_raw_advertisements(adv)
await asyncio.sleep(5)
print(f"peer advertisements seen in 5 s: {seen}", flush=True)
if not seen:
print("FAIL: the proxy does not see the peer", flush=True)
await cli.disconnect()
return 1
done = 0
for r in range(1, rounds + 1):
state: asyncio.Queue = asyncio.Queue()
def cb(
connected: bool, mtu: int, err: int, state: asyncio.Queue = state
) -> None:
state.put_nowait((connected, err, time.time()))
t0 = time.time()
try:
cancel = await cli.bluetooth_device_connect(
addr, cb, timeout=20, address_type=0, feature_flags=0xFF
)
except (APIConnectionError, TimeoutError) as e:
print(f"R{r} CONNECT ERROR {type(e).__name__}", flush=True)
await asyncio.sleep(9)
continue
try:
c, err, t = await asyncio.wait_for(state.get(), 25)
except TimeoutError:
print(f"R{r} CONNECT TIMEOUT", flush=True)
cancel()
await asyncio.sleep(8)
continue
if not c:
print(f"R{r} CONNECT FAIL err {err} after {t - t0:.2f}s", flush=True)
cancel()
await asyncio.sleep(8)
continue
try:
n = len((await cli.bluetooth_gatt_get_services(addr)).services)
except (APIConnectionError, TimeoutError) as e:
n = f"err {e!r}"
await asyncio.sleep(idle)
td = time.time()
await cli.bluetooth_device_disconnect(addr)
try:
c2, err2, t2 = await asyncio.wait_for(state.get(), 15)
if c2 or not isinstance(n, int):
# an unexpected connect state or a failed service read: the round did not run as intended
print(
f"R{r} BAD ROUND services {n} connected {c2} err {err2}", flush=True
)
else:
print(
f"R{r} services {n} DISC_CALL {td:.3f} DISC_DONE {t2:.3f} (+{t2 - td:.3f}s) err {err2}",
flush=True,
)
done += 1
except TimeoutError:
print(
f"R{r} services {n} DISC_CALL {td:.3f} no disconnect state", flush=True
)
cancel()
await asyncio.sleep(
9
) # a peer that missed the terminate hits its 6 s supervision timeout in this gap
await cli.disconnect()
print(f"rounds completed {done} of {rounds}", flush=True)
return 0 if done == rounds else 1
sys.exit(
asyncio.run(
main(
sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4]), float(sys.argv[5])
)
)
)
@@ -0,0 +1,17 @@
#pragma once
#include <cstring>
#include <esp_gap_ble_api.h>
#include "esphome/core/log.h"
#include "central_bda.hpp" // written by run.sh from PROXY_BT_MAC
// 50 ms interval, peripheral latency 10, 6 s supervision timeout
inline void btpeer_request_latency() {
esp_ble_conn_update_params_t p{};
memcpy(p.bda, CENTRAL_BDA, 6);
p.min_int = 40;
p.max_int = 40;
p.latency = 10;
p.timeout = 600;
esp_err_t err = esp_ble_gap_update_conn_params(&p);
ESP_LOGI("peer", "requested interval 50 ms latency 10 timeout 6 s: %d", err);
}
@@ -0,0 +1,36 @@
esphome:
name: btpeer
includes:
- btpeer.hpp
- central_bda.hpp
esp32:
board: esp32dev
framework:
type: esp-idf
logger:
level: VERBOSE
logs:
esp32_ble: VERBOSE
scheduler: DEBUG
component: DEBUG
esp32_ble:
max_connections: 1
esp32_ble_server:
manufacturer: test
on_connect:
- lambda: ESP_LOGI("peer", "PEER CONNECT conn %u", (unsigned) id);
- delay: 4s
- lambda: btpeer_request_latency();
on_disconnect:
- lambda: ESP_LOGI("peer", "PEER DISCONNECT conn %u", (unsigned) id);
services:
- uuid: 6e400001-b5a3-f393-e0a9-e50e24dcca9e
advertise: true
characteristics:
- uuid: 6e400002-b5a3-f393-e0a9-e50e24dcca9e
read: true
value: "peer"
@@ -0,0 +1,44 @@
substitutions:
name: btproxy
esphome:
name: ${name}
esp32:
board: esp32-s3-devkitc-1
variant: esp32s3
flash_size: 16MB
framework:
type: esp-idf
logger:
hardware_uart: USB_SERIAL_JTAG
level: VERBOSE
logs:
scheduler: DEBUG
component: DEBUG
esp32_ble_tracker: DEBUG
ethernet:
type: W5500
clk_pin: GPIO13
mosi_pin: GPIO11
miso_pin: GPIO12
cs_pin: GPIO14
interrupt_pin: GPIO10
reset_pin: GPIO9
api:
encryption:
key: !secret api_key
reboot_timeout: 0s
ota:
- platform: esphome
esp32_ble_tracker:
scan_parameters:
active: false
bluetooth_proxy:
active: true
+31
View File
@@ -0,0 +1,31 @@
#!/bin/bash
# usage: run.sh LABEL ROUNDS build both boards, then ROUNDS connect/disconnect rounds through the proxy
# Copy this directory into a scratch directory with a secrets.yaml (api_key, base64 Noise key) and run it there.
# env: TREE (esphome checkout to build the proxy from), PORT (peer devkit serial port), PROXY (proxy address, flashed
# over the air; the first flash of a fresh board goes over USB), PROXY_BT_MAC (the proxy's Bluetooth MAC, printed by
# btdrive.py as bt_mac), PEER_MAC (the peer's Bluetooth MAC, base MAC + 2 on a classic ESP32), SC (path to
# serial_capture.py), PY (checkout python), PEER_TREE (checkout for the peer, defaults to TREE)
D=$(cd "$(dirname "$0")" && pwd); L=${1:?label}; N=${2:-12}; T=${TREE:?set TREE}; PT=${PEER_TREE:-$T}
P=${PORT:?set PORT}; S3=${PROXY:?set PROXY}; SC=${SC:?set SC}; PY=${PY:-$T/venv/bin/python}
PEER=${PEER_MAC:?set PEER_MAC}; CM=${PROXY_BT_MAC:?set PROXY_BT_MAC}
KEY=$(sed -n 's/^api_key: *"\{0,1\}\([^"]*\)"\{0,1\}$/\1/p' "$D/secrets.yaml")
[ -n "$KEY" ] || { echo "FAIL: no api_key in secrets.yaml"; exit 1; }
cd "$D" || exit 1
printf '#pragma once\n#include <cstdint>\nstatic const uint8_t CENTRAL_BDA[6] = {0x%s};\n' "${CM//:/, 0x}" > central_bda.hpp
(cd "$PT" && PYTHONUNBUFFERED=1 timeout 1500 $PY -m esphome run --no-logs "$D/btpeer.yaml" --device "$P" > "$D/$L-peer-upload.log" 2>&1) \
|| { echo "FAIL: peer build or upload failed"; exit 1; }
(cd "$T" && PYTHONUNBUFFERED=1 timeout 1500 $PY -m esphome run --no-logs "$D/btproxy.yaml" --device "$S3" > "$D/$L-proxy-upload.log" 2>&1) \
|| { echo "FAIL: proxy build or upload failed"; exit 1; }
SECS=$((N * 26 + 40))
pkill -f "[s]erial_capture.py $P"
$PY "$SC" "$P" $SECS "$D/$L-peer.txt" --ms > /dev/null 2>&1 & CAP=$!
(cd "$T" && PYTHONUNBUFFERED=1 exec timeout $((SECS - 10)) $PY -m esphome logs "$D/btproxy.yaml" --device "$S3" > "$D/$L-proxy.txt" 2>&1) & LOGS=$!
trap 'kill $CAP $LOGS 2>/dev/null' EXIT
sleep 6
$PY "$D/btdrive.py" "$S3" "$KEY" "$PEER" "$N" 10 > "$D/$L-drive.txt" 2>&1; RC=$?
sleep 10
kill $CAP $LOGS 2>/dev/null; wait 2>/dev/null; trap - EXIT
[ -s "$D/$L-peer.txt" ] || { tail -3 "$D/$L-drive.txt"; echo "FAIL: peer capture got nothing"; exit 1; }
$PY "$D/an.py" "$D" "$L" "$N"; ARC=$?
[ "$RC" = 0 ] || { tail -1 "$D/$L-drive.txt"; echo "FAIL: driver rc $RC (not every round completed)"; exit 1; }
exit $ARC
@@ -0,0 +1,45 @@
# Classic ESP32 devkit: RTC pins 25 26 27 32 33 and digital pins 19 21 22 23, three rounds 5 s after boot.
esphome:
name: gpio-hold-esp32
includes:
- hold_test.hpp
on_boot:
priority: -100
then:
- delay: 5s
- lambda: |-
static const int pins[] = {25, 26, 27, 32, 33, 19, 21, 22, 23};
for (int r = 1; r <= 3; r++) holdtest::run(pins, sizeof(pins) / sizeof(pins[0]), r);
esp32:
board: esp32dev
framework:
type: esp-idf
logger:
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
api:
reboot_timeout: 0s
ota:
- platform: esphome
# Turns on USE_GPIO_HOLD.
output:
- platform: gpio
id: held_out
pin:
number: GPIO4
hold_state: true
button:
- platform: template
name: rerun
on_press:
- lambda: |-
static const int pins[] = {25, 26, 27, 32, 33, 19, 21, 22, 23};
holdtest::run(pins, sizeof(pins) / sizeof(pins[0]), 9);
@@ -0,0 +1,41 @@
# Waveshare ESP32-S3-ETH: RTC pins 16 17 and digital pin 43 are free; a round every 15 s.
esphome:
name: gpio-hold-esp32s3
includes:
- hold_test.hpp
esp32:
board: esp32-s3-devkitc-1
variant: esp32s3
flash_size: 16MB
framework:
type: esp-idf
logger:
hardware_uart: USB_SERIAL_JTAG
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
api:
reboot_timeout: 0s
ota:
- platform: esphome
# Turns on USE_GPIO_HOLD.
output:
- platform: gpio
id: held_out
pin:
number: GPIO44
hold_state: true
interval:
- interval: 15s
then:
- lambda: |-
static int round = 0;
static const int pins[] = {16, 17, 43};
holdtest::run(pins, sizeof(pins) / sizeof(pins[0]), ++round);
@@ -0,0 +1,93 @@
#pragma once
#include "esphome/components/esp32/gpio.h"
#include "esphome/core/log.h"
#include <driver/gpio.h>
#include <driver/rtc_io.h>
// Drives held pads through the ISR pin API and reads the pad back.
namespace holdtest {
using esphome::esp32::ESP32InternalGPIOPin;
namespace gpio = esphome::gpio;
static const char *const TAG = "holdtest";
// One pin and one ISR argument block per GPIO and hold setting, made on first use and reused by later rounds,
// so a test that repeats forever does not use up the heap.
struct PinPair {
ESP32InternalGPIOPin *pin{nullptr};
esphome::ISRInternalGPIOPin isr;
};
static PinPair pairs[2][GPIO_NUM_MAX];
static PinPair &get(int num, bool hold) {
PinPair &pp = pairs[hold][num];
if (pp.pin == nullptr) {
pp.pin = new ESP32InternalGPIOPin(); // NOLINT
pp.pin->set_pin(static_cast<gpio_num_t>(num));
pp.pin->set_flags(gpio::FLAG_INPUT | gpio::FLAG_OUTPUT | (hold ? gpio::FLAG_HOLD : gpio::FLAG_NONE));
pp.isr = pp.pin->to_isr();
}
pp.pin->setup(); // the previous round left the pad unheld with no mode
return pp;
}
static int lvl(int num) {
esphome::delayMicroseconds(50);
return gpio_get_level(static_cast<gpio_num_t>(num));
}
// Returns failures for one pin.
static int run_pin(int num, bool hold) {
int fail = 0;
auto &isr = get(num, hold).isr;
isr.pin_mode(gpio::FLAG_INPUT | gpio::FLAG_OUTPUT);
int wr_ok = 0;
for (int i = 0; i < 20; i++) {
bool v = i & 1;
isr.digital_write(v);
if (lvl(num) == (int) v) {
wr_ok++;
} else {
fail++;
}
}
// Control: a raw register write without a hold refresh must not reach a held pad.
int before = lvl(num);
gpio_set_level(static_cast<gpio_num_t>(num), !before);
int ctrl = lvl(num);
bool ctrl_ok = hold ? (ctrl == before) : (ctrl != before);
if (!ctrl_ok)
fail++;
isr.digital_write(before); // back in sync
// Pulls through the ISR pin_mode: input must toggle in the flags diff to apply them.
int pd1, pu, pd2;
isr.pin_mode(gpio::FLAG_NONE);
isr.pin_mode(gpio::FLAG_INPUT | gpio::FLAG_PULLDOWN);
pd1 = lvl(num);
isr.pin_mode(gpio::FLAG_NONE);
isr.pin_mode(gpio::FLAG_INPUT | gpio::FLAG_PULLUP);
pu = lvl(num);
isr.pin_mode(gpio::FLAG_NONE);
isr.pin_mode(gpio::FLAG_INPUT | gpio::FLAG_PULLDOWN);
pd2 = lvl(num);
if (pd1 != 0 || pu != 1 || pd2 != 0)
fail++;
ESP_LOGI(TAG, "GPIO%d hold=%d rtc=%d write %d/20 control %s pulls pd=%d pu=%d pd=%d -> %s", num, hold,
(int) rtc_gpio_is_valid_gpio(static_cast<gpio_num_t>(num)), wr_ok, ctrl_ok ? "ok" : "BAD", pd1, pu, pd2,
fail ? "FAIL" : "PASS");
// Leave the pad free for the next run.
if (hold)
gpio_hold_dis(static_cast<gpio_num_t>(num));
isr.pin_mode(gpio::FLAG_NONE);
return fail;
}
static void run(const int *pins, int n, int round) {
int fail = 0;
for (int i = 0; i < n; i++) {
fail += run_pin(pins[i], true);
fail += run_pin(pins[i], false);
}
ESP_LOGI(TAG, "ROUND %d %s failures=%d", round, fail ? "FAIL" : "PASS", fail);
}
} // namespace holdtest
@@ -0,0 +1,79 @@
# BK7238 bit banged master; needs the BK72xx software I2C bus from #21586 (dev rejects the pins).
# The ESP32 control is the same i2c, sensor and interval blocks on a devkit (sda GPIO21, scl GPIO22, 25 or 50 kHz).
substitutions:
frequency: 100kHz
esphome:
name: i2cbk
bk72xx:
board: xh-wb3s
logger:
hardware_uart: UART1
level: DEBUG
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
api:
reboot_timeout: 0s
ota:
- platform: esphome
i2c:
id: bus
sda: P26
scl: P24
scan: true
frequency: ${frequency}
timeout: 20ms # clock stretch limit; the bus default (1 ms) is shorter than the slave's 5 ms stretch
sensor:
- platform: hdc1080
address: 0x40
update_interval: 5s
temperature:
name: fake temperature
humidity:
name: fake humidity
globals:
- id: n
type: uint8_t
initial_value: "0"
- id: n_ok
type: uint32_t
initial_value: "0"
- id: n_bad
type: uint32_t
initial_value: "0"
interval:
- interval: 2s
then:
- lambda: |-
uint8_t k = ++id(n);
uint8_t w[4] = {0x20, k, (uint8_t) ~k, 0xA5};
uint32_t t0 = micros();
auto e1 = id(bus)->write(0x40, w, 4);
uint8_t reg = 0x20, r[3] = {0, 0, 0};
auto e2 = id(bus)->write_readv(0x40, &reg, 1, r, 3);
uint32_t t1 = micros();
uint8_t x;
auto e3 = id(bus)->read(0x41, &x, 1);
uint8_t s1 = 0x7E, s2 = 0x7F, rr[2];
uint32_t t2 = micros();
auto e4 = id(bus)->write_readv(0x40, &s1, 1, rr, 2);
uint32_t t3 = micros();
auto e5 = id(bus)->write_readv(0x40, &s2, 1, rr, 2);
uint32_t t4 = micros();
// the absent address must NACK and both clock stretched reads must succeed
bool ok = e1 == 0 && e2 == 0 && r[0] == k && r[1] == (uint8_t) ~k && r[2] == 0xA5 && e3 != 0 && e4 == 0 &&
e5 == 0;
if (ok) id(n_ok)++; else id(n_bad)++;
ESP_LOGI("t", "RW %s e1 %d e2 %d got %02X %02X %02X want %02X %02X A5 | %u us | absent e %d | stretch500 e %d %u us | stretch5ms e %d %u us | ok %u bad %u",
ok ? "OK" : "BAD", e1, e2, r[0], r[1], r[2], k, (uint8_t) ~k, (unsigned) (t1 - t0), e3, e4,
(unsigned) (t3 - t2), e5, (unsigned) (t4 - t3), (unsigned) id(n_ok), (unsigned) id(n_bad));
@@ -0,0 +1,50 @@
#pragma once
#include <Wire.h>
#include "esphome/core/log.h"
// Fake HDC1080 at 0x40: 0x00 temperature (26.0 C), 0x01 humidity (50 %), other registers are a
// 256 byte file; reading 0x7E holds SCL for 500 us, reading 0x7F for 5 ms.
static volatile uint8_t SL_REGS[256];
static volatile uint8_t sl_ptr = 0;
static volatile uint32_t sl_rx = 0, sl_tx = 0, sl_stretch = 0;
static void sl_on_receive(int n) {
if (n < 1)
return;
sl_ptr = Wire.read();
uint8_t p = sl_ptr;
while (--n > 0 && Wire.available())
SL_REGS[p++] = Wire.read();
sl_rx++;
}
static void sl_on_request() {
uint8_t b[8];
uint8_t p = sl_ptr;
sl_tx++;
if (p == 0x7E || p == 0x7F) {
sl_stretch++;
delayMicroseconds(p == 0x7E ? 500 : 5000);
}
for (int i = 0; i < 8; i++)
b[i] = SL_REGS[(uint8_t) (p + i)];
if (p == 0x00) {
b[0] = 0x66;
b[1] = 0x66;
} else if (p == 0x01) {
b[0] = 0x80;
b[1] = 0x00;
}
Wire.write(b, 8);
}
inline void i2cslave_begin() {
Wire.begin(4, 5, 0x40);
Wire.onReceive(sl_on_receive);
Wire.onRequest(sl_on_request);
ESP_LOGI("slave", "I2C slave at 0x40 on SDA GPIO4 SCL GPIO5");
}
inline void i2cslave_report() {
ESP_LOGI("slave", "rx %u tx %u stretch %u", (unsigned) sl_rx, (unsigned) sl_tx, (unsigned) sl_stretch);
}
@@ -0,0 +1,29 @@
esphome:
name: i2cslave
libraries:
- Wire
includes:
- i2cslave.hpp
platformio_options:
board_build.f_cpu: 160000000L
on_boot:
priority: -100
then:
- lambda: i2cslave_begin();
esp8266:
board: d1_mini
logger:
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
ota:
- platform: esphome
interval:
- interval: 10s
then:
- lambda: i2cslave_report();
@@ -0,0 +1,127 @@
"""Time the presence hold on stream-harness.yaml and check presence_timeout survives a restart.
usage: holddrive.py HOST OUT env: API_KEY (when the harness has one)
For timeouts 5 and 0: target frames for 3 s, then empty frames; prints the ms from the "mode none" press to the
has_target off line (up to one 100 ms frame of that is the harness). Then sets 0 and 20, restarts, reads the number.
A missing press line, off line or number state prints NO-DATA and the run exits 1.
"""
import asyncio
import os
import pathlib
import re
import sys
from aioesphomeapi import APIClient, ButtonInfo, LogLevel, NumberInfo, NumberState
HOST, OUT = sys.argv[1], sys.argv[2]
LOG = pathlib.Path(OUT).open("w", encoding="utf-8") # noqa: SIM115 open for the whole run
MISSING = []
def note(s: str) -> None:
print(s)
LOG.write(s + "\n")
LOG.flush()
async def session():
c = APIClient(HOST, 6053, None, noise_psk=os.environ.get("API_KEY"))
for attempt in range(60):
try:
await c.connect(login=True)
break
except Exception as err: # noqa: BLE001
last_err = err
note(f"connect attempt {attempt + 1} failed: {err!r}")
await asyncio.sleep(2)
else:
raise last_err
ents, _ = await c.list_entities_services()
btn = {e.name: e.key for e in ents if isinstance(e, ButtonInfo)}
num = next(
e.key
for e in ents
if isinstance(e, NumberInfo) and e.name == "Presence Timeout"
)
st, lines = {}, []
def on_state(s) -> None:
if isinstance(s, NumberState) and s.key == num:
st["t"] = s.state
def on_log(m) -> None:
t = re.sub(r"\x1b\[[0-9;]*m", "", m.message.decode(errors="replace"))
if "harness" in t:
lines.append(t)
LOG.write("LOG " + t + "\n")
c.subscribe_states(on_state)
c.subscribe_logs(on_log, log_level=LogLevel.LOG_LEVEL_DEBUG)
for _ in range(20):
await asyncio.sleep(1)
if "t" in st:
break
# a freshly booted ESP8266 delays API commands that arrive too early
await asyncio.sleep(8)
return c, btn, num, st, lines
def first_ms(lines: list[str], pat: str) -> int | None:
for line in lines:
if m := re.search(pat + r" at (\d+)", line):
return int(m.group(1))
return None
def number(st: dict, what: str) -> str:
if "t" not in st:
MISSING.append(what)
return "NO-DATA"
return f"{st['t']:g}"
async def hold(c, btn, num, st, lines, timeout: int) -> None:
c.number_command(num, timeout)
await asyncio.sleep(2)
if st.get("t") != timeout:
# dev snaps 0 back to the saved value; the hold is then timed with what the number reads
note(f"HOLD timeout={timeout}: the number reads {st.get('t')}, timing that")
c.button_command(btn["Mode target"])
await asyncio.sleep(3)
lines.clear() # only this run's press and off lines count
c.button_command(btn["Mode none"])
await asyncio.sleep(timeout + 8)
start, off = first_ms(lines, "mode none"), first_ms(lines, "presence raw OFF")
if start is None or off is None or off < start:
MISSING.append(f"hold {timeout}")
note(f"HOLD timeout={timeout}: NO-DATA (press line {start}, off line {off})")
else:
note(
f"HOLD timeout={timeout}: off {off - start} ms after the last target frame"
)
async def main() -> None:
c, btn, num, st, lines = await session()
note(f"START number {number(st, 'start')}")
for t in (5, 0):
await hold(c, btn, num, st, lines, t)
for t in (0, 20):
st.pop("t", None)
c.number_command(num, t)
await asyncio.sleep(2)
note(f"SET {t}, number reads {number(st, f'set {t}')}")
c.button_command(btn["Restart"])
await asyncio.sleep(1)
await c.disconnect()
await asyncio.sleep(15)
c, btn, num, st, lines = await session()
note(f"AFTER RESTART number reads {number(st, f'restart {t}')}")
await c.disconnect()
if MISSING:
note(f"NO-DATA for: {', '.join(MISSING)}")
sys.exit(1)
asyncio.run(main())
@@ -0,0 +1,82 @@
"""Step stream-harness.yaml through frames, silence, garbage and radar restarts; print every state change.
usage: linkdrive.py HOST OUT env: API_KEY (when the harness has one)
Lines are seconds since start: PRESS steps, STATE changes of the ld2450 entities (unknown when missing), and LOG lines
about the link or ld2450 warnings.
"""
import asyncio
import math
import os
import pathlib
import re
import sys
import time
from aioesphomeapi import APIClient, ButtonInfo, LogLevel
HOST, OUT = sys.argv[1], sys.argv[2]
LOG = pathlib.Path(OUT).open("w", encoding="utf-8") # noqa: SIM115 open for the whole run
T0 = time.time()
STEPS = [
("Mode none", 8), ("Mode target", 6), ("Mode silent", 10), ("Mode none", 4), ("Mode target", 4),
("Mode garbage", 10), ("Mode target", 5),
("Radar Restart", 0.3), ("Mode silent", 3.5), ("Mode target", 6),
("Radar Restart", 0.3), ("Mode silent", 15), ("Mode none", 4),
] # fmt: skip
def note(s: str) -> None:
line = f"{time.time() - T0:7.2f} {s}"
print(line)
LOG.write(line + "\n")
LOG.flush()
async def main() -> None:
c = APIClient(HOST, 6053, None, noise_psk=os.environ.get("API_KEY"))
await c.connect(login=True)
ents, _ = await c.list_entities_services()
names = {e.key: e.name for e in ents}
btn = {e.name: e.key for e in ents if isinstance(e, ButtonInfo)}
last = {}
# state changes after the first step; the burst at connect does not count
stepped, changes = [False], [0]
def on_state(s) -> None:
n = names.get(s.key)
if n is None or n in btn:
return
v = (
"unknown"
if getattr(s, "missing_state", False)
else getattr(s, "state", None)
)
if isinstance(v, float):
v = "unknown (nan)" if math.isnan(v) else round(v, 1)
if last.get(n) != v:
last[n] = v
changes[0] += stepped[0]
note(f"STATE {n} = {v}")
def on_log(m) -> None:
t = re.sub(r"\x1b\[[0-9;]*m", "", m.message.decode(errors="replace"))
if re.search(r"[Ll]ink|\[W\]\[ld2450", t):
note("LOG " + t.strip())
c.subscribe_states(on_state)
c.subscribe_logs(on_log, log_level=LogLevel.LOG_LEVEL_DEBUG)
await asyncio.sleep(3)
stepped[0] = True
for name, wait in STEPS:
note(f"PRESS {name}")
c.button_command(btn[name])
await asyncio.sleep(wait)
await c.disconnect()
# dev freezes entities during silence but still updates them on target frames; nothing at all is a dead stream
if not changes[0]:
note("NO-DATA: no entity changed state after the first step")
sys.exit(1)
asyncio.run(main())
@@ -0,0 +1,82 @@
"""Read the LD24xx BT MAC text sensors, turn every LD24xx Bluetooth switch off, then on again.
usage: macdrive.py HOST OUT env: API_KEY (when the device has one)
Works on any device whose MAC, Bluetooth and firmware entities have those words in their names (the BT MAC sensors
may be disabled by default; they still publish over the API). Quote at most the first MAC byte in a PR.
"""
import asyncio
import os
import pathlib
import sys
import time
from aioesphomeapi import APIClient, SwitchInfo, TextSensorInfo
HOST, OUT = sys.argv[1], sys.argv[2]
LOG = pathlib.Path(OUT).open("w", encoding="utf-8") # noqa: SIM115 open for the whole run
def note(s: str) -> None:
line = f"{time.strftime('%H:%M:%S')} {s}"
print(line)
LOG.write(line + "\n")
LOG.flush()
async def main() -> None:
c = APIClient(HOST, 6053, None, noise_psk=os.environ.get("API_KEY"))
await c.connect(login=True)
ents, _ = await c.list_entities_services()
keys = {
e.key: e.name
for e in ents
if isinstance(e, (SwitchInfo, TextSensorInfo))
and any(w in e.name for w in ("MAC", "Bluetooth", "Firmware"))
}
states = {}
def on_state(s) -> None:
if s.key in keys and states.get(keys[s.key]) != getattr(s, "state", None):
states[keys[s.key]] = s.state
note(f"STATE {keys[s.key]} = {s.state}")
c.subscribe_states(on_state)
await asyncio.sleep(8)
switches = {
e.name: e.key
for e in ents
if isinstance(e, SwitchInfo) and "Bluetooth" in e.name
}
macs = [n for n in keys.values() if "MAC" in n]
if not macs or not switches:
note(
f"FAIL: need a MAC text sensor and a Bluetooth switch, found {sorted(keys.values())}"
)
sys.exit(1)
missing = []
if silent := [n for n in sorted(keys.values()) if n not in states]:
note(f"NO-DATA after 8 s: {', '.join(silent)}")
missing += silent
note(
"SNAP start: "
+ "; ".join(f"{n}={states.get(n)}" for n in sorted(keys.values()))
)
for phase, on in (("off", False), ("on", True)):
for name, key in switches.items():
note(f"SET {name} {phase}")
c.switch_command(key, on)
await asyncio.sleep(1)
await asyncio.sleep(20)
note(
f"SNAP bluetooth {phase}: "
+ "; ".join(f"{n}={states.get(n)}" for n in sorted(keys.values()))
)
missing += [n for n in switches if states.get(n) is not True]
await c.disconnect()
if missing:
note(f"NO-DATA for: {', '.join(sorted(set(missing)))}")
sys.exit(1)
asyncio.run(main())
@@ -0,0 +1,5 @@
binary_sensor:
- platform: ld2450
ld2450_id: radar
connected:
name: Connected
@@ -0,0 +1,128 @@
# D1 mini, ld2450 on UART0 looped back onto itself, fed one periodic frame every 100 ms from a mode global:
# 0 no target, 1 target 1 approaching, 2 silent, 3 garbage bytes (what a radar at another baud rate looks like).
# Add `connected: !include stream-connected.yaml` under packages on builds whose ld2450 has the link watchdog.
substitutions:
name: ld2450-stream
esphome:
name: ${name}
on_boot:
priority: -100
then:
- lambda: |-
// UART0 TX looped back into its own RX so injected frames reach the hub
USC0(0) |= (1 << UCLBE);
ESP_LOGI("harness", "UART0 loopback on");
esp8266:
board: d1_mini
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
api:
reboot_timeout: 0s
ota:
- platform: esphome
logger:
baud_rate: 0
level: DEBUG
uart:
id: radar_uart
tx_pin: GPIO1
rx_pin: GPIO3
baud_rate: 256000
ld2450:
id: radar
uart_id: radar_uart
globals:
- id: mode
type: int
initial_value: "0"
interval:
- interval: 100ms
then:
- if:
condition:
lambda: return id(mode) == 1;
then:
- uart.write:
id: radar_uart
data: [0xAA, 0xFF, 0x03, 0x00, 0x00, 0x00, 0xE8, 0x83, 0x14, 0x00, 0x64, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x55, 0xCC]
- if:
condition:
lambda: return id(mode) == 0;
then:
- uart.write:
id: radar_uart
data: [0xAA, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x55, 0xCC]
- if:
condition:
lambda: return id(mode) == 3;
then:
- uart.write:
id: radar_uart
data: [0x3F, 0x80, 0xF8, 0x00, 0x7E, 0x07, 0xC0, 0x1F, 0xE0, 0x03, 0xF0, 0x0F]
binary_sensor:
- platform: ld2450
has_target:
name: Has Target
# no settle filter, so the hub's own presence hold is what gets timed
filters: []
on_state:
- lambda: 'ESP_LOGI("harness", "presence raw %s at %u", x ? "ON" : "OFF", (unsigned) millis());'
sensor:
- platform: ld2450
target_count:
name: Target Count
target_1:
x:
name: T1 X
text_sensor:
- platform: ld2450
target_1:
direction:
name: T1 Direction
number:
- platform: ld2450
presence_timeout:
name: Presence Timeout
button:
- platform: template
name: Mode none
on_press:
- lambda: 'id(mode) = 0; ESP_LOGI("harness", "mode none at %u", (unsigned) millis());'
- platform: template
name: Mode target
on_press:
- lambda: 'id(mode) = 1; ESP_LOGI("harness", "mode target at %u", (unsigned) millis());'
- platform: template
name: Mode silent
on_press:
- lambda: 'id(mode) = 2; ESP_LOGI("harness", "mode silent at %u", (unsigned) millis());'
- platform: template
name: Mode garbage
on_press:
- lambda: 'id(mode) = 3; ESP_LOGI("harness", "mode garbage at %u", (unsigned) millis());'
- platform: ld2450
ld2450_id: radar
restart:
name: Radar Restart
- platform: restart
name: Restart
@@ -0,0 +1,124 @@
"""Press one crash button after another on an RTL8720C test build and keep the decoded API logs of each next boot.
Usage: rtl_drive.py HOST OUTDIR TREE YAML BUTTON... (button names from templates/rtl8720c-crash-buttons-dut.yaml)
Prints PRESS lines with the wall clock time, so resets can be timed against a serial capture taken with --ms.
Each case waits for the board to answer on the API port again, then saves 15 s of `esphome logs` (run from TREE,
so the CLI decodes the addresses) as OUTDIR/caseN-BUTTON.txt. The run prints CASE N BUTTON and exits 1 with NO RESET
when the API port never closes after the press (the button did not reset the board), NO BOOT when the board is not
back within BOOT_DEADLINE_S, and NO LOGS when the log capture never connected."""
import asyncio
import contextlib
import os
from pathlib import Path
import socket
import subprocess
import sys
import time
from aioesphomeapi import APIClient
host, out, tree, yaml = sys.argv[1:5]
buttons = sys.argv[5:]
BOOT_DEADLINE_S = 120
# Every case button resets the board: a fault, the watchdog (hang) or a restart. The watchdog takes about 11 s.
RESET_DEADLINE_S = 20
def port_open() -> bool:
try:
socket.create_connection((host, 6053), 1).close()
except OSError:
return False
return True
def wait_for_port() -> bool:
deadline = time.monotonic() + BOOT_DEADLINE_S
while not port_open():
if time.monotonic() > deadline:
return False
time.sleep(1)
return True
def wait_for_reset() -> bool:
deadline = time.monotonic() + RESET_DEADLINE_S
while port_open():
if time.monotonic() > deadline:
return False
time.sleep(0.2)
return True
def fail(i: int, name: str, why: str) -> None:
print(f"CASE {i} {name} {why}", flush=True)
sys.exit(1)
async def button_keys() -> dict[str, int]:
cli = APIClient(host, 6053, None)
await cli.connect(login=True)
try:
entities, _ = await cli.list_entities_services()
finally:
await cli.disconnect()
return {e.name: e.key for e in entities if type(e).__name__ == "ButtonInfo"}
async def press(name: str, key: int) -> None:
cli = APIClient(host, 6053, None)
await cli.connect(login=True)
now = time.time()
print(
f"PRESS {name} at {time.strftime('%H:%M:%S', time.localtime(now))}.{int(now * 1000) % 1000:03d}",
flush=True,
)
cli.button_command(key)
await asyncio.sleep(0.5)
# the board resets within about a second, so the disconnect reply may never come
with contextlib.suppress(Exception):
await asyncio.wait_for(cli.disconnect(), 2)
if not wait_for_port():
sys.exit("NO BOOT before the first case")
# Check every name up front, so a typo in the last case does not waste the crashes before it
keys = asyncio.run(button_keys())
if missing := [b for b in buttons if b not in keys]:
sys.exit(f"Unknown buttons {missing}; the board has {sorted(keys)}")
for i, name in enumerate(buttons):
if not wait_for_port():
fail(i, name, "NO BOOT")
time.sleep(5)
asyncio.run(press(name, keys[name]))
if not wait_for_reset():
fail(i, name, "NO RESET")
time.sleep(20) # boot and Wi-Fi
if not wait_for_port():
fail(i, name, "NO BOOT")
case_file = Path(out) / f"case{i}-{name.replace(' ', '_')}.txt"
with case_file.open("w", encoding="utf-8") as fh:
subprocess.run(
[
"timeout",
"15",
sys.executable,
"-m",
"esphome",
"logs",
yaml,
"--device",
host,
],
cwd=tree,
env={**os.environ, "PYTHONPATH": tree, "PYTHONUNBUFFERED": "1"},
stdout=fh,
stderr=subprocess.STDOUT,
check=False,
)
if "Successful handshake" not in case_file.read_text(
encoding="utf-8", errors="replace"
):
fail(i, name, "NO LOGS")
print(f"CASE {i} {name} done", flush=True)
@@ -0,0 +1,81 @@
"""Match each RTL8720C ROM fault dump in a serial capture with the report on the next boot.
usage: rtl_rom_vs_report.py SERIAL_CAPTURE (taken with serial_capture.py --ms)
Per ROM dump: the ROM's CFSR and PC, ms from the dump to the next `ROM Version` banner, and the Reason, CFSR, PC and SP
the next boot reported. The ROM lines start with a bare CR, so the capture is split on newlines only.
"""
import pathlib
import re
import sys
RAW = pathlib.Path(sys.argv[1]).read_bytes().decode(errors="replace")
LINES = [
re.sub(r"\x1b\[[0-9;]*m", "", line) for line in RAW.replace("\r", "").split("\n")
]
def stamp(line: str) -> float | None:
"""Seconds since midnight from a serial_capture.py --ms timestamp."""
m = re.search(r"\[(\d\d):(\d\d):(\d\d\.\d{3})\]", line)
return (
int(m.group(1)) * 3600 + int(m.group(2)) * 60 + float(m.group(3)) if m else None
)
if not any(stamp(line) is not None for line in LINES):
sys.exit(
"NO-DATA: no [HH:MM:SS.mmm] timestamps; take the capture with serial_capture.py --ms"
)
dumps = bad = 0
i = 0
while i < len(LINES):
if "Fault Handler:" not in LINES[i]:
i += 1
continue
t0 = stamp(LINES[i])
kind = LINES[i + 2].split("]", 1)[-1].strip() if i + 2 < len(LINES) else "?"
cfsr = pc = None
j = i
while j < len(LINES) and "ROM Version" not in LINES[j]:
if cfsr is None and "Configurable Fault Status Reg" in LINES[j]:
cfsr = LINES[j].split("=")[1].strip()
if pc is None and "PC =" in LINES[j]:
pc = LINES[j].split("=")[1].strip()
j += 1
tj = next(
(
stamp(LINES[x])
for x in range(j, min(j + 5, len(LINES)))
if stamp(LINES[x]) is not None
),
None,
)
reset = (
f"{(tj - t0) * 1000:.0f} ms"
if tj is not None and t0 is not None
else "no reset seen"
)
report = {}
k = j + 1
while (
k < len(LINES)
and "Fault Handler:" not in LINES[k]
and "boot reason" not in LINES[k]
):
m = re.search(r"(Reason|CFSR|PC|SP):\s+(.*)", LINES[k])
if m and "libretiny.crash" in LINES[k]:
report.setdefault(m.group(1), m.group(2).split(" (")[0].strip())
k += 1
dumps += 1
missing = [
n for n, v in (("ROM CFSR", cfsr), ("ROM PC", pc), ("reset", tj)) if v is None
]
missing += [k for k in ("Reason", "CFSR", "PC", "SP") if k not in report]
bad += bool(missing)
flag = f" | MISSING {', '.join(missing)}" if missing else ""
print(f"{kind:18} ROM CFSR {cfsr} PC {pc} | reset {reset} | report {report}{flag}")
i = j
if not dumps:
sys.exit("NO-DATA: no ROM fault dump in the capture")
sys.exit(1 if bad else 0)
@@ -0,0 +1,40 @@
# Any ESP32-C3 with GPIO10 free; drop ESPHome ledc outputs, the C3 shares one LEDC clock across timers.
esphome:
name: wake-probe-esp32c3
includes:
- wake_probe.hpp
on_boot:
priority: -100
then:
- lambda: wakeprobe::start();
esp32:
board: esp32-c3-devkitm-1
variant: esp32c3
framework:
type: esp-idf
advanced:
include_builtin_idf_components:
- esp_driver_ledc
logger:
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
api:
reboot_timeout: 0s
ota:
- platform: esphome
power_management:
- platform: esp32_power_management
enable_light_sleep: true
profiling: true
interval:
- interval: 30s
then:
- lambda: wakeprobe::report();
@@ -0,0 +1,110 @@
#pragma once
// LEDC on an RC_FAST clock keeps toggling GPIO10 in light sleep; an ESP32InternalGPIOPin interrupt on the same pad
// timestamps every edge.
#include <cstdio>
#include "driver/ledc.h"
#include "driver/gpio.h"
#include "esp_pm.h"
#include "esp_timer.h"
#include "esphome/components/esp32/gpio.h"
#include "esphome/core/log.h"
namespace wakeprobe {
static const char *const TAG = "wakeprobe";
static constexpr gpio_num_t PIN = GPIO_NUM_10;
static volatile uint32_t edges = 0;
static volatile int64_t last_us = 0;
static volatile int64_t gap_min = INT64_MAX, gap_max = 0;
static volatile uint32_t late_edges = 0; // gap more than 20 ms off the half period
static int64_t start_us = 0;
static uint32_t half_period_us = 0;
static uint32_t freq = 0;
static esp_err_t err_timer = ESP_OK, err_channel = ESP_OK;
static void IRAM_ATTR on_edge(void *) {
int64_t now = esp_timer_get_time();
if (last_us != 0) {
int64_t gap = now - last_us;
if (gap < gap_min)
gap_min = gap;
if (gap > gap_max)
gap_max = gap;
int64_t off = gap - (int64_t) half_period_us;
if (off > 20000 || off < -20000)
late_edges = late_edges + 1;
}
last_us = now;
edges = edges + 1;
}
inline void start() {
auto *pin = new esphome::esp32::ESP32InternalGPIOPin(); // NOLINT
pin->set_pin(PIN);
pin->set_flags(esphome::gpio::FLAG_INPUT);
pin->setup();
pin->attach_interrupt(on_edge, (void *) nullptr, esphome::gpio::INTERRUPT_ANY_EDGE);
ledc_timer_config_t t{};
t.speed_mode = LEDC_LOW_SPEED_MODE;
t.duty_resolution = LEDC_TIMER_14_BIT;
t.timer_num = LEDC_TIMER_0;
t.freq_hz = 2;
t.clk_cfg = LEDC_USE_RC_FAST_CLK;
esp_err_t e1 = err_timer = ledc_timer_config(&t);
ledc_channel_config_t c{};
c.gpio_num = PIN;
c.speed_mode = LEDC_LOW_SPEED_MODE;
c.channel = LEDC_CHANNEL_0;
c.timer_sel = LEDC_TIMER_0;
c.duty = 1 << 13;
c.sleep_mode = LEDC_SLEEP_MODE_KEEP_ALIVE;
esp_err_t e2 = err_channel = ledc_channel_config(&c);
// ledc_channel_config makes the pad output only; turn its input back on so the interrupt sees the wave.
gpio_input_enable(PIN);
freq = ledc_get_freq(LEDC_LOW_SPEED_MODE, LEDC_TIMER_0);
half_period_us = freq ? 500000 / freq : 0;
start_us = esp_timer_get_time();
ESP_LOGI(TAG, "LEDC timer=%s channel=%s freq=%u Hz half period %u us", esp_err_to_name(e1), esp_err_to_name(e2),
(unsigned) freq, (unsigned) half_period_us);
}
inline void report() {
if (start_us == 0)
return;
char lv[21];
for (int i = 0; i < 20; i++) {
lv[i] = gpio_get_level(PIN) ? '1' : '0';
vTaskDelay(pdMS_TO_TICKS(50));
}
lv[20] = 0;
// Elapsed time and edge count are read together, after the 1 s level loop, so they describe the same interval.
float secs = (esp_timer_get_time() - start_us) / 1e6f;
uint32_t seen = edges;
ESP_LOGI(TAG, "LEDC timer=%s channel=%s freq=%u, level over 1 s: %s", esp_err_to_name(err_timer),
esp_err_to_name(err_channel), (unsigned) freq, lv);
ESP_LOGI(TAG, "%.0f s: edges=%u expected=%.0f gap min=%lld max=%lld us, off by >20 ms: %u", secs, (unsigned) seen,
secs * 2 * freq, (long long) gap_min, (long long) gap_max, (unsigned) late_edges);
#ifdef CONFIG_PM_PROFILING
static char buf[1024];
FILE *f = fmemopen(buf, sizeof(buf) - 1, "w");
if (f == nullptr) {
ESP_LOGW(TAG, "pm dump failed: fmemopen");
return;
}
esp_pm_dump_locks(f);
long n = ftell(f);
fclose(f);
buf[n < 0 ? 0 : n] = 0;
bool sleep_seen = false;
for (char *line = strtok(buf, "\n"); line != nullptr; line = strtok(nullptr, "\n")) {
if (strstr(line, "SLEEP") || strstr(line, "CPU_MAX") || strstr(line, "APB_MAX") || strstr(line, "APB_MIN")) {
sleep_seen = sleep_seen || strstr(line, "SLEEP") != nullptr;
ESP_LOGI(TAG, "pm %s", line);
}
}
if (!sleep_seen)
ESP_LOGW(TAG, "pm dump has no SLEEP line (%ld bytes, buffer %u)", n, (unsigned) sizeof(buf));
#else
ESP_LOGW(TAG, "pm profiling unavailable: set power_management profiling: true");
#endif
}
} // namespace wakeprobe
@@ -0,0 +1,36 @@
# AP manual IP: the only network is missing, so the fallback AP starts after 10 s on 10.42.7.1.
substitutions:
name: mip-ap
plat: esp32
esphome:
name: ${name}
packages:
plat: !include plat-${plat}.yaml
logger:
level: VERBOSE
logs:
scheduler: DEBUG
component: DEBUG
wifi:
networks:
- ssid: mip-nowhere
password: nowhere123
manual_ip:
static_ip: 10.9.9.9
gateway: 10.9.9.1
subnet: 255.255.255.0
dns1: 10.9.9.1
ap:
ssid: mip-ap-test
password: mipaptest1
ap_timeout: 10s
manual_ip:
static_ip: 10.42.7.1
gateway: 10.42.7.1
subnet: 255.255.255.0
captive_portal:
@@ -0,0 +1,36 @@
# Joins the DUT's AP and fetches its page every 10 s.
substitutions:
name: mip-client
plat: esp32
esphome:
name: ${name}
packages:
plat: !include plat-${plat}.yaml
logger:
wifi:
ssid: mip-ap-test
password: mipaptest1
reboot_timeout: 0s
http_request:
verify_ssl: false
interval:
- interval: 10s
then:
- if:
condition: wifi.connected
then:
- http_request.get:
url: http://10.42.7.1/
capture_response: false
on_response:
then:
- lambda: ESP_LOGI("client", "GET http://10.42.7.1/ status=%d", response->status_code);
on_error:
then:
- logger.log: "GET http://10.42.7.1/ failed"
@@ -0,0 +1,32 @@
#pragma once
#include "esphome/core/log.h"
#include "lwip/dns.h"
#include "lwip/ip_addr.h"
#ifdef USE_ESP8266
#include <ESP8266WiFi.h>
#else
#include "lwip/netdb.h"
#include "lwip/inet.h"
#endif
inline void dns_probe() {
char b0[IPADDR_STRLEN_MAX], b1[IPADDR_STRLEN_MAX], res[16] = "-";
ipaddr_ntoa_r(dns_getserver(0), b0, sizeof(b0));
ipaddr_ntoa_r(dns_getserver(1), b1, sizeof(b1));
int ok;
#ifdef USE_ESP8266
IPAddress ip;
ok = WiFi.hostByName("pool.ntp.org", ip);
if (ok)
strncpy(res, ip.toString().c_str(), sizeof(res) - 1);
#else
struct addrinfo hints{};
hints.ai_family = AF_INET;
struct addrinfo *r = nullptr;
ok = lwip_getaddrinfo("pool.ntp.org", nullptr, &hints, &r) == 0 && r != nullptr;
if (ok) {
inet_ntoa_r(((struct sockaddr_in *) r->ai_addr)->sin_addr, res, sizeof(res));
lwip_freeaddrinfo(r);
}
#endif
ESP_LOGI("dnsprobe", "dns0=%s dns1=%s lookup=%s %s", b0, b1, ok ? "ok" : "FAIL", res);
}
@@ -0,0 +1,4 @@
esp32:
board: esp32dev
framework:
type: esp-idf
@@ -0,0 +1,2 @@
esp8266:
board: d1_mini
+30
View File
@@ -0,0 +1,30 @@
#!/bin/bash
# usage: run-ap.sh LABEL the DUT runs the fallback AP on 10.42.7.1, the other board joins it and fetches its page
# Copy this directory into a scratch directory and run it there; no secrets are needed.
# env: TREE (esphome checkout for the DUT), CLIENT_TREE (checkout for the client, default TREE), DUT_PORT, DUT_PLAT,
# CLIENT_PORT, CLIENT_PLAT (esp32 or esp8266), SC (path to serial_capture.py), PY (default $TREE/venv/bin/python)
D=$(cd "$(dirname "$0")" && pwd); L=${1:?label}; T=${TREE:?set TREE}; CT=${CLIENT_TREE:-$T}
PY=${PY:-$T/venv/bin/python}; SC=${SC:?set SC}; DP=${DUT_PORT:?set DUT_PORT}; CP=${CLIENT_PORT:?set CLIENT_PORT}
N=mip-ap-$L; CN=mip-client
up() { (cd "$1" && PYTHONUNBUFFERED=1 timeout 1500 $PY -m esphome -s name "$2" -s plat "$3" run --no-logs "$D/$4" \
--device "$5" > "$D/$2-upload.log" 2>&1) || { echo "FAIL: $2 build or upload"; exit 1; }; }
up "$T" "$N" "${DUT_PLAT:-esp32}" ap.yaml "$DP"
up "$CT" "$CN" "${CLIENT_PLAT:-esp8266}" client.yaml "$CP"
rm -f "$D/$N-serial.txt" "$D/$CN-$N-serial.txt"
$PY "$SC" "$DP" 120 "$D/$N-serial.txt" --reset > /dev/null 2>&1 & C1=$!
$PY "$SC" "$CP" 120 "$D/$CN-$N-serial.txt" --reset > /dev/null 2>&1 & C2=$!
wait $C1; R1=$?; wait $C2; R2=$?
strip() { LC_ALL=C sed 's/\x1b\[[0-9;]*m//g' | sort -u -k2; }
echo "--- DUT"; LC_ALL=C grep -a -E "Manual IP|Starting fallback|IP Address|Setting up AP|rst cause|Guru|abort|panic" \
"$D/$N-serial.txt" | strip | head -8
echo "--- client"; LC_ALL=C grep -a -E "IP Address:|Gateway:|Subnet:" "$D/$CN-$N-serial.txt" | strip | head -4
ok=$(grep -a -c 'status=200' "$D/$CN-$N-serial.txt"); bad=$(grep -a -c 'GET http://10.42.7.1/ failed' "$D/$CN-$N-serial.txt")
echo "client GET ok=$ok failed=$bad"
fail=0
[ "$R1" = 0 ] && [ -s "$D/$N-serial.txt" ] || { echo "FAIL: DUT capture failed or empty (rc $R1)"; fail=1; }
[ "$R2" = 0 ] && [ -s "$D/$CN-$N-serial.txt" ] || { echo "FAIL: client capture failed or empty (rc $R2)"; fail=1; }
grep -a -q -E "IP Address: +10\.42\.7\.1\b" "$D/$N-serial.txt" || { echo "FAIL: AP address is not 10.42.7.1"; fail=1; }
grep -a -q -E "IP Address: +10\.42\.7\." "$D/$CN-$N-serial.txt" || { echo "FAIL: client never joined"; fail=1; }
[ "$ok" -gt 0 ] || { echo "FAIL: no page fetched"; fail=1; }
grep -a -q -E "Guru|abort\(\)|panic|[eE]xception \(|Soft WDT reset|wdt reset" "$D/$N-serial.txt" && { echo "FAIL: DUT crash"; fail=1; }
[ $fail = 0 ] && echo PASS; exit $fail
+24
View File
@@ -0,0 +1,24 @@
#!/bin/bash
# usage: run-sta.sh LABEL flash sta.yaml, capture 75 s, ping the manual address, check the dump and the DNS probe
# Copy this directory into a scratch directory with a secrets.yaml (wifi_ssid, wifi_password) and run it there.
# env: TREE (esphome checkout), PORT (board serial port), PLAT (esp32 or esp8266), IP (the board's own DHCP lease),
# GATEWAY, SUBNET, DNS1 (the network's values), SC (path to serial_capture.py), PY (default $TREE/venv/bin/python)
D=$(cd "$(dirname "$0")" && pwd); L=${1:?label}; T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}
P=${PORT:?set PORT}; IP=${IP:?set IP}; SC=${SC:?set SC}; N=mip-sta-$L; C=$D/$N-serial.txt
(cd "$T" && PYTHONUNBUFFERED=1 timeout 1500 $PY -m esphome -s name "$N" -s plat "${PLAT:-esp32}" -s ip "$IP" \
-s gateway "${GATEWAY:?set GATEWAY}" -s subnet "${SUBNET:?set SUBNET}" -s dns1 "${DNS1:?set DNS1}" \
run --no-logs "$D/sta.yaml" --device "$P" > "$D/$N-upload.log" 2>&1) || { echo "FAIL: build or upload"; exit 1; }
rm -f "$C"
$PY "$SC" "$P" 75 "$C" --reset > /dev/null 2>&1 & CAP=$!
# ping exits 0 when at least one reply came back, on macOS and Linux alike.
sleep 50; PING=$(ping -c 10 -i 0.3 "$IP" 2>&1); PING_RC=$?; wait $CAP; CAPRC=$?
LC_ALL=C grep -a -E "Manual IP|IP Address:|Gateway:|Subnet:|DNS1:|DNS2:|dnsprobe|rst cause|Guru|abort|panic" "$C" \
| LC_ALL=C sed 's/\x1b\[[0-9;]*m//g' | sort -u -k2 | head -14
echo "ping: $(echo "$PING" | grep -E 'transmitted')"
fail=0
[ "$CAPRC" = 0 ] && [ -s "$C" ] || { echo "FAIL: serial capture failed or empty (rc $CAPRC)"; fail=1; }
grep -a -q -E "dns0=$DNS1 dns1=9\.9\.9\.9 lookup=ok" "$C" || { echo "FAIL: DNS servers or lookup"; fail=1; }
grep -a -q -E "IP Address: +$IP\b" "$C" || { echo "FAIL: address is not $IP"; fail=1; }
[ $PING_RC = 0 ] || { echo "FAIL: no ping reply"; fail=1; }
grep -a -q -E "Guru|abort\(\)|panic|[eE]xception \(|Soft WDT reset|wdt reset" "$C" && { echo "FAIL: crash"; fail=1; }
[ $fail = 0 ] && echo PASS; exit $fail
@@ -0,0 +1,62 @@
# Station manual IP. The real network is the second table row and inherits the top level manual_ip; set ip to the
# board's own DHCP lease and dns2 to a server DHCP does not hand out, so the logs prove the manual values are used.
# run-sta.sh passes name, plat, ip, gateway, subnet and dns1 with -s; dns2 stays 9.9.9.9, which it checks for.
substitutions:
name: mip-sta
plat: esp32
ip: 192.168.1.50
gateway: 192.168.1.1
subnet: 255.255.255.0
dns1: 192.168.1.1
dns2: 9.9.9.9
esphome:
name: ${name}
includes:
- dnsprobe.hpp
packages:
plat: !include plat-${plat}.yaml
logger:
level: VERBOSE
logs:
scheduler: DEBUG
component: DEBUG
api.service: DEBUG
api.connection: DEBUG
api.socket: DEBUG
socket: DEBUG
mdns: DEBUG
wifi:
manual_ip:
static_ip: ${ip}
gateway: ${gateway}
subnet: ${subnet}
dns1: ${dns1}
dns2: ${dns2}
networks:
- ssid: mip-nowhere
password: nowhere123
manual_ip:
static_ip: 10.9.9.9
gateway: 10.9.9.1
subnet: 255.255.255.0
dns1: 10.9.9.1
- ssid: !secret wifi_ssid
password: !secret wifi_password
api:
reboot_timeout: 0s
ota:
- platform: esphome
interval:
- interval: 20s
then:
- if:
condition: wifi.connected
then:
- lambda: dns_probe();
@@ -0,0 +1,43 @@
"""Check over the API that each board runs the expected build.
Usage: apiinfo.py HOST[=BUILD_INFO_JSON]...
Prints name and compilation time per host. With a build_info.json (from the build directory), the board's
compilation time must equal that build's build_time_str. Exits 1 when a host fails or runs another build.
env: API_KEY (the boards' api encryption key, when they have one)"""
import asyncio
import json
import os
from pathlib import Path
import sys
from aioesphomeapi import APIClient, APIConnectionError
async def info(host: str) -> tuple[str, str]:
cli = APIClient(host, 6053, None, noise_psk=os.environ.get("API_KEY"))
await cli.connect(login=True)
try:
i = await cli.device_info()
finally:
await cli.disconnect()
return i.name, i.compilation_time
bad = 0
for arg in sys.argv[1:]:
host, _, build_info = arg.partition("=")
try:
name, built = asyncio.run(asyncio.wait_for(info(host), 30))
except (APIConnectionError, TimeoutError, OSError) as err:
print("API", host, "ERROR", repr(err), flush=True)
bad += 1
continue
want = (
json.loads(Path(build_info).read_text(encoding="utf-8"))["build_time_str"]
if build_info
else None
)
ok = want is None or built == want
bad += not ok
print("API", host, name, built, "" if ok else f"MISMATCH want {want}", flush=True)
sys.exit(1 if bad else 0)
@@ -0,0 +1,42 @@
# Inflate benchmark: run gen_streams.py first, then bench.sh. Results go out over syslog to syslog_ip:5514.
substitutions:
name: inflbench-bk
board: cb3s
esphome:
name: ${name}
includes:
- bench_streams.hpp
- bench.hpp
bk72xx:
board: ${board}
logger:
hardware_uart: UART1
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
api:
reboot_timeout: 0s
ota:
- platform: esphome
udp:
addresses:
- !secret syslog_ip
time:
- platform: sntp
syslog:
port: 5514
interval:
- interval: 90s
then:
- delay: 20s
- lambda: run_inflate_bench();
@@ -0,0 +1,44 @@
# Inflate benchmark: run gen_streams.py first, then bench.sh. Results go out over syslog to syslog_ip:5514.
substitutions:
name: inflbench-s3
esphome:
name: ${name}
includes:
- bench_streams.hpp
- bench.hpp
esp32:
board: esp32-s3-devkitc-1
variant: esp32s3
framework:
type: esp-idf
logger:
hardware_uart: USB_SERIAL_JTAG
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
api:
reboot_timeout: 0s
ota:
- platform: esphome
udp:
addresses:
- !secret syslog_ip
time:
- platform: sntp
syslog:
port: 5514
interval:
- interval: 90s
then:
- delay: 20s
- lambda: run_inflate_bench();
@@ -0,0 +1,54 @@
#pragma once
// On-device inflate speed for the ESPHome OTA decoder. Targets the decoder interface with dest_limit (dev as of
// this writing); once the interface without dest_limit lands (#21641), drop the dest_limit line.
#include "esphome/components/esphome/ota/ota_esphome_inflate.h"
#include "esphome/core/application.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
#include "bench_streams.hpp"
static uint8_t bench_ring[32768];
static OtaInflateState bench_state;
// LibreTiny defines micros as a macro; the parentheses call the ESPHome function.
inline uint32_t bench_now() { return (esphome::micros) (); }
inline void run_inflate_bench() {
unsigned expected = 0;
for (const auto &c : BENCH_CASES) {
for (unsigned ring : {4096u, 8192u, 16384u, 32768u})
expected += ring >= c.enc_window;
}
ESP_LOGI("bench", "BENCHSTART cases=%u", expected);
for (const auto &c : BENCH_CASES) {
for (unsigned ring : {4096u, 8192u, 16384u, 32768u}) {
if (ring < c.enc_window)
continue;
uint32_t best = UINT32_MAX;
size_t out = 0;
int res = 0;
for (int rep = 0; rep < 3; rep++) {
ota_inflate_init(&bench_state, bench_ring, ring);
bench_state.source = c.data;
bench_state.source_limit = c.data + c.len;
bench_state.source_read_cb = [](OtaInflateState *) -> int { return -1; };
out = 0;
uint32_t t0 = bench_now();
do {
bench_state.dest = bench_ring;
bench_state.dest_limit = bench_ring + ring;
res = ota_inflate(&bench_state);
out += bench_state.dest - bench_ring;
esphome::App.feed_wdt();
} while (res == OTA_INFLATE_OK);
uint32_t dt = bench_now() - t0;
if (dt < best)
best = dt;
}
ESP_LOGI("bench", "%s enc=%u ring=%u in=%u out=%u/%u res=%d best_us=%u out_kBps=%u in_kBps=%u", c.name,
c.enc_window, ring, (unsigned) c.len, (unsigned) out, (unsigned) c.raw, res, (unsigned) best,
(unsigned) ((uint64_t) out * 1000 / best), (unsigned) ((uint64_t) c.len * 1000 / best));
}
}
ESP_LOGI("bench", "BENCHDONE");
}
@@ -0,0 +1,42 @@
#!/bin/bash
# usage: bench.sh CONFIG DEVICE build and upload CONFIG (bench-bk72xx or bench-esp32s3) to DEVICE (OTA address or
# serial port), then collect one benchmark pass over syslog. Run gen_streams.py in this directory first.
# Copy this directory into a scratch directory with a secrets.yaml (wifi_ssid, wifi_password, syslog_ip = this
# host's address) and run it there. env: TREE (esphome checkout under test), PY (checkout python), WAIT (seconds to
# wait for a pass, default 300)
D=$(cd "$(dirname "$0")" && pwd); C=${1:?config name}; DEV=${2:?device}; T=${TREE:?set TREE}
PY=${PY:-$T/venv/bin/python}; WAIT=${WAIT:-300}; OUT=$D/$C-syslog.txt
[ -f "$D/bench_streams.hpp" ] || { echo "FAIL: run gen_streams.py first"; exit 1; }
(cd "$T" && PYTHONUNBUFFERED=1 timeout 1500 $PY -m esphome run --no-logs "$D/$C.yaml" --device "$DEV" > "$D/$C-upload.log" 2>&1) \
|| { echo "FAIL: build or upload failed, see $C-upload.log"; exit 1; }
$PY - "$OUT" "$WAIT" << 'PYEOF'
import socket
import sys
import time
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("0.0.0.0", 5514))
s.settimeout(1)
end = time.time() + int(sys.argv[2])
started = False
with open(sys.argv[1], "w", encoding="utf-8") as out:
while time.time() < end:
try:
d, _ = s.recvfrom(2048)
except TimeoutError:
continue
line = d.decode(errors="replace").strip()
# keep one whole pass: lines from a pass already under way are dropped
started = started or "BENCHSTART" in line
if started and "bench" in line:
print(line, file=out, flush=True)
if "BENCHDONE" in line:
break
PYEOF
grep -q BENCHDONE "$OUT" || { echo "FAIL: no complete pass within $WAIT s"; exit 1; }
grep -o 'bench:[0-9]*\]: .*' "$OUT"
BAD=$(grep 'best_us=' "$OUT" | grep -v 'res=1 ' | wc -l | tr -d ' ')
SHORT=$(grep -o 'out=[0-9]*/[0-9]*' "$OUT" | awk -F'[=/]' '$2 != $3' | wc -l | tr -d ' ')
WANT=$(grep -o 'BENCHSTART cases=[0-9]*' "$OUT" | cut -d= -f2); GOT=$(grep -c 'best_us=' "$OUT")
[ "$BAD" = 0 ] && [ "$SHORT" = 0 ] && [ "$GOT" = "$WANT" ] && echo "PASS" \
|| { echo "FAIL: $BAD cases did not finish, $SHORT short outputs, $GOT of $WANT results (lost syslog lines)"; exit 1; }
@@ -0,0 +1,43 @@
"""Write bench_streams.hpp: one 128 KB slice per image, raw deflate at level 9 with 4 KB and 32 KB windows.
Usage: gen_streams.py NAME=IMAGE[@OFFSET]... [--windows 12,15]
Each image gives one case per window. Keep the total near 130 KB on a BK7231N: an image with about 330 KB of extra
incompressible data failed its OTA ("Writing OTA data to flash memory failed"); use one image and --windows 12 there."""
import argparse
from pathlib import Path
import zlib
SLICE = 128 * 1024
ap = argparse.ArgumentParser()
ap.add_argument("images", nargs="+")
ap.add_argument("--windows", default="12,15")
args = ap.parse_args()
arrays, cases, total = [], [], 0
for spec in args.images:
name, _, rest = spec.partition("=")
path, _, offset = rest.partition("@")
raw = Path(path).read_bytes()[int(offset or 0) :][:SLICE]
for wbits in (int(w) for w in args.windows.split(",")):
data = zlib.compress(raw, 9, -wbits)
total += len(data)
var = f"{name}_w{wbits}"
arrays.append(
f"static const uint8_t {var}[{len(data)}] = {{{','.join(map(str, data))}}};"
)
cases.append(f'{{"{name}", {var}, sizeof({var}), {len(raw)}u, {1 << wbits}u}}')
print(f"{var}: {len(raw)} -> {len(data)} bytes")
head = "#pragma once\n#include <cstddef>\n#include <cstdint>\n"
case_struct = (
"struct BenchCase {\n const char *name;\n const uint8_t *data;\n size_t len;\n size_t raw;\n"
" unsigned enc_window;\n};\n"
)
body = (
"\n".join(arrays)
+ "\n"
+ case_struct
+ "static const BenchCase BENCH_CASES[] = {"
+ ", ".join(cases)
+ "};\n"
)
Path("bench_streams.hpp").write_text(head + body, encoding="utf-8")
print(f"total {total} bytes of streams")
@@ -0,0 +1,88 @@
"""Time one ESPHome OTA upload and print one RESULT json line.
Usage: otatime.py HOST IMAGE MODE (MODE: deflate, raw, deflate-tcp or raw-tcp)
env: OTA_PORT (default 3232), OTA_PASSWORD, API_KEY (a board with an api encryption key also encrypts OTA),
TAG (label stored in the result)
Run it with the checkout under test first on PYTHONPATH, so its espota2 is the client being measured.
raw: the client leaves deflate out of its feature offer. Never patch the deflate branch off after the offer: once
the device accepted deflate it expects a deflate stream. -tcp: the link is reported clean, so the client asks to
stay on TCP. Clearing the UDP feature bit instead desyncs the handshake ("receiving UDP token response: timed out")."""
import json
import logging
import os
from pathlib import Path
import sys
import time
import esphome.espota2 as espota
host, image, mode = sys.argv[1], Path(sys.argv[2]), sys.argv[3]
# Assigning a missing attribute would silently do nothing, so a renamed name must stop the run
for name in ("CLIENT_FEATURE_SUPPORTS_DEFLATE", "_loss_reason"):
if not hasattr(espota, name):
sys.exit(f"espota2 in this tree has no {name}; update otatime.py")
if mode.startswith("raw"):
espota.CLIENT_FEATURE_SUPPORTS_DEFLATE = 0
if mode.endswith("-tcp"):
espota._loss_reason = lambda *a: None # noqa: SLF001
marks: list[tuple[float, float]] = []
class Recorder:
"""Stands in for the progress bar and records when each fraction went out."""
def __init__(self, *args) -> None:
pass
def update(self, progress: float) -> None:
marks.append((time.perf_counter(), progress))
def done(self) -> None:
pass
espota.ProgressBar = Recorder
lines: list[str] = []
class Keep(logging.Handler):
def emit(self, record: logging.LogRecord) -> None:
lines.append(record.getMessage())
logging.basicConfig(level=logging.INFO)
logging.getLogger().addHandler(Keep())
t0 = time.perf_counter()
rc, _ = espota.run_ota(
host,
int(os.environ.get("OTA_PORT", "3232")),
os.environ.get("OTA_PASSWORD"),
image,
noise_psk=os.environ.get("API_KEY"),
)
total = time.perf_counter() - t0
deciles = []
if marks:
start = marks[0][0]
for q in range(1, 11):
hit = next((t for t, f in marks if f >= q / 10 - 1e-9), None)
deciles.append(round(hit - start, 2) if hit is not None else None)
result = {
"board": os.environ.get("TAG", ""),
"mode": mode,
"rc": rc,
"total": round(total, 2),
"took": next((x for x in lines if x.startswith("Update took")), ""),
"size": next((x for x in lines if "Compressed to" in x), ""),
"udp": any("Using UDP" in x for x in lines),
"deciles": deciles,
}
# The log must agree with the mode, or the row would be counted under the wrong mode
if mode.startswith("raw") and result["size"]:
result["rc"] = rc = rc or 1
print("raw mode upload was compressed anyway", file=sys.stderr)
if mode.endswith("-tcp") and result["udp"]:
result["rc"] = rc = rc or 1
print("-tcp mode upload switched to UDP", file=sys.stderr)
print("RESULT", json.dumps(result), flush=True)
sys.exit(1 if rc else 0)
+65
View File
@@ -0,0 +1,65 @@
#!/bin/bash
# usage: run.sh N PHASE... OTA upload timing A/B: per phase build every board, one warm-up upload per board
# (installs the phase's build, not timed), an API check that each board booted that build, then N rounds of every
# MODE on every board, interleaved so the boards share the same air. summ.py prints medians at the end.
# Layout: $D/PHASE/NAME.yaml per phase and board (with its secrets.yaml); outputs go to $D/res.txt.
# env: BOARDS ("NAME,HOST,OTA_PORT ..."; add an ESP32 on the same Wi-Fi as a network control), TREE_<PHASE>
# (esphome checkout for each phase, e.g. TREE_base, TREE_pr), PY (python with esphome's requirements),
# MODES (default "deflate-tcp raw-tcp"), SETTLE (seconds after a board answers again, default 15), API_KEY (when the
# boards have an api encryption key; it also encrypts their OTA, so all boards in one run need the same key)
D=$(cd "$(dirname "$0")" && pwd); N=${1:?rounds}; shift; [ $# -gt 0 ] || { echo "usage: run.sh N PHASE..."; exit 2; }
B=${BOARDS:?set BOARDS}; PY=${PY:?set PY}; MODES=${MODES:-deflate-tcp raw-tcp}; SETTLE=${SETTLE:-15}
wait_up() { # wait_up HOST PORT: up to 5 minutes for the OTA port to answer
local i
for i in $(seq 60); do
"$PY" -c "import socket,sys; socket.create_connection((sys.argv[1], int(sys.argv[2])), 2).close()" "$1" "$2" 2>/dev/null \
&& { sleep "$SETTLE"; return 0; }
sleep 5
done
return 1
}
up() { # up PHASE NAME HOST PORT MODE TAG OUTFILE; returns 1 unless the upload succeeded
local tree=TREE_$1 out=""
if wait_up "$3" "$4"; then
out=$(TAG=$1-$2-$6 OTA_PORT=$4 PYTHONPATH=${!tree} timeout 900 "$PY" "$D/otatime.py" "$3" \
"$(cat "$D/img-$1-$2.txt")" "$5" 2>> "$D/stderr-$1.log" | grep RESULT)
else
echo "FAIL: $3 not answering on $4"
fi
# no RESULT line (board gone, otatime.py crashed or timed out): record a failed upload so summ.py counts it
[ -n "$out" ] || out="RESULT {\"board\": \"$1-$2-$6\", \"mode\": \"$5\", \"rc\": -1, \"total\": 0, \"took\": \"\", \"size\": \"\", \"udp\": false, \"deciles\": []}"
echo "$out" | tee -a "$7"
[[ $out == *'"rc": 0,'* ]]
}
# results from an earlier run would fill in for missing rows: move them aside
for f in res.txt warm.txt api.txt; do [ -f "$D/$f" ] && mv "$D/$f" "$D/$f.$(date +%Y%m%d-%H%M%S)"; done
for ph in "$@"; do
tree=TREE_$ph; [ -n "${!tree}" ] || { echo "FAIL: set $tree"; exit 1; }
checks=()
for b in $B; do
IFS=, read -r n h p <<< "$b"
(cd "${!tree}" && PYTHONUNBUFFERED=1 timeout 1500 "$PY" -m esphome compile "$D/$ph/$n.yaml") > "$D/build-$ph-$n.log" 2>&1 \
|| { echo "FAIL: build $ph/$n"; exit 1; }
# the image the CLI uploads (CORE.firmware_bin): ESP-IDF build, LibreTiny UF2, else the PlatformIO bin
bd=$D/$ph/.esphome/build/$n; : > "$D/img-$ph-$n.txt"
for f in "$bd/build/$n.bin" "$bd/.pioenvs/$n/firmware.uf2" "$bd/.pioenvs/$n/firmware.bin"; do
[ -f "$f" ] && { echo "$f" > "$D/img-$ph-$n.txt"; break; }
done
[ -s "$D/img-$ph-$n.txt" ] || { echo "FAIL: no firmware image under $bd"; exit 1; }
case $(cat "$D/img-$ph-$n.txt") in
*.uf2) PYTHONPATH=${!tree} "$PY" "$D/trim_uf2.py" "$(cat "$D/img-$ph-$n.txt")" > "$D/img-$ph-$n.tmp" \
&& mv "$D/img-$ph-$n.tmp" "$D/img-$ph-$n.txt" || { echo "FAIL: trim_uf2.py $ph/$n"; exit 1; } ;;
esac
checks+=("$h=$D/$ph/.esphome/build/$n/build_info.json")
done
for b in $B; do IFS=, read -r n h p <<< "$b"; up "$ph" "$n" "$h" "$p" deflate-tcp warm "$D/warm.txt" || exit 1; done
for b in $B; do IFS=, read -r n h p <<< "$b"; wait_up "$h" "$p"; done
"$PY" "$D/apiinfo.py" "${checks[@]}" | tee -a "$D/api.txt"; [ "${PIPESTATUS[0]}" = 0 ] || { echo "FAIL: $ph did not boot everywhere"; exit 1; }
for i in $(seq "$N"); do
for m in $MODES; do
for b in $B; do IFS=, read -r n h p <<< "$b"; up "$ph" "$n" "$h" "$p" "$m" "r$i" "$D/res.txt"; done
done
done
echo "PHASE DONE $ph"
done
"$PY" "$D/summ.py" "$D/res.txt" "$N"
@@ -0,0 +1,43 @@
"""Median upload time per board and mode from otatime.py RESULT lines.
Usage: summ.py RESULTS_FILE [ROUNDS]
Exits 1 when any upload failed, an upload time could not be read, or (with ROUNDS) a board and mode has fewer rows."""
import json
from pathlib import Path
import re
import statistics
import sys
rows = [
json.loads(line.split("RESULT ", 1)[1])
for line in Path(sys.argv[1]).read_text(encoding="utf-8").splitlines()
if "RESULT " in line
]
by: dict[tuple[str, str], list[dict]] = {}
for r in rows:
m = re.search(r"upload ([\d.]+)", r["took"])
r["up"] = float(m[1]) if m else None
# TAG is PHASE-BOARD-ROUND; group per phase and board
by.setdefault((r["board"].rsplit("-", 1)[0], r["mode"]), []).append(r)
rounds = int(sys.argv[2]) if len(sys.argv) > 2 else 0
failed = unparsed = short = 0
for (board, mode), v in sorted(by.items()):
ok = sorted(r["up"] for r in v if r["rc"] == 0 and r["up"] is not None)
fails = sum(r["rc"] != 0 for r in v)
failed += fails
unparsed += sum(r["rc"] == 0 and r["up"] is None for r in v)
short += len(v) < rounds
udp = sum(r["udp"] for r in v if r["rc"] == 0)
med = statistics.median(ok) if ok else None
print(
f"{board:24} {mode:12} n={len(v)} fail={fails} udp={udp} median={med} upload s: {ok}"
)
if not rows:
print("FAIL: no results")
elif failed or unparsed or short:
print(
f"FAIL: {failed} failed uploads, {unparsed} without an upload time, {short} groups under {rounds} rows"
)
else:
print("PASS")
sys.exit(0 if rows and not (failed or unparsed or short) else 1)
@@ -0,0 +1,24 @@
"""Write the trimmed LibreTiny UF2 the CLI would send (esphome#21642) next to firmware.uf2 and print its path.
Usage: trim_uf2.py FIRMWARE_UF2 (run with the phase's checkout on PYTHONPATH)
Prints the input path unchanged when the tree has no device_ota_uf2() or there is nothing to drop."""
from pathlib import Path
import sys
src = Path(sys.argv[1])
try:
from esphome.components.libretiny.uf2 import device_ota_uf2
except ModuleNotFoundError as err:
if err.name != "esphome.components.libretiny.uf2":
raise
print("no device_ota_uf2() in this tree, sending the full UF2", file=sys.stderr)
print(src)
sys.exit(0)
data = src.read_bytes()
if (trimmed := device_ota_uf2(data)) is None:
print(src)
sys.exit(0)
out = src.with_name("firmware.ota.uf2")
out.write_bytes(trimmed)
print(f"trimmed {len(data)} -> {len(trimmed)} bytes", file=sys.stderr)
print(out)
@@ -0,0 +1,90 @@
"""Print the date, time and datetime rows of /metrics, set new values over the API, print them again.
usage: datetime_metrics.py HOST env: API_KEY
Sets every date to 2040-03-04, every time to 23:59:59 and every datetime to 2040-03-04 05:06:07 UTC (past 2038 on
purpose). Values are printed with their UTC reading: dates are local midnight, times are ms since midnight and
datetimes are ms since the epoch. Exits 1 when a time or datetime row does not hold the value that was set.
"""
import asyncio
from datetime import UTC, datetime
import os
import re
import sys
import urllib.request
from aioesphomeapi import APIClient, DateInfo, DateTimeInfo, TimeInfo
HOST = sys.argv[1]
def metrics(tag: str) -> dict[tuple[str, str], int]:
with urllib.request.urlopen(f"http://{HOST}/metrics", timeout=10) as resp: # noqa: S310
body = resp.read().decode()
rows = [
line
for line in body.splitlines()
if re.match(r"esphome_(date|time|datetime)_", line)
]
print(f"--- {tag}: {len(rows)} rows")
parsed: dict[tuple[str, str], int] = {}
for line in rows:
m = re.match(r'(esphome_\w+)\{.*name="([^"]+)"\} (-?\d+)$', line)
if not m:
print(f" UNPARSED {line}")
continue
metric, name, value = m.group(1), m.group(2), int(m.group(3))
parsed[(metric, name)] = value
utc = ""
if metric in ("esphome_date_value", "esphome_datetime_value"):
utc = " = " + datetime.fromtimestamp(value / 1000, UTC).isoformat()
print(f" {metric} {name} {value}{utc}")
return parsed
async def main() -> None:
if not metrics("initial"):
sys.exit(
"NO-DATA: no date, time or datetime rows (a build without them, or no such entities)"
)
c = APIClient(HOST, 6053, None, noise_psk=os.environ.get("API_KEY"))
await c.connect(login=True)
ents, _ = await c.list_entities_services()
sent = 0
sent_per_metric = {"esphome_time_value": 0, "esphome_datetime_value": 0}
for e in ents:
sent += isinstance(e, (DateInfo, TimeInfo, DateTimeInfo))
if isinstance(e, DateInfo):
c.date_command(e.key, 2040, 3, 4)
elif isinstance(e, TimeInfo):
sent_per_metric["esphome_time_value"] += 1
c.time_command(e.key, 23, 59, 59)
elif isinstance(e, DateTimeInfo):
sent_per_metric["esphome_datetime_value"] += 1
c.datetime_command(
e.key, int(datetime(2040, 3, 4, 5, 6, 7, tzinfo=UTC).timestamp())
)
await asyncio.sleep(2)
await c.disconnect()
if not sent:
sys.exit("NO-DATA: the device lists no date, time or datetime entities")
after = metrics("after setting 2040-03-04, 23:59:59 and 2040-03-04 05:06:07 UTC")
if not after:
sys.exit("NO-DATA: no rows after setting the values")
# dates are local midnight, so their value depends on the device's time zone and is only printed
want = {"esphome_time_value": 86399000, "esphome_datetime_value": 2214450367000}
wrong = [
f"{metric} {name} {value} (want {want[metric]})"
for (metric, name), value in after.items()
if metric in want and value != want[metric]
]
# a time or datetime row that is missing or UNPARSED after the set is a failure too
for metric, n in sent_per_metric.items():
if (got := sum(m == metric for m, _ in after)) < n:
wrong.append(f"{metric}: {got} parsed rows for {n} entities set")
for line in wrong:
print(f" WRONG {line}")
sys.exit(1 if wrong else 0)
asyncio.run(main())
@@ -0,0 +1,10 @@
# Adds a device time zone (UTC-10, no DST) to prom-datetime.yaml; the zone applies without a time sync.
substitutions:
name: prom-datetime-tz
packages:
base: !include prom-datetime.yaml
time:
- platform: sntp
timezone: HST10
@@ -0,0 +1,46 @@
# D1 mini with three optimistic template datetime entities. -s name NAME; build prom-datetime-tz.yaml for a time zone.
substitutions:
name: prom-datetime
esphome:
name: ${name}
esp8266:
board: d1_mini
logger:
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
api:
reboot_timeout: 0s
ota:
- platform: esphome
web_server:
port: 80
datetime:
- platform: template
name: Date
id: test_date
type: date
optimistic: true
initial_value: "2000-1-2"
- platform: template
name: Time
id: test_time
type: time
optimistic: true
initial_value: "12:34:56am"
- platform: template
name: DateTime
id: test_datetime
type: datetime
optimistic: true
initial_value: "2000-1-2 12:34:56"
prometheus:
@@ -0,0 +1,6 @@
captive_portal:
button:
- platform: template
name: Start portal
on_press:
- lambda: captive_portal::global_captive_portal->start();
@@ -0,0 +1,4 @@
esp32:
board: esp32dev
framework:
type: esp-idf
@@ -0,0 +1,2 @@
esp8266:
board: d1_mini
@@ -0,0 +1,18 @@
#pragma once
// A handler registered after setup(), the way an external component would; answers GET /probe.
#include "esphome/components/web_server_base/web_server_base.h"
class ProbeHandler : public AsyncWebHandler {
public:
bool canHandle(AsyncWebServerRequest *request) const override {
if (request->method() != HTTP_GET)
return false;
#ifdef USE_ESP32
char url_buf[AsyncWebServerRequest::URL_BUF_SIZE];
return request->url_to(url_buf) == "/probe";
#else
return request->url() == ESPHOME_F("/probe");
#endif
}
void handleRequest(AsyncWebServerRequest *request) override { request->send(200, "text/plain", "probe-ok"); }
};
inline ProbeHandler probe_handler;
@@ -0,0 +1,2 @@
captive_portal:
prometheus:
+65
View File
@@ -0,0 +1,65 @@
#!/bin/bash
# usage: run.sh LABEL VARIANT flash webbase.yaml, fetch /probe and /, then a web OTA of the same image
# Copy this directory into a scratch directory with a secrets.yaml (wifi_ssid, wifi_password) and run it there.
# VARIANT is ws, cp or prom (see webbase.yaml). The cp variant presses "Start portal" over the API first.
# env: TREE (esphome checkout), PORT (board serial port), PLAT (esp32 or esp8266), IP (the board's address),
# SC (path to serial_capture.py), PY (default $TREE/venv/bin/python), SKILL_SCRIPTS (the skill's scripts directory)
D=$(cd "$(dirname "$0")" && pwd); L=${1:?label}; V=${2:?variant}; T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}
P=${PORT:?set PORT}; IP=${IP:?set IP}; SC=${SC:?set SC}; PL=${PLAT:-esp32}; N=web-$V-$PL-$L; C=$D/$N-serial.txt
# api_button.py and ota_timing/apiinfo.py live in the skill's scripts directory; set SKILL_SCRIPTS when this
# directory was copied elsewhere.
S=${SKILL_SCRIPTS:-$(cd "$D/.." && pwd)}
[ -f "$S/api_button.py" ] && [ -f "$S/ota_timing/apiinfo.py" ] || { echo "FAIL: set SKILL_SCRIPTS to the skill's scripts directory"; exit 1; }
if [ "$PL" = esp32 ]; then BIN=$D/.esphome/build/$N/build/$N.bin; else BIN=$D/.esphome/build/$N/.pioenvs/$N/firmware.bin; fi
(cd "$T" && PYTHONUNBUFFERED=1 timeout 1500 $PY -m esphome -s name "$N" -s plat "$PL" -s variant "$V" \
run --no-logs "$D/webbase.yaml" --device "$P" > "$D/$N-upload.log" 2>&1) || { echo "FAIL: build or upload"; exit 1; }
rm -f "$C"
# Longer than the worst case below: 80 s to come up, 120 s of OTA, 80 s to come back.
$PY "$SC" "$P" 300 "$C" --reset > /dev/null 2>&1 & CAP=$!
# Wait on the API port: in the cp variant the HTTP server only starts when the portal does, also after the OTA reboot.
up() {
for _ in $(seq 1 40); do
$PY -c 'import socket, sys; socket.create_connection((sys.argv[1], 6053), 1).close()' "$IP" 2> /dev/null && return 0
sleep 2
done
return 1
}
up || { echo "FAIL: board not reachable"; kill $CAP; exit 1; }; sleep 8
fail=0
if [ "$V" = cp ]; then
$PY "$S/api_button.py" "$IP" - press "Start portal" || { echo "FAIL: Start portal press"; fail=1; }
sleep 2
# The captive portal only answers /config.json while it is active.
CFG=$(curl -s -m 10 -o /dev/null -w '%{http_code}' "http://$IP/config.json")
echo "GET /config.json: $CFG"; [ "$CFG" = 200 ] || { echo "FAIL: captive portal not active"; fail=1; }
fi
PROBE=$(curl -s -m 10 -w ' %{http_code}' "http://$IP/probe")
echo "GET /probe: $PROBE"
ROOT=$(curl -s -m 10 -o /dev/null -w '%{http_code}' "http://$IP/")
echo "GET /: $ROOT"
# prometheus has no page at / (no answer on ESP32, 404 on ESP8266, on dev too)
[ "$V" = prom ] || [ "$ROOT" = 200 ] || { echo "FAIL: GET /"; fail=1; }
if [ "$V" = prom ]; then
MET=$(curl -s -m 10 -o /dev/null -w '%{http_code}' "http://$IP/metrics")
echo "GET /metrics: $MET"; [ "$MET" = 200 ] || { echo "FAIL: /metrics"; fail=1; }
fi
# A failed update also answers 200, with "Update Failed!" in the body.
OTA=$(curl -s -m 120 -F "update=@$BIN" -w ' %{http_code}' "http://$IP/update" | tr -d '\r\n')
echo "POST /update ($(wc -c < "$BIN" | tr -d ' ') B): $OTA"
sleep 5
if up; then
sleep 6
$PY "$S/ota_timing/apiinfo.py" "$IP=$D/.esphome/build/$N/build_info.json" 2>&1 | tail -1; API=${PIPESTATUS[0]}
else
echo "FAIL: board not back after the web OTA"; fail=1; API=1
fi
wait $CAP; CAPRC=$?
[ "$CAPRC" = 0 ] && [ -s "$C" ] || { echo "FAIL: serial capture failed or empty (rc $CAPRC)"; fail=1; }
[ "$PROBE" = "probe-ok 200" ] || { echo "FAIL: /probe"; fail=1; }
case "$OTA" in *"Update Successful!"*" 200") ;; *) echo "FAIL: web OTA"; fail=1;; esac
[ "$API" = 0 ] || { echo "FAIL: board not on the uploaded build after the web OTA"; fail=1; }
# The image is the same build, so prove the reboot from the log: setup finishes again after the OTA reboot line.
grep -a -q "Performing OTA reboot now" "$C" || { echo "FAIL: no OTA reboot in the serial log"; fail=1; }
sed -n '/Performing OTA reboot now/,$p' "$C" | grep -a -q 'setup() finished' || { echo "FAIL: no boot after the OTA"; fail=1; }
grep -a -q -E "Guru|abort\(\)|panic|[eE]xception \(|Soft WDT reset|wdt reset" "$C" && { echo "FAIL: crash"; fail=1; }
[ $fail = 0 ] && echo PASS; exit $fail
@@ -0,0 +1,36 @@
# variant: ws (web_server), cp (captive_portal only, started from a button) or prom (captive_portal and prometheus).
# A GET /probe handler is added after setup, the way an external component would.
substitutions:
name: web-handlers
plat: esp32
variant: ws
esphome:
name: ${name}
includes:
- probehandler.hpp
on_boot:
priority: -100
then:
- lambda: |-
web_server_base::global_web_server_base->add_handler(&probe_handler);
ESP_LOGI("probe", "probe handler added after setup");
packages:
plat: !include plat-${plat}.yaml
variant: !include ${variant}.yaml
logger:
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
ap:
password: webtest123
api:
reboot_timeout: 0s
ota:
- platform: esphome
- platform: web_server
@@ -0,0 +1,2 @@
web_server:
port: 80
@@ -0,0 +1,95 @@
"""Summarise the AP restart run: alive lines over syslog per DUT, reboots, gaps, recovery after each AP start.
Usage: an.py DIR BUILD [RECOVER_S] reads BUILD-marks.txt, BUILD-syslog.txt, BUILD-bk.txt, BUILD-cb.txt (optional)
and BUILD-up.txt (the bridge's API logs)
Exits 1 when a DUT rebooted, crashed, sent nothing, or had no syslog line within RECOVER_S (default 120) of an
AP start, when the BK7238 capture (or a CB3S capture that was started) is empty, or when the bridge did not switch
its AP to WPA2/WPA3 mixed after each AP start."""
from itertools import pairwise
from pathlib import Path
import re
import sys
D, b = Path(sys.argv[1]), sys.argv[2]
RECOVER = int(sys.argv[3]) if len(sys.argv) > 3 else 120
def read(suffix: str) -> str | None:
f = D / f"{b}-{suffix}.txt"
return f.read_text(encoding="utf-8", errors="replace") if f.exists() else None
def secs(t: str) -> int:
h, m, s = t.split(":")
return int(h) * 3600 + int(m) * 60 + int(float(s))
marks = [
(secs(line.split()[0]), line.split()[3])
for line in read("marks").splitlines()
if line.strip()
]
sl = (read("syslog") or "").splitlines()
bad = []
for dev in ("rebk", "recb"):
lines = [line for line in sl if re.search(rf"\b{dev}\b", line)]
ups = [
(secs(line.split()[0]), int(m[1]))
for line in lines
if (m := re.search(r"up (\d+) s", line))
]
if not ups:
print(f"== {dev}: no alive lines over syslog")
bad.append(f"{dev} silent")
continue
reboots = sum(1 for (_, u0), (_, u1) in pairwise(ups) if u1 < u0)
gaps = [t1 - t0 for (t0, _), (t1, _) in pairwise(ups) if t1 - t0 > 25]
print(
f"== {dev}: alive lines {len(ups)}, reboots {reboots}, syslog gaps over 25 s: {gaps}"
)
if reboots:
bad.append(f"{dev} rebooted")
for t, st in marks:
if st != "on":
continue
after = [x for x in ups if x[0] > t]
first = after[0][0] - t if after else None
print(
f" ap back at t={t % 86400 // 3600:02d}:{t % 3600 // 60:02d}:{t % 60:02d}, first syslog line {first} s later"
)
if first is None or first > RECOVER:
bad.append(f"{dev} not back {RECOVER} s after an AP start")
for dev, suffix in (("rebk", "bk"), ("recb", "cb")):
if (s := read(suffix)) is None and dev == "recb":
continue # the CB3S capture is optional
if not s:
bad.append(f"{dev} serial capture missing or empty")
continue
crashes = len(re.findall(r"(?i)hard fault|exception|abort|watchdog", s))
connected = len(re.findall(r"\[wifi:\d+\]: Connected", s))
print(
f"-- {dev} serial: lines {s.count(chr(10))}, overflow {s.count('queue overflow')}, fallback AP starts "
f"{s.count('Starting fallback AP')}, connected {connected}, boots {s.count('ESPHome version')}, crashes {crashes}"
)
if crashes:
bad.append(f"{dev} crashed")
up = read("up") or ""
switches = [
secs(m[1]) for m in re.finditer(r"\[(\d+:\d+:\d+)[.\d]*\].*PMF capable: 0", up)
]
# each AP start needs its own switch between that mark (less a few seconds of clock skew) and the next mark
ends = [t for t, _ in marks[1:]] + [float("inf")]
missed = [
t
for (t, st), end in zip(marks, ends, strict=True)
if st == "on" and not any(t - 5 <= s < end for s in switches)
]
starts = sum(1 for _, st in marks if st == "on")
print(
f"-- bridge: WPA2/WPA3 switches {len(switches)}, AP starts {starts} ({len(missed)} without a switch), "
f"failures {up.count('AP CONFIG FAILED')}"
)
if "AP CONFIG FAILED" in up or missed:
bad.append("the bridge did not switch its AP to WPA2/WPA3 mixed after every start")
print("PASS" if not bad else "FAIL: " + ", ".join(bad))
sys.exit(1 if bad else 0)
@@ -0,0 +1,58 @@
esphome:
name: ${name}
logger:
level: DEBUG
wifi:
networks:
- ssid: !secret wisp_up_ssid
password: !secret wisp_up_password
manual_ip:
static_ip: ${ip}
gateway: 10.40.0.1
subnet: 255.255.255.0
dns1: 10.40.0.1
power_save_mode: LIGHT
ap:
ssid: ${name}-fallback
password: !secret fallback_ap_password
captive_portal:
web_server:
port: 80
api:
reboot_timeout: 0s
ota:
- platform: esphome
udp:
addresses:
- !secret syslog_ip
time:
- platform: sntp
syslog:
port: 5514
interval:
- interval: 10s
then:
- lambda: ESP_LOGI("alive", "up %u s", (unsigned) (millis() / 1000));
- interval: 30s
then:
- if:
condition:
lambda: |-
static bool done = false;
if (done || millis() < 19 * 60 * 1000) return false;
done = true;
return true;
then:
- lambda: ESP_LOGI("alive", "GOING HOME");
- wifi.configure:
ssid: !secret wifi_ssid
password: !secret wifi_password
save: false
@@ -0,0 +1,13 @@
# BK7238 DUT (NiceMCU XH-WB3S), flashed over serial by run.sh
substitutions:
name: rebk
ip: 10.40.0.21
packages:
common: !include re-common.yaml
bk72xx:
board: xh-wb3s
logger:
hardware_uart: UART1
@@ -0,0 +1,13 @@
# CB3S (BK7231N) DUT, flashed over the air by run.sh; its log port is UART1 (TX1)
substitutions:
name: recb
ip: 10.40.0.22
packages:
common: !include re-common.yaml
bk72xx:
board: cb3s
logger:
hardware_uart: UART1
+57
View File
@@ -0,0 +1,57 @@
#!/bin/bash
# usage: run.sh BUILD OTA the CB3S, serial flash the BK7238, then switch the upstream AP off and on three times
# while both DUTs send alive lines over syslog. BUILD is a label (pr, base) for the output files.
# Copy this directory into a scratch directory with a secrets.yaml (wifi_ssid, wifi_password, wisp_up_ssid,
# wisp_up_password, fallback_ap_password, syslog_ip, api_key) and run it there. wisp-upstream-wpa3.yaml runs on the
# ethernet ESP32-S3 upstream; syslog_ip is this host's address as the DUTs reach it through the bridge's NAT.
# env: TREE (esphome checkout for the DUTs), BK_PORT (BK7238 serial), CB_PORT (CB3S log only serial, optional),
# CB_HOST (CB3S address to OTA), UPSTREAM (bridge address), SC (path to serial_capture.py), FLASH_BK (path to
# flash_bk72xx.py), LT (LibreTiny penv python), PY (checkout python), UP_TREE (checkout for the bridge's API logs)
D=$(cd "$(dirname "$0")" && pwd); b=${1:?build label}; T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}
BK=${BK_PORT:?set BK_PORT}; CBH=${CB_HOST:?set CB_HOST}; UP=${UPSTREAM:?set UPSTREAM}; SC=${SC:?set SC}
FB=${FLASH_BK:?set FLASH_BK}; LT=${LT:-$HOME/.platformio/penv/.libretiny/bin/python}; CB=${CB_PORT:-}
ap() { curl -s -m 5 -X POST -d "" -o /dev/null -w "%{http_code}" "http://$UP/button/ap%20$1/press"; }
# retry N PAUSE CMD...: run CMD up to N times, PAUSE seconds apart; fails when every attempt failed
retry() { local n=$1 pause=$2 i; shift 2; for i in $(seq "$n"); do "$@" && return 0; [ "$i" -lt "$n" ] && sleep "$pause"; done; return 1; }
build() { (cd "$T" && PYTHONUNBUFFERED=1 timeout 1500 $PY -m esphome "$@"); }
# only this run's ports: a global pkill stops other runs' captures
pkill -f "[s]erial_capture.py $BK"; [ -n "$CB" ] && pkill -f "[s]erial_capture.py $CB"
[ "$(ap on)" = 200 ] || { echo "FAIL: upstream bridge did not take ap on"; exit 1; }
cb_upload() { build run --no-logs "$D/recb.yaml" --device "$CBH" > "$D/cb-$b-upload.log" 2>&1; }
retry 3 15 cb_upload || { echo "FAIL: CB3S build or OTA after 3 tries"; exit 1; }
build compile "$D/rebk.yaml" > "$D/bk-$b-build.log" 2>&1 || { echo "FAIL: BK7238 build"; exit 1; }
UF2=$D/.esphome/build/rebk/.pioenvs/rebk/firmware.uf2
bk_flash() { $LT "$FB" flash write -d "$BK" "$UF2" > "$D/bk-$b-flash.log" 2>&1; }
retry 4 5 bk_flash || { echo "FAIL: BK7238 flash after 4 tries"; exit 1; }
PIDS=()
$PY - > "$D/$b-syslog.txt" 2>&1 << 'PYEOF' &
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("0.0.0.0", 5514))
s.settimeout(1)
end = time.time() + 1250
while time.time() < end:
try:
d, a = s.recvfrom(2048)
print(time.strftime("%H:%M:%S"), a[0], d.decode(errors="replace").strip(), flush=True)
except TimeoutError:
pass
PYEOF
PIDS+=($!)
$PY "$SC" "$BK" 1240 "$D/$b-bk.txt" --released > /dev/null 2>&1 & PIDS+=($!)
# an empty file marks the CB3S capture as requested, so an.py fails it if the capture never writes anything
[ -n "$CB" ] && { : > "$D/$b-cb.txt"; $PY "$SC" "$CB" 1240 "$D/$b-cb.txt" --released > /dev/null 2>&1 & PIDS+=($!); }
(cd "${UP_TREE:-$T}" && PYTHONUNBUFFERED=1 exec timeout 1240 $PY -m esphome logs "$D/wisp-upstream-wpa3.yaml" --device "$UP" > "$D/$b-up.txt" 2>&1) & PIDS+=($!)
trap 'kill "${PIDS[@]}" 2>/dev/null' EXIT
t0=$(date +%s); : > "$D/$b-marks.txt"
for step in 180:off 330:on 480:off 630:on 780:off 930:on; do
t=${step%%:*}; st=${step#*:}
while [ $(($(date +%s) - t0)) -lt "$t" ]; do sleep 1; done
code=$(ap "$st")
echo "$(date +%H:%M:%S) t=$t ap $st $code" | tee -a "$D/$b-marks.txt"
[ "$code" = 200 ] || { echo "FAIL: upstream bridge returned $code for ap $st"; exit 1; }
done
wait "${PIDS[@]}"; trap - EXIT
$PY "$D/an.py" "$D" "$b"
@@ -0,0 +1,3 @@
#pragma once
#include <esp_wifi.h>
#include <esp_event.h>
@@ -0,0 +1,95 @@
esphome:
name: wisp-upstream
includes:
- wdap_inc.h
on_boot:
priority: -100
then:
- delay: 3s
- script.execute: wpa3_ap
esp32:
board: esp32-s3-devkitc-1
variant: esp32s3
flash_size: 16MB
framework:
type: esp-idf
logger:
hardware_uart: USB_SERIAL_JTAG
ethernet:
type: W5500
clk_pin: GPIO13
mosi_pin: GPIO11
miso_pin: GPIO12
cs_pin: GPIO14
interrupt_pin: GPIO10
reset_pin: GPIO9
wifi:
ap:
ssid: !secret wisp_up_ssid
password: !secret wisp_up_password
ap_mode: WISP
manual_ip:
static_ip: 10.40.0.1
gateway: 10.40.0.1
subnet: 255.255.255.0
api:
encryption:
key: !secret api_key
reboot_timeout: 0s
ota:
- platform: esphome
web_server:
port: 80
button:
- platform: template
name: ap off
on_press:
- wifi.disable:
- platform: template
name: ap on
on_press:
- wifi.enable:
- delay: 3s
- script.execute: wpa3_ap
script:
- id: wpa3_ap
then:
- lambda: |-
static bool registered = false;
wifi_config_t c{};
esp_err_t err = esp_wifi_get_config(WIFI_IF_AP, &c);
if (err == ESP_OK) {
c.ap.authmode = WIFI_AUTH_WPA2_WPA3_PSK;
c.ap.pmf_cfg.required = false;
c.ap.sae_pwe_h2e = WPA3_SAE_PWE_BOTH;
err = esp_wifi_set_config(WIFI_IF_AP, &c);
}
// read back: only a running AP that reports WPA2/WPA3 mixed counts as switched
wifi_config_t check{};
if (err == ESP_OK)
err = esp_wifi_get_config(WIFI_IF_AP, &check);
if (err != ESP_OK || check.ap.authmode != WIFI_AUTH_WPA2_WPA3_PSK) {
ESP_LOGE("wdap", "AP CONFIG FAILED: %d authmode %d", err, (int) check.ap.authmode);
} else {
ESP_LOGI("wdap", "AP set to WPA2/WPA3 mixed, PMF capable: %d", err);
}
if (registered) return;
registered = true;
esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, [](void *, esp_event_base_t, int32_t id, void *data) {
if (id == WIFI_EVENT_AP_STACONNECTED) {
auto *e = (wifi_event_ap_staconnected_t *) data;
ESP_LOGI("wdap", "STA JOIN %02X:%02X:%02X:%02X:%02X:%02X", e->mac[0], e->mac[1], e->mac[2], e->mac[3], e->mac[4], e->mac[5]);
} else if (id == WIFI_EVENT_AP_STADISCONNECTED) {
auto *e = (wifi_event_ap_stadisconnected_t *) data;
ESP_LOGI("wdap", "STA LEAVE %02X:%02X:%02X:%02X:%02X:%02X reason %u", e->mac[0], e->mac[1], e->mac[2], e->mac[3], e->mac[4], e->mac[5], e->reason);
}
}, nullptr);
@@ -0,0 +1,16 @@
substitutions:
name: wispdut-aoi
framework: esp-idf
packages:
common: !include dut-common.yaml
wifi:
networks:
- ssid: !secret wisp_up_ssid
password: !secret wisp_up_password
post_connect_roaming: false
ap:
ssid: !secret dut_ap_ssid
password: !secret dut_ap_password
ap_mode: ALWAYS_ON
web_server:
port: 80
@@ -0,0 +1,16 @@
esphome:
name: ${name}
esp32:
board: esp32dev
framework:
type: ${framework}
logger:
level: DEBUG
api:
reboot_timeout: 0s
ota:
- platform: esphome
@@ -0,0 +1,14 @@
substitutions:
name: wispdut-wisp
framework: esp-idf
packages:
common: !include dut-common.yaml
wifi:
networks:
- ssid: !secret wisp_up_ssid
password: !secret wisp_up_password
ap:
ssid: !secret dut_ap_ssid
password: !secret dut_ap_password
ap_mode: WISP
captive_portal:
+36
View File
@@ -0,0 +1,36 @@
#!/bin/bash
# usage: run.sh DUT START SECONDS T:STATE... e.g. run.sh dut-wisp on 600 120:off 300:on
# Builds and flashes DUT.yaml (dut-wisp or dut-always-on) over serial, sets the upstream AP to START, captures the
# DUT and the client, and switches the upstream AP at each T seconds; sum.py summarises the client per phase.
# Copy this directory into a scratch directory with a secrets.yaml (wisp_up_ssid, wisp_up_password, dut_ap_ssid,
# dut_ap_password, lan_probe_url, api_key) and run it there. wisp-upstream.yaml runs on an ethernet ESP32-S3 and
# wispcli.yaml on a D1 mini; flash both once (CLI_FLASH=1 builds and flashes the client too).
# env: TREE (esphome checkout for the DUT), PORT (DUT serial), CLI_PORT (client serial), UPSTREAM (upstream bridge
# address), SC (path to serial_capture.py), PY (checkout python)
D=$(cd "$(dirname "$0")" && pwd); n=${1:?dut yaml name}; start=${2:?on or off}; dur=${3:?seconds}; shift 3
T=${TREE:?set TREE}; P=${PORT:?set PORT}; CP=${CLI_PORT:?set CLI_PORT}; UP=${UPSTREAM:?set UPSTREAM}
SC=${SC:?set SC}; PY=${PY:-$T/venv/bin/python}
ap() { curl -s -m 5 -X POST -d "" -o /dev/null -w "%{http_code}" "http://$UP/button/ap%20$1/press"; }
pkill -f "[s]erial_capture.py ($P|$CP)"
[ "$(ap "$start")" = 200 ] || { echo "FAIL: upstream bridge did not take ap $start"; exit 1; }
if [ "${CLI_FLASH:-0}" = 1 ]; then
(cd "$T" && PYTHONUNBUFFERED=1 timeout 1500 $PY -m esphome run --no-logs "$D/wispcli.yaml" --device "$CP" > "$D/wispcli-upload.log" 2>&1) \
|| { echo "FAIL: client build or upload"; exit 1; }
fi
(cd "$T" && PYTHONUNBUFFERED=1 timeout 1500 $PY -m esphome run --no-logs "$D/$n.yaml" --device "$P" > "$D/$n-upload.log" 2>&1) \
|| { echo "FAIL: DUT build or upload"; exit 1; }
echo "$(date +%H:%M:%S) t=0 upstream $start start" > "$D/$n-marks.txt" # phase 1 is the start state
$PY "$SC" "$P" "$dur" "$D/$n-dut.txt" --reset > /dev/null 2>&1 & C1=$!
# no --reset on the client: a CH340 D1 mini floods garbage after an RTS reset
$PY "$SC" "$CP" "$dur" "$D/$n-cli.txt" > /dev/null 2>&1 & C2=$!
trap 'kill $C1 $C2 2>/dev/null' EXIT
t0=$(date +%s)
for step in "$@"; do
t=${step%%:*}; st=${step#*:}
while [ $(($(date +%s) - t0)) -lt "$t" ]; do sleep 1; done
code=$(ap "$st")
echo "$(date +%H:%M:%S) t=$t upstream $st $code" | tee -a "$D/$n-marks.txt"
[ "$code" = 200 ] || { echo "FAIL: upstream bridge returned $code for ap $st"; exit 1; }
done
wait $C1 $C2; trap - EXIT
$PY "$D/sum.py" "$D" "$n"
@@ -0,0 +1,80 @@
"""Summarise the client's results per upstream phase and the DUT's connects, AP starts, crashes and boots.
Usage: sum.py DIR NAME reads NAME-marks.txt, NAME-cli.txt and NAME-dut.txt
Phase N runs from mark N (the first mark is the start state). Exits 1 when the DUT crashed, the DUT capture does not
hold exactly one boot (empty or rebooted), the client had no successful result at all, or a phase with the upstream
on had no successful name lookup (an answer equal to the gateway is the captive portal and does not count)."""
from collections import defaultdict
from pathlib import Path
import re
import sys
D, n = Path(sys.argv[1]), sys.argv[2]
def read(suffix: str) -> str:
return (D / f"{n}-{suffix}.txt").read_text(encoding="utf-8", errors="replace")
mark_lines = [line.split() for line in read("marks").splitlines() if line.strip()]
marks = [m[0] for m in mark_lines]
upstream = {
i + 1: m[3] for i, m in enumerate(mark_lines)
} # "HH:MM:SS t=N upstream on|off CODE"
cli = [line for line in read("cli").splitlines() if "[cli" in line]
def phase(t: str) -> int:
return sum(1 for m in marks if t >= m)
stat: dict[int, dict[str, int]] = defaultdict(lambda: defaultdict(int))
good: dict[int, int] = defaultdict(int) # successful name lookups per phase
any_ok = 0
for line in cli:
m = re.search(r"\]: (NOT CONNECTED|NET .*|NAME \S+|GW \S+|MAC \S+)", line)
if not m:
continue
s = m.group(1)
if s.startswith("NET"):
dns = re.search(r"dns (\S+)", s).group(1)
gw = re.search(r"gw (\S+)", s).group(1)
res = s.split("-> ")[1].strip()
# the captive portal answers every name with the AP's own address; that is not a working upstream
s = f"dns={dns} resolve={'CAPTIVE' if res == gw else res}"
if res not in ("FAIL", gw):
good[phase(line[1:9])] += 1
any_ok += 1
elif re.match(r"(NAME|GW|MAC) 200\b", s):
any_ok += 1
stat[phase(line[1:9])][s] += 1
for p in sorted(stat):
print(f"phase {p} (upstream {upstream.get(p, '?')}):", dict(stat[p]))
dead = [p for p, st in upstream.items() if st == "on" and not good[p]]
dut = read("dut")
crash = len(re.findall(r"Guru|panic|abort\(", dut))
boots = dut.count("ESPHome version")
print(
"DUT connected:",
len(re.findall(r"\[wifi:\d+\]: Connected", dut)),
"AP starts:",
dut.count("Starting AP"),
"crash:",
crash,
"boots:",
boots,
)
failed = []
if not cli:
failed.append("empty client log")
elif not any_ok:
failed.append("the client never got a successful result")
if dead:
failed.append(f"no successful lookup in upstream on phases {dead}")
# run.sh resets the DUT when the capture starts, so a good capture holds exactly one boot
if boots != 1:
failed.append(f"{boots} DUT boots captured, expected 1")
if crash:
failed.append(f"{crash} DUT crash lines")
print("PASS" if not failed else "FAIL: " + "; ".join(failed))
sys.exit(1 if failed else 0)
@@ -0,0 +1,52 @@
esphome:
name: wisp-upstream
esp32:
board: esp32-s3-devkitc-1
variant: esp32s3
flash_size: 16MB
framework:
type: esp-idf
logger:
hardware_uart: USB_SERIAL_JTAG
ethernet:
type: W5500
clk_pin: GPIO13
mosi_pin: GPIO11
miso_pin: GPIO12
cs_pin: GPIO14
interrupt_pin: GPIO10
reset_pin: GPIO9
wifi:
ap:
ssid: !secret wisp_up_ssid
password: !secret wisp_up_password
ap_mode: WISP
manual_ip:
static_ip: 10.40.0.1
gateway: 10.40.0.1
subnet: 255.255.255.0
api:
encryption:
key: !secret api_key
reboot_timeout: 0s
ota:
- platform: esphome
web_server:
port: 80
button:
- platform: template
name: ap off
on_press:
- wifi.disable:
- platform: template
name: ap on
on_press:
- wifi.enable:
@@ -0,0 +1,77 @@
esphome:
name: wispcli
esp8266:
board: d1_mini
logger:
level: DEBUG
wifi:
networks:
- ssid: !secret dut_ap_ssid
password: !secret dut_ap_password
reboot_timeout: 0s
ota:
- platform: esphome
http_request:
timeout: 5s
verify_ssl: false
globals:
- id: tick
type: int
initial_value: "0"
interval:
- interval: 3s
then:
- lambda: |-
id(tick)++;
if (id(tick) % 4 != 1) return;
if (!WiFi.isConnected()) { ESP_LOGI("cli", "NOT CONNECTED"); return; }
IPAddress r;
bool ok = WiFi.hostByName("neverssl.com", r, 3000);
ESP_LOGI("cli", "NET ip %s gw %s dns %s | neverssl.com -> %s", WiFi.localIP().toString().c_str(),
WiFi.gatewayIP().toString().c_str(), WiFi.dnsIP(0).toString().c_str(),
ok ? r.toString().c_str() : "FAIL");
- if:
condition:
lambda: return id(tick) % 4 == 2 && WiFi.isConnected();
then:
- http_request.get:
url: http://neverssl.com/
capture_response: true
max_response_buffer_size: 160
collect_headers:
- location
on_response:
- lambda: ESP_LOGI("cli", "NAME %d loc=%s body=%.60s", response->status_code, response->get_response_header("location").c_str(), body.c_str());
on_error:
- lambda: ESP_LOGI("cli", "NAME error");
- if:
condition:
lambda: return id(tick) % 4 == 3 && WiFi.isConnected();
then:
- http_request.get:
url: !lambda 'return std::string("http://") + WiFi.gatewayIP().toString().c_str() + "/";'
capture_response: true
max_response_buffer_size: 160
on_response:
- lambda: ESP_LOGI("cli", "GW %d body=%.60s", response->status_code, body.c_str());
on_error:
- lambda: ESP_LOGI("cli", "GW error");
- if:
condition:
lambda: return id(tick) % 4 == 0 && WiFi.isConnected();
then:
- http_request.get:
url: !secret lan_probe_url
capture_response: true
max_response_buffer_size: 64
on_response:
- lambda: ESP_LOGI("cli", "MAC %d body=%.20s", response->status_code, body.c_str());
on_error:
- lambda: ESP_LOGI("cli", "MAC error");
@@ -0,0 +1,56 @@
"""Summarise the PMF AP's join and leave events per station and the BK7238's joins.
Usage: an.py DIR BUILD [AP_SSID] reads DIR/ap-BUILD.txt and DIR/bk-BUILD.txt (AP_SSID defaults to wd-pmf-ap)
J = join, L<n> = leave with reason n. Reason 3: the station sent a deauth. Reason 2: the AP found a stale
association when the station came back; a run of reason 2 before one join is reconnects the AP rejected.
env DUT_MACS: comma separated station MACs that must appear in the AP events (default: at least two stations).
Exits 1 on a rejected reconnect, an AP that did not switch to WPA2/WPA3, a missing DUT, or a BK7238 that never
joined the AP."""
from itertools import pairwise
import os
from pathlib import Path
import re
import sys
D, b = Path(sys.argv[1]), sys.argv[2]
AP_SSID = sys.argv[3] if len(sys.argv) > 3 else "wd-pmf-ap"
failed = []
ap = (D / f"ap-{b}.txt").read_text(encoding="utf-8", errors="replace").splitlines()
if not any("PMF capable: 0" in line for line in ap) or any(
"AP CONFIG FAILED" in line for line in ap
):
failed.append("the AP did not switch to WPA2/WPA3 mixed")
ev = [line for line in ap if "STA JOIN" in line or "STA LEAVE" in line]
mac_re = re.compile(r"([0-9A-F]{2}(?::[0-9A-F]{2}){5})")
macs = sorted({m.group(1) for line in ev if (m := mac_re.search(line))})
rejected = 0
print(f"== {b}")
for m in macs:
seq = [
"J" if "JOIN" in line else "L" + re.search(r"reason (\d+)", line).group(1)
for line in ev
if m in line
]
# every L2 after the first in a run without a join in between is a rejected reconnect
rej = sum(1 for prev, cur in pairwise(seq) if prev == cur == "L2")
rejected += rej
print(" ", m, " ".join(seq), f"(rejected {rej})")
if rejected:
failed.append(f"{rejected} rejected reconnects")
if want := [
x.strip().upper() for x in os.environ.get("DUT_MACS", "").split(",") if x.strip()
]:
if missing := [x for x in want if x not in macs]:
failed.append(f"no AP events for {', '.join(missing)}")
elif len(macs) < 2:
failed.append(f"AP events for {len(macs)} stations, expected both DUTs")
bk = (D / f"bk-{b}.txt").read_text(encoding="utf-8", errors="replace").splitlines()
joins = [
m.groups() for line in bk if (m := re.search(r"JOINED (.+?) after (\d+) ms", line))
]
print(" bk7238 joins:", " ".join(f"{s}@{int(t) / 1000:.1f}s" for s, t in joins))
print(" bk7238 reboots:", sum("REBOOT on" in line for line in bk))
if not any(s == AP_SSID for s, _ in joins):
failed.append(f"the BK7238 never joined {AP_SSID}")
print("PASS" if not failed else "FAIL: " + "; ".join(failed))
sys.exit(1 if failed else 0)
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
# usage: run.sh BUILD flash the PMF AP, OTA the CB3S, serial flash the BK7238, then capture one AP window
# Copy this directory into a scratch directory with a secrets.yaml (wifi_ssid, wifi_password, wd_ap_password) and
# run it there. BUILD is a label (pr, base) for the output files.
# env: TREE (esphome checkout for the DUTs), AP_PORT (classic devkit running wdap.yaml), BK_PORT (BK7238 serial),
# CB_HOST (CB3S address on the house network), SC (path to serial_capture.py), FLASH_BK (path to flash_bk72xx.py),
# LT (LibreTiny penv python, default ~/.platformio/penv/.libretiny/bin/python), PY (checkout python), DUT_MACS
# (optional, comma separated station MACs of both DUTs for an.py)
D=$(cd "$(dirname "$0")" && pwd); b=${1:?build label}; T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}
AP=${AP_PORT:?set AP_PORT}; BK=${BK_PORT:?set BK_PORT}; CB=${CB_HOST:?set CB_HOST}; SC=${SC:?set SC}
FB=${FLASH_BK:?set FLASH_BK}; LT=${LT:-$HOME/.platformio/penv/.libretiny/bin/python}
pkill -f "[s]erial_capture.py ($AP|$BK)"
# retry N PAUSE CMD...: run CMD up to N times, PAUSE seconds apart; fails when every attempt failed
retry() { local n=$1 pause=$2 i; shift 2; for i in $(seq "$n"); do "$@" && return 0; [ "$i" -lt "$n" ] && sleep "$pause"; done; return 1; }
build() { (cd "$T" && PYTHONUNBUFFERED=1 timeout 1500 $PY -m esphome "$@"); }
build run --no-logs "$D/wdap.yaml" --device "$AP" > "$D/ap-$b-upload.log" 2>&1 || { echo "FAIL: AP build or upload"; exit 1; }
# The DUT reboots 150 s after joining the house network; retry when it reboots mid-upload.
cb_upload() { build run --no-logs "$D/wdcb.yaml" --device "$CB" > "$D/cb-$b-upload.log" 2>&1; }
retry 3 20 cb_upload || { echo "FAIL: CB3S build or OTA after 3 tries"; exit 1; }
build compile "$D/wdbk.yaml" > "$D/bk-$b-build.log" 2>&1 || { echo "FAIL: BK7238 build"; exit 1; }
# The build directory has two .uf2 files; firmware.uf2 is the one to flash.
UF2=$D/.esphome/build/wdbk/.pioenvs/wdbk/firmware.uf2
bk_flash() { $LT "$FB" flash write -d "$BK" "$UF2" > "$D/bk-$b-flash.log" 2>&1; }
retry 4 5 bk_flash || { echo "FAIL: BK7238 flash after 4 tries"; exit 1; }
sleep 20
# The reset restarts the AP's 420 s window.
$PY "$SC" "$AP" 450 "$D/ap-$b.txt" --reset > /dev/null 2>&1 & C1=$!
sleep 8
$PY "$SC" "$BK" 440 "$D/bk-$b.txt" --released > /dev/null 2>&1 & C2=$!
trap 'kill $C1 $C2 2>/dev/null' EXIT
wait $C1 $C2; trap - EXIT
$PY "$D/an.py" "$D" "$b"
@@ -0,0 +1,44 @@
esphome:
name: ${name}
logger:
level: DEBUG
globals:
- id: connect_ms
type: uint32_t
initial_value: "0"
wifi:
networks:
- ssid: ${ap_ssid}
password: !secret wd_ap_password
priority: 10
- ssid: !secret wifi_ssid
password: !secret wifi_password
priority: 0
on_connect:
- lambda: |-
id(connect_ms) = millis();
char buf[wifi::SSID_BUFFER_SIZE];
ESP_LOGI("wd", "JOINED %s after %u ms since boot", wifi::global_wifi_component->wifi_ssid_to(buf), (unsigned) millis());
api:
reboot_timeout: 0s
ota:
- platform: esphome
interval:
- interval: 5s
then:
- lambda: |-
if (!wifi::global_wifi_component->is_connected() || id(connect_ms) == 0)
return;
char buf[wifi::SSID_BUFFER_SIZE];
bool on_ap = strcmp(wifi::global_wifi_component->wifi_ssid_to(buf), "${ap_ssid}") == 0;
uint32_t up = millis() - id(connect_ms);
if (up > (on_ap ? 30000u : 150000u)) {
ESP_LOGI("wd", "REBOOT on %s", on_ap ? "ap" : "home");
App.safe_reboot();
}
@@ -0,0 +1,59 @@
substitutions:
ap_ssid: wd-pmf-ap
esphome:
name: wdap
includes:
- wdap_inc.h
on_boot:
priority: -100
then:
- delay: 3s
- lambda: |-
wifi_config_t c{};
esp_err_t err = esp_wifi_get_config(WIFI_IF_AP, &c);
if (err == ESP_OK) {
c.ap.authmode = WIFI_AUTH_WPA2_WPA3_PSK;
c.ap.pmf_cfg.required = false;
c.ap.sae_pwe_h2e = WPA3_SAE_PWE_BOTH;
c.ap.max_connection = 4;
err = esp_wifi_set_config(WIFI_IF_AP, &c);
}
// read back: only a running AP that reports WPA2/WPA3 mixed counts as switched
wifi_config_t check{};
if (err == ESP_OK)
err = esp_wifi_get_config(WIFI_IF_AP, &check);
if (err != ESP_OK || check.ap.authmode != WIFI_AUTH_WPA2_WPA3_PSK) {
ESP_LOGE("wdap", "AP CONFIG FAILED: %d authmode %d", err, (int) check.ap.authmode);
} else {
ESP_LOGI("wdap", "AP set to WPA2/WPA3 mixed, PMF capable: %d", err);
}
esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, [](void *, esp_event_base_t, int32_t id, void *data) {
if (id == WIFI_EVENT_AP_STACONNECTED) {
auto *e = (wifi_event_ap_staconnected_t *) data;
ESP_LOGI("wdap", "STA JOIN %02X:%02X:%02X:%02X:%02X:%02X aid %u t %u", e->mac[0], e->mac[1], e->mac[2], e->mac[3], e->mac[4], e->mac[5], e->aid, (unsigned) millis());
} else if (id == WIFI_EVENT_AP_STADISCONNECTED) {
auto *e = (wifi_event_ap_stadisconnected_t *) data;
ESP_LOGI("wdap", "STA LEAVE %02X:%02X:%02X:%02X:%02X:%02X aid %u reason %u t %u", e->mac[0], e->mac[1], e->mac[2], e->mac[3], e->mac[4], e->mac[5], e->aid, e->reason, (unsigned) millis());
}
}, nullptr);
- delay: 420s
- lambda: ESP_LOGI("wdap", "AP WINDOW OVER");
- wifi.disable:
esp32:
board: esp32dev
framework:
type: esp-idf
logger:
level: DEBUG
wifi:
ap:
ssid: ${ap_ssid}
password: !secret wd_ap_password
ap_timeout: 0s
ota:
- platform: esphome
@@ -0,0 +1,3 @@
#pragma once
#include <esp_wifi.h>
#include <esp_event.h>
Loaded 100 of 2077 files, more files were not shown because too many files have changed in this diff. Show more