Compare commits

..
Author SHA1 Message Date
J. Nick Koston 746775a4e5 Require proof of refused reads, fail on missing data, build the BLE server from SERVER_TREE and log when the sleep share is unavailable 2026-10-27 14:26:02 -10:00
J. Nick Koston d7770afa9a [ci] Add AmebaZ (BW12) serial flashing to the hardware-test skill 2026-10-27 14:22:29 -10:00
J. Nick Koston d0d1fb6088 Merge remote-tracking branch 'origin/dev' into hardware-test-skill-sync-10 2026-10-27 13:57:40 -10:00
J. Nick Koston af8542c7b9 Add the BLE server security pair, Prometheus datetime metrics and upload without a configuration flows; give the LD2450 stream harness OTA 2026-10-27 13:57:39 -10: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 34bbe618e3 Fail on short dumps and reads, missing data and an unstopped scan; check GET / and toggle only switches 2026-10-27 11:39:35 -10:00
J. Nick Koston a101d57476 [runtime_image] Hold the JPEG decoder state in a RAMUniquePtr (#21717) 2026-10-27 11:37:24 -10:00
J. Nick Koston 60bda810d0 Add the RTL8720C ROM dump matcher, BK72xx flash readback and partition diff, and LD2450 frame stream, presence hold, link loss and BT MAC drivers 2026-10-27 11:29:39 -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
J. Nick Koston 6c79b57a49 Wait on the API port so the captive portal variant is reachable before the portal starts 2026-10-27 10:29:12 -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
J. Nick Koston d96e758916 Build before flashing, tighten runner checks, reuse GPIO hold pins and quiesce scanning around BLE injection 2026-10-27 08:48:25 -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 a09e2e303e Check ping by exit status, prove the portal and the OTA reboot, and fail on a missing capture 2026-10-27 08:27:05 -10:00
J. Nick Koston 822bd4363b Add GPIO hold, BLE event injection, light sleep wake, manual IP and web handler flows to the hardware-test skill 2026-10-27 08:13:32 -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
3b1bf1dcba [core] Move shared BLE pairing constants to components/const (#21710)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-26 22:15:04 -10:00
72221aa0d3 [esp32_ble] Keep LL_TERMINATE_IND going until acknowledged on ESP32-C3/S3 (#20232)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-26 21:55:50 -10: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
J. Nick Koston 70448afb87 [ci] Stop saving an empty apt cache when the install fails (#21713) 2026-10-27 19:33:01 +13:00
J. Nick Koston 6ba8862ad8 [sendspin] Test the enabled switch codegen (#21671) 2026-10-26 19:54:36 -10:00
J. Nick Koston ca69cd06e9 [pipsolar] Use Apply switches (#21659) 2026-10-26 19:53:42 -10:00
J. Nick Koston c965c5ee70 [ld2410s] Use Apply entities for the select and numbers (#21662) 2026-10-26 19:53:04 -10:00
J. Nick Koston 97bbe58c8c [ld2410s] Test the select and number writes (#21661) 2026-10-26 19:53:04 -10: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
Clyde StubbsandClaude Opus 5.5 1cc6c9d1dd [core] Split AGENTS.md detail into skills, add schema extraction rule (#21606)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:16:25 -10: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
Clyde Stubbs f188d0c450 [http_request] Fix macOS host build with the precompiled header (#21705) 2026-10-27 14:11:05 +11: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
Jonathan Swoboda d4064d3f3d [core][nrf52] Make sdk-nrf a native toolchain (#21704) 2026-10-26 21:49:29 -04:00
Jonathan Swoboda 72c429bb0f [core] Fix a pylint false positive in idedata.py (#21706) 2026-10-27 01:30:39 +00:00
a9f970ca67 [modbus_monitor] Add modbus_monitor with on_request and on_response for server and client hubs (#20256)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: Dale Klein <49771139+dalklein@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-10-26 15:28:03 -10:00
1a50e1394a [vnc] Add input actions and touchscreen forwarding (#20627)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-26 12:48:25 -10:00
luar123andJ. Nick Koston ae1f912a5f [esp32] fix rtcio handling (#21576)
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-26 22:42:56 +00:00
916798184d [nextion] Keep a queued command when an unrelated response arrives (#19019)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-10-26 12:41:48 -10:00
Adam Matthews 1e49616bc5 [api] Fix compile of responding actions with array args (#21672) 2026-10-26 12:32:11 -10:00
esphome[bot] c66f71bb96 Bump aioesphomeapi from 46.22.0 to 46.23.0 (#21700) 2026-10-26 22:31:36 +00:00
8db0774d67 [integration] Test state_class on the integration sensor (#21489)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-26 12:28:18 -10:00
Jonathan Swoboda f735c4634e [esp32] Split and quote build flags in native ESP-IDF builds (#21680) 2026-10-26 17:54:37 -04:00
fe125726ee [template] Stop a running position action on the next cover command (#21599)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-26 11:39:25 -10:00
e05f2fc74e [copy] Forward cover toggle and lock open to the source (#21598)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-26 11:22:58 -10:00
PanoplianandJ. Nick Koston 4e68f1d324 [display] Warn when show_test_card is used with update_interval: never (#20887)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-26 11:12:41 -10:00
Bascht74andJ. Nick Koston 98706c594b [demo] Set the cover to idle when it is stopped (#21600)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-26 11:09:08 -10:00
Jonathan Swoboda 633c2b7f71 [core] Load !include_dir_* files in a fixed order (#21678) 2026-10-26 16:44:24 -04:00
dependabot[bot] 516511b346 Bump actions/setup-python from 7.0.0 to 7.1.0 (#21694)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 20:27:44 +00:00
dependabot[bot] f72dc7c329 Bump astral-sh/setup-uv from 10.3.0 to 10.3.2 (#21695)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 10:27:07 -10:00
dependabot[bot] f1695ac0b0 Bump CodSpeedHQ/action from 5.5.0 to 5.6.0 (#21692)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 10:27:01 -10:00
dependabot[bot] 24c64a8efd Bump prek from 0.5.6 to 0.5.7 (#21689)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 10:26:54 -10:00
dependabot[bot]andesphome[bot] d3638336ae Bump ruff from 0.17.1 to 0.17.2 (#21683)
Co-authored-by: esphome[bot] <115708604+esphome[bot]@users.noreply.github.com>
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 10:26:47 -10:00
dependabot[bot] 53bffb560b Bump tzlocal from 5.4.4 to 5.4.5 (#21686)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 10:26:44 -10:00
dependabot[bot] 2af39e6643 Bump smp from 4.1.0 to 4.2.0 (#21685)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 10:26:40 -10:00
dependabot[bot] 533a3afebd Bump actions/setup-python from 7.0.0 to 7.1.0 in /.github/actions/restore-python (#21690)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 10:26:34 -10:00
dependabot[bot] ddb7a6d9aa Bump astral-sh/setup-uv from 10.3.0 to 10.3.2 in /.github/actions/restore-python (#21688)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 10:26:28 -10:00
dependabot[bot] ae99accace Bump cryptography from 48.0.1 to 50.0.2 (#21684)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 10:26:15 -10:00
dependabot[bot] 474667d1a8 Bump github/codeql-action/init from 4.39.0 to 4.39.1 (#21693)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 10:26:08 -10:00
dependabot[bot] dbc93bb133 Bump docker/login-action from 4.6.0 to 4.7.0 in the docker-actions group (#21687)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 10:26:01 -10:00
dependabot[bot] 5486ef400f Bump github/codeql-action/analyze from 4.39.0 to 4.39.1 (#21691)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 10:25:54 -10:00
J. Nick Koston bd723f75af [pipsolar] Test the switch commands (#21655) 2026-10-26 16:17:27 -04:00
J. Nick Koston efba19ea3a [ld2420] Switch the module to simple reporting when the select picks Simple (#21651) 2026-10-26 08:29:45 -10:00
Jonathan Swoboda 6c68985c14 [core] Report missing dependencies of a component as an import error (#21670) 2026-10-26 14:05:19 -04:00
Jonathan Swoboda 7be8a7c390 [core][esp32] Reject git refs and github:// shorthands with unmatched text (#21656) 2026-10-26 14:05:11 -04:00
PolarGoose eb8cf139d7 [dlms_meter] Update parser to latest version to fix bogus error message on some smart meters (#21657) 2026-10-26 07:45:58 -10:00
Kevin Ahrendt ab6ebac628 [microphone] Zero muted audio in place before publishing (#21646) 2026-10-26 13:27:22 -04:00
6cb622417a [tas58xx] Add fault_output and modulation options (#21242)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-26 17:18:18 +00:00
Jonathan Swoboda 960316abd6 [core] Percent-encode "/" in git credentials (#21653) 2026-10-26 07:17:44 -10:00
Jonathan Swoboda 87341dc136 [logger] Enable Log V2 only on the native ESP-IDF toolchain (#21652) 2026-10-26 13:03:15 -04:00
J. Nick Koston cfe5809654 [wifi] Hand the DPP bootstrapping key to the supplicant DER encoded (#20882) 2026-10-26 16:37:25 +00:00
J. Nick Koston 9c54f96520 [libretiny] Send only the UF2 images the device writes over OTA (#21642) 2026-10-26 06:28:54 -10:00
J. Nick Kostonandpre-commit-ci-lite[bot] 0cc5b372fb [core] Defer integration imports in ir_rf_base and media_player (#21601)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-10-26 06:26:00 -10:00
J. Nick Koston f7c8cba8b7 [components] Use pulse_reset for blocking reset pin pulses (#21472) 2026-10-26 06:22:11 -10:00
J. Nick Koston 79a22e9a9a [core] Add pulse_reset for active-low reset pins (#21470) 2026-10-26 06:22:10 -10:00
J. Nick Koston 103023737d [openthread] Resolve IPv6 literal addresses when the DNS64 client is enabled (#19269) 2026-10-26 16:18:12 +00:00
J. Nick Koston 6b6b70a8b6 [dfrobot_sen0395] Collect lines with LineReader (#20979) 2026-10-26 12:16:51 -04:00
J. Nick Koston d312bf1b73 [core] Let the yaml editor insert lines, write with a rollback and restore (#20602) 2026-10-26 06:16:26 -10:00
J. Nick Koston 0d2f8c0e88 [components] Set or clear entity, socket and sensor bits with assign_bits (#21188) 2026-10-26 12:10:29 -04:00
J. Nick Koston 2f8b50c5af [components] Build the remaining enum option dicts with options() (#20972) 2026-10-26 12:10:08 -04:00
Kevin Ahrendt c4b598be3e [microphone] Pass each audio buffer as an AudioCapture (#21645) 2026-10-26 06:09:53 -10:00
J. Nick Koston 0cd16df16f [components] Write constant codec register tables with write_registers (#20946) 2026-10-26 12:09:47 -04:00
J. Nick Koston a680974da2 [ld6002b] Use Apply entities and find the setting by entity pointer (#20937) 2026-10-26 12:09:03 -04:00
J. Nick Koston 78f0b1ceba [esp32_rmt_led_strip] Stop blocking the main loop while waiting for the previous frame (#19337) 2026-10-26 06:08:13 -10:00
J. Nick Koston c5a841e11e [seeed_mr60fda2] Keep the parameter value tables in flash (#20720) 2026-10-26 12:07:24 -04:00
J. Nick Koston 365965f9bb [veml7700] Keep the gain and integration time tables in flash (#20719) 2026-10-26 12:07:06 -04:00
J. Nick Koston 16011d7fce [nextion] Keep the queue type name table in flash (#20658) 2026-10-26 12:06:31 -04:00
J. Nick Koston 4486dc53d8 [tx20] Keep the wind direction table in flash (#20657) 2026-10-26 12:05:43 -04:00
8d5e3ce534 [components] Use Apply selects for hub forwarding selects (#20966)
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-10-26 16:05:20 +00:00
J. Nick Koston 9ea4d35a50 [uart] Keep debug delimiters and event patterns in flash (#20109) 2026-10-26 12:05:06 -04:00
J. Nick Koston 5cceddfbf4 [kamstrup_kmp] Keep the unit name table in flash (#20642) 2026-10-26 11:58:43 -04:00
J. Nick Koston ff6a37a052 [micronova] Keep the stove state table in flash (#20645) 2026-10-26 11:58:15 -04:00
J. Nick Koston 6990092be0 [ezo] Keep the command and calibration type tables in flash (#20655) 2026-10-26 11:57:41 -04:00
J. Nick Koston 9220c79a51 [bme680_bsec] Keep the IAQ accuracy names in flash (#20656) 2026-10-26 11:57:23 -04:00
J. Nick Koston 215fcd4f5d [pulse_counter] Keep the edge mode name table in flash (#20660) 2026-10-26 11:57:03 -04:00
J. Nick Koston 918e3b3a58 [haier] Keep the protocol phase names in flash (#20710) 2026-10-26 11:56:43 -04:00
J. Nick Koston 347eb3902e [seeed_mr24hpc1] Keep the text sensor state tables in flash (#20711) 2026-10-26 11:55:18 -04:00
J. Nick Koston 177820083f [epaper_spi] Keep the state name table in flash (#20713) 2026-10-26 11:54:07 -04:00
J. Nick Koston b0a0524091 [cc1101] Keep the modulation name table in flash (#20716) 2026-10-26 11:53:10 -04:00
93b6388cb9 [sx127x] Keep the bandwidth and ramp tables in flash (#20650)
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-10-26 11:50:47 -04:00
J. Nick Koston 8677844629 [ld2410] Format the gate threshold test (#21649) 2026-10-26 05:50:10 -10:00
c1a9c8f2f1 [sx126x] Keep the bandwidth and ramp tables in flash (#20647)
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-10-26 15:49:44 +00:00
J. Nick Koston f35e45febf [ld2412] Send the output pin level when its select changes (#21353) 2026-10-26 11:46:42 -04:00
J. Nick Koston 9f47b5c7f8 [core] Defer mqtt, web_server and zigbee imports in sixteen entity components (#21508) 2026-10-26 05:45:52 -10:00
J. Nick Koston 58b6779dbe [components] Drain UART bytes with read_available (#20948) 2026-10-26 11:42:58 -04:00
J. Nick Koston bd881b025f [ld2410] Keep the select option names in flash (#21351) 2026-10-26 05:41:57 -10:00
J. Nick Koston c41b1f8f0f [components] Use Apply switches for hub forwarding switches (#20967) 2026-10-26 11:41:28 -04:00
J. Nick Koston 87b20ffdbb [uart] Collect fixed length frames with FrameReader in five components (#21449) 2026-10-26 05:41:11 -10:00
J. Nick Koston a3f38a9d4d [components] Use Apply numbers for hub forwarding numbers (#20965) 2026-10-26 11:40:15 -04:00
J. Nick Koston 76491691f5 [components] Use Apply buttons for hub forwarding buttons (#20964) 2026-10-26 11:39:42 -04:00
6791dc7750 [i2c] Add software I2C bus for BK72xx (#21586)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-26 05:36:57 -10:00
J. Nick Koston db76f0b1cd [logger] Defer platform imports out of module scope (#18336) 2026-10-26 05:35:47 -10:00
J. Nick Koston 09f7b71efd [nfc] Keep the URI prefix table in flash (#20709) 2026-10-26 11:34:18 -04:00
J. Nick Koston fd54bf7a07 [shelly_dimmer] Drop the device table fields that are never read (#20671) 2026-10-26 11:33:27 -04:00
J. Nick Koston 011497c447 [ezo_pmp] Keep the dosing mode names in flash (#20665) 2026-10-26 11:32:48 -04:00
J. Nick Koston 31bfdcb316 [rtttl] Keep the note frequency table in flash (#20664) 2026-10-26 11:32:18 -04:00
J. Nick Koston 42f50ac3bc [bl0939] Keep the init command table in flash (#20663) 2026-10-26 11:31:58 -04:00
J. Nick KostonandOmni Flux 3edbfb47b9 [logger] Add optional boot log buffer replayed over the API (#17666)
Co-authored-by: Omni Flux <omniflux@omniflux.com>
2026-10-26 05:08:27 -10:00
J. Nick Koston b622a59d74 [usb_audio] Flush the speaker's tail when the bus idles so a stream can stop and restart (#21103) 2026-10-26 05:01:15 -10:00
J. Nick Koston 0bfdbb948e [esp32] Enable ESP-IDF Log V2 on IDF 6.1+ (#17343) 2026-10-26 10:57:43 -04:00
J. Nick Koston 840f3216b8 [wifi_info][ethernet_info] Size the IP address child sensor array from the configured addresses (#21559) 2026-10-26 10:55:48 -04:00
J. Nick Koston e257b279d5 [ld2412] Keep the select option names in flash (#21350) 2026-10-26 04:54:05 -10:00
J. Nick Koston 125bd8ccd0 [ld2410][ld2410s][ld2412][ld2450][ld2460][dfrobot_sen0609] Use sensor::SensorWithDedup (#20926) 2026-10-26 10:47:14 -04:00
J. Nick Koston cce3511112 [ld2410][ld2412][ld2450][tfluna][dfrobot_sen0609] Use the button schema presets (#20916) 2026-10-26 10:46:43 -04:00
J. Nick Kostonandpre-commit-ci-lite[bot] 836b3220a2 [components] Look up declaring configs with get_declaring_config (#20913)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-10-26 10:46:18 -04:00
J. Nick Koston 49f2610595 [fusb302b] Filter the state triggers with when (#20859) 2026-10-26 10:45:58 -04:00
J. Nick Koston b49f3953f9 [i2c] Move 18 components to I2CDevice::update_register (#20855) 2026-10-26 10:44:57 -04:00
J. Nick Koston de9420a625 [sensor][number] Build in_range with register_apply_condition (#20848) 2026-10-26 10:43:22 -04:00
mrtoy-meandClaude Opus 5.5 ae127f7db8 [speaker][i2s_audio][es8156] Allow a list of audio DACs on one speaker (#21260)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 10:43:03 -04:00
J. Nick Koston 26ba2cc234 [http_request] Build ota.http_request.flash with register_apply_action (#20830) 2026-10-26 10:42:47 -04:00
J. Nick Koston 068fe3b7ce [libretiny] Reboot and report the previous boot's crash on BK7238 and BK7231N (#21012) 2026-10-26 04:42:30 -10:00
J. Nick Koston db6c956e55 [core] Add the YAML loader helpers store_yaml builds on (#21432) 2026-10-26 04:39:25 -10:00
J. Nick Koston c95ce587c0 [components] Use Apply outputs for hub channel outputs (#21257) 2026-10-26 04:38:23 -10:00
J. Nick Koston 3540ac4d1f [esp32] Describe each variant's GPIO rules with a pin spec (#21463) 2026-10-26 14:37:43 +00:00
J. Nick Koston 180d7b31d8 [components] Use shared helpers in recently added components (#21024) 2026-10-26 10:35:25 -04:00
J. Nick Koston 3cf79df27c [components] Use update_register and write_registers in the remaining I2C components (#21083) 2026-10-26 10:34:45 -04:00
J. Nick Kostonandpre-commit-ci-lite[bot] 2beb2de8a1 [web_server] Pass entity domain names from flash (#21115)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-10-26 10:33:04 -04:00
J. Nick Koston 9e457b11ba [dfrobot_sen0395] Use Apply switches (#21253) 2026-10-26 10:30:39 -04:00
J. Nick Koston ee41748744 [ld2420] Use fixed size storage and keep the mode strings in flash (#21347) 2026-10-26 10:30:11 -04:00
J. Nick Koston 08d4d59b1f [ld2450] Keep the baud rate, direction and zone type names in flash (#21349) 2026-10-26 10:29:29 -04:00
J. Nick Koston e4c0ef7c95 [ld24xx] Keep the unknown MAC text and version format in flash (#21352) 2026-10-26 10:22:42 -04:00
J. Nick Koston 26ee68652f [core] Add FrameReader to collect fixed length binary frames (#21446) 2026-10-26 04:20:59 -10:00
J. Nick Koston fa88c9218b [ld2412] Split frames by their length instead of scanning for footer bytes (#21360) 2026-10-26 04:19:37 -10:00
J. Nick Koston 44e27c08d8 [ld2450] Split frames by their length instead of scanning for footer bytes (#21357) 2026-10-26 04:19:20 -10:00
J. Nick Koston f431cdfb0c [haier_water_heater] Move child entities to sensor, binary_sensor and text_sensor platforms (#21437) 2026-10-26 10:18:05 -04:00
J. Nick Koston ba488eab6e [components] Apply inverted when restoring gree, hbridge, lvgl, opentherm and haier_tundra switches (#21544) 2026-10-26 04:16:56 -10:00
J. Nick Koston f21183c160 [esp32] Add a data driven pin spec for the variant GPIO validators (#21461) 2026-10-26 10:15:09 -04:00
J. Nick Koston 60ca75baad [ld2410] Split frames by their length instead of scanning for footer bytes (#21361) 2026-10-26 04:15:00 -10:00
J. Nick Koston b668cb1e50 [usb_uart] Use FixedRingBuffer for the receive buffer (#21476) 2026-10-26 10:14:32 -04:00
J. Nick Koston ab7d0ca17d [ltr390] Pack members, drop the float tables and expand gain and resolution in the schema (#21195) 2026-10-26 14:11:02 +00:00
J. Nick Koston 43f10a7cfe [core] Turn off the precompiled header with ccache older than 4.7 (#21627) 2026-10-26 04:09:55 -10:00
J. Nick Koston d5e755e407 [dfrobot_sen0395] Queue commands by value instead of allocating them on the heap (#20906) 2026-10-26 04:09:07 -10:00
J. Nick Koston cf67610d43 [xiaomi_ble] Move the Xiaomi sensors onto XiaomiDevice and fix the shared duplicate filter (#21483) 2026-10-26 04:08:39 -10:00
J. Nick Koston bd55bdcd6c [sen6x] Drop the product and serial strings (#21199) 2026-10-26 10:05:57 -04:00
J. Nick Koston f42d1ac645 [airton] Use an Apply select for the vane direction (#21252) 2026-10-26 10:05:13 -04:00
J. Nick Koston 5198c37cd9 [bedjet] Keep the device name in a fixed buffer (#21204) 2026-10-26 10:04:47 -04:00
J. Nick Koston d9fcc292e2 [components] Read hub-restored switch levels with get_initial_write_state (#21543) 2026-10-26 04:03:48 -10:00
J. Nick Koston 8f8e615ee7 [libretiny] Apply a level written before a pin becomes an output (#21603) 2026-10-26 04:03:25 -10:00
J. Nick Koston f91ad8d43c [ltr390] Wait the full integration time at 17, 16 and 13 bit (#21194) 2026-10-26 10:03:11 -04:00
J. Nick Koston 465a8b0386 [fan] Pack the fan traits flags and narrow the speed count to 16 bits (#21340) 2026-10-26 09:52:19 -04:00
J. Nick Koston 9e692b6772 [output] Add ApplyFloatOutput and ApplyBinaryOutput (#21255) 2026-10-26 09:49:49 -04:00
J. Nick Koston 1fd4025a0e [haier] Use Apply switches (#21251) 2026-10-26 09:46:30 -04:00
J. Nick Koston 03b8bd7941 [core] Add bulk push and pop to FixedRingBuffer (#21474) 2026-10-26 09:43:54 -04:00
J. Nick Koston 0e2c906fce [i2c] Put the device address after the bus pointer so derived classes reuse its padding (#21473) 2026-10-26 09:40:37 -04:00
J. Nick Koston d260265cf5 [ld6002b] Use StaticRingBuffer for the command queue (#21479) 2026-10-26 09:40:08 -04:00
J. Nick Koston 2388c3313d [xiaomi_ble] Add a shared XiaomiDevice base for MiBeacon devices (#21481) 2026-10-26 09:39:42 -04:00
J. Nick Koston e717a21bce [restart][shutdown][factory_reset][safe_mode] Use momentary Apply switches (#21519) 2026-10-26 09:37:12 -04:00
J. Nick Koston d47a510b84 [remote_base] Use the byte helpers in roomba, dooya and magiquest (#21513) 2026-10-26 09:09:36 -04:00
J. Nick Koston a16d0c48a0 [core] Add publish="momentary" for Apply switches that trigger an action (#21518) 2026-10-26 09:08:59 -04:00
J. Nick Koston 8541104d87 [switch] Add get_initial_write_state for hubs that restore their switches (#21542) 2026-10-26 09:04:41 -04:00
J. Nick Koston 579c5a5226 [components] Publish PROGMEM table strings on text sensors directly (#21537) 2026-10-26 09:02:38 -04:00
J. Nick Koston a027785fbf [libretiny] Bump LibreTiny to 1.14.0 and build BK7231N and BK7231T with BDK 3.0.78 (#21531) 2026-10-26 09:01:50 -04:00
J. Nick Koston d7f5976525 [http_request] Keep the OTA request strings out of RAM until a flash (#21556) 2026-10-26 09:00:04 -04:00
J. Nick Koston 4c8de264fd [remote_base] Keep the stateless dumpers in flash (#21563) 2026-10-26 08:59:08 -04:00
Bascht74andJ. Nick Koston 2d37ad6836 [api] Keep an entity's events in order under backpressure (#21567)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-25 23:57:11 -10:00
Clyde Stubbs d2f6b389d4 [runtime_image] Fix LVGL widgets on image resize (#21368) 2026-10-26 20:08:06 +11:00
Raphael Hehl 875b2076c0 [esp32_camera] Fix lost single image requests (#21613) 2026-10-25 22:04:24 -10:00
c21660251c [modbus_client] Pass the request's address to the send handlers (#20461)
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: Dale Klein <49771139+dalklein@users.noreply.github.com>
Co-authored-by: Bonne Eggleston <bonne@exciton.com.au>
2026-10-25 21:05:10 -10:00
esphome[bot] 995acb94b4 [ci] Refresh integration test durations (#21640) 2026-10-26 05:58:30 +00:00
Manuel MauszandJ. Nick Koston 24b7eefaad [remote_base] Add support for Cardin S438 remotes (#21507)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-25 19:56:32 -10:00
Clyde StubbsandClaude Opus 5.5 2349e0be00 [esp32] Check that code is mapped when reporting a crash (#21630)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:49:16 +11:00
Clyde StubbsandClaude Opus 5.5 63349801b7 [ci] Include dependencies added by overrides of dependency components (#21635)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:18:17 -10:00
afdfa7b298 [gree] Add use_fahrenheit for Fahrenheit display on the unit's panel (#20751)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-25 17:09:04 -10:00
JoHoenk 400407b135 [runtime_image] Allocate the JPEG decoder state from PSRAM (#21629) 2026-10-26 08:28:49 +11:00
Jonathan SwobodaandJ. Nick Koston 22b32b194a [core][scheduler] Count a cancelled item on a failed component as removed (#21626)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-25 15:36:17 -04:00
J. Nick Koston 6dcd989a7f [switch][number][text] Follow the source with plain binary sensors, sensors and text sensors (#21612) 2026-10-25 18:05:42 +00:00
J. Nick Koston 2016884210 [copy] Follow the source with plain sensors and text sensors (#21610) 2026-10-25 07:52:01 -10:00
1169 changed files with 31956 additions and 13557 deletions

No files matched your search

+215
View File
@@ -0,0 +1,215 @@
---
name: automations
description: Write ESPHome automation building blocks - triggers (on_* keys), actions and conditions. Use when adding or changing an on_* trigger, an action such as my_component.do_something, a condition, a callback registration method (add_on_*_callback), or code that calls build_callback_automation, build_automation, register_*_action or register_*_condition.
---
# Automations: triggers, actions and conditions
Automations have three building blocks: **Triggers** (fire when something happens), **Actions** (do
something), and **Conditions** (check if something is true). The helpers named here are documented in
their docstrings in `esphome/automation.py`.
## Triggers: callback method (preferred)
Use `build_callback_automation()` for simple triggers. This eliminates the need for a C++ Trigger class by
using a lightweight pointer-sized forwarder struct registered directly as a callback. No `CONF_TRIGGER_ID`
in the schema.
**Python:**
```python
from esphome import automation
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(MyComponent),
cv.Optional(CONF_ON_STATE): automation.validate_automation({}),
}
).extend(cv.COMPONENT_SCHEMA)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
for conf in config.get(CONF_ON_STATE, []):
await automation.build_callback_automation(
var, "add_on_state_callback", [(bool, "x")], conf
)
```
`build_callback_automation` arguments: `parent`, `callback_method` (C++ method name), `args` (template args
as `[(type, name)]` tuples), `config`, and optional `forwarder` (defaults to `TriggerForwarder<Ts...>`).
For boolean filtering (e.g. `on_press`/`on_release`), use built-in forwarders with `args=[]`:
```python
for conf_key, forwarder in (
(CONF_ON_PRESS, automation.TriggerOnTrueForwarder),
(CONF_ON_RELEASE, automation.TriggerOnFalseForwarder),
):
for conf in config.get(conf_key, []):
await automation.build_callback_automation(
var, "add_on_state_callback", [], conf, forwarder=forwarder
)
```
When the callback's parameters differ from the automation's arguments, or the trigger should only fire for
some values, pass `params`, `forward` and `when`; the helper then generates a capture-less lambda (stored
inline, nothing allocated). Name the parent with `automation.parent_ref(var)` and build `forward` from
`MockObj` calls, not f-strings of C++:
```python
parent = automation.parent_ref(var)
index = cg.RawExpression("index")
await automation.build_callback_automation(
var,
"add_on_state_callback",
[(cg.StringRef, "x"), (cg.size_t, "i")],
conf,
params=[(cg.size_t, "index")],
forward=[cg.StringRef(parent.option_at(index)), index],
)
```
`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`.
**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
class MyComponent : public Component {
public:
// Must be a template -- accepts both std::function and pointer-sized forwarder structs
template<typename F> void add_on_state_callback(F &&callback) {
this->state_callback_.add(std::forward<F>(callback));
}
protected:
// Use CallbackManager when callbacks are always registered (e.g. core components)
CallbackManager<void(bool)> state_callback_;
// Use LazyCallbackManager when callbacks are often not registered -- saves 8 bytes
// (nullptr vs empty std::vector) per instance when no callbacks are added
// LazyCallbackManager<void(bool)> state_callback_;
};
```
Never type a registration method's parameter as `std::function`; that forces a heap allocation for every
forwarder struct:
```cpp
// Bad
void add_on_state_callback(std::function<void(bool)> &&callback) {
this->state_callback_.add(std::move(callback));
}
```
| Type | Idle overhead (32-bit) | When to use |
|------|----------------------|-------------|
| `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) |
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
callback is added. Prefer it for entity-level callbacks where most instances have no subscribers.
## Triggers: Trigger class method
Use `build_automation()` with a `Trigger<Ts...>` subclass only when the forwarder needs **mutable state
beyond a single `Automation*` pointer** (e.g. edge detection tracking previous state, timing logic).
**Python:**
```python
TurnOnTrigger = my_ns.class_("TurnOnTrigger", automation.Trigger.template())
CONFIG_SCHEMA = cv.Schema(
{
cv.Optional(CONF_ON_TURN_ON): automation.validate_automation(
{cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(TurnOnTrigger)}
),
}
)
async def to_code(config):
for conf in config.get(CONF_ON_TURN_ON, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [], conf)
```
**C++:**
```cpp
class TurnOnTrigger : public Trigger<> {
public:
explicit TurnOnTrigger(MyComponent *parent) : last_on_{false} {
parent->add_on_state_callback([this](bool state) {
if (state && !this->last_on_)
this->trigger();
this->last_on_ = state;
});
}
protected:
bool last_on_;
};
```
## Actions
```cpp
template<typename... Ts> class MyAction : public Action<Ts...> {
public:
explicit MyAction(MyComponent *parent) : parent_(parent) {}
void play(const Ts &...) override { this->parent_->do_something(); }
protected:
MyComponent *parent_;
};
```
Register it without writing a builder:
```python
automation.register_simple_action(
"my_component.do_something", MyAction, schema, synchronous=True
)
```
The constructor receives the object named by `config[CONF_ID]`. Use `register_bare_action` for a
no-argument constructor, `register_parented_action` for a class deriving from `Parented<T>`, and the
`@automation.register_action(...)` decorator only when the builder must also set fields.
Use `synchronous=True` for actions that run to completion inside `play()` without deferring. Use
`synchronous=False` if the action may suspend/defer execution (e.g. `delay`, `wait_until`, `script.wait`)
or store trigger arguments for later use.
**Actions that only forward templatable values to their parent need no C++ class.** Register them with
`register_apply_action`; do not write a `TEMPLATABLE_VALUE` class or a builder for this shape.
```python
automation.register_apply_action(
"my_component.set_gains",
schema,
automation.ApplyField(CONF_KP, "set_kp", cg.float_),
automation.ApplyField(CONF_KI, "set_ki", cg.float_),
)
```
The `ApplyField`, `ApplyCall` and `register_apply_action` docstrings in `esphome/automation.py` cover the
rest; `cover.control` and `cover.template.publish` are in-tree examples. An action whose input is a byte
payload passes `automation.ApplyBytes(CONF_DATA, "send({})")` in the same call; a constant payload stays in
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.
## Conditions
```cpp
template<typename... Ts> class MyCondition : public Condition<Ts...> {
public:
explicit MyCondition(MyComponent *parent) : parent_(parent) {}
bool check(const Ts &...) override { return this->parent_->is_active(); }
protected:
MyComponent *parent_;
};
```
Register with `automation.register_simple_condition("my_component.is_active", MyCondition, schema)`;
`register_bare_condition`, `register_parented_condition` and the decorator follow the action rules.
**Conditions that only test their parent need no C++ class either.** Register them with
`register_apply_condition`; the expression is applied to the parent, and an `ApplyCall` compares against
config values.
```python
automation.register_apply_condition("my_component.is_active", schema, "is_active()")
automation.register_apply_condition(
"my_component.state_is",
schema,
automation.ApplyCall("state == {}", ((CONF_STATE, cg.bool_),)),
)
```
`cover.is_open`, `rtttl.is_playing` and `component.is_idle` are in-tree examples.
+68
View File
@@ -0,0 +1,68 @@
---
name: breaking-changes
description: Decide whether an ESPHome change breaks public API and handle it - what counts as public C++ and Python API, the deprecation window, ESPDEPRECATED for C++, cv.rename_key and deprecation warnings for config keys, and the migration notes a PR needs. Use when removing, renaming or changing the signature of a config option, a public C++ member or a core Python helper.
---
# Public API and breaking changes
Full policy: https://developers.esphome.io/contributing/code/#public-api-and-breaking-changes
## What is public
- **C++ in components:** only features documented at [esphome.io](https://esphome.io) are public API.
Undocumented `public` members are internal.
- **C++ core and base classes** (`esphome/core/`, `Component`, `Sensor`, etc.): all `public` members are
public API.
- **Components with global accessors** (`global_api_server`, etc.): all `public` members are public API
(except config setters).
- **Python:** all documented configuration options are public API. Python code in `esphome/core/` that
existing core components use is stable API. Other Python code is internal unless explicitly documented
for external component use.
- Changing the signature of a lambda that code generation injects is not a breaking change.
## Policy
- Aim for a **6-month deprecation window** when possible.
- Clean breaks are allowed for signature changes, deep refactorings and resource constraints.
- The migration path goes in the PR description (it generates the release notes).
- A blog post is required for core/base class changes or significant architectural changes.
Checklist:
- [ ] Clear justification (RAM/flash savings, architectural improvement)
- [ ] Explored non-breaking alternatives
- [ ] Added deprecation warnings if possible (`ESPDEPRECATED` for C++)
- [ ] Documented migration path in the PR description with before/after examples
- [ ] Updated all internal usage and esphome.io
- [ ] Tested backward compatibility during the deprecation period
## Deprecating C++
```cpp
// Remove before 2026.6.0
ESPDEPRECATED("Use new_method() instead. Removed in 2026.6.0", "2025.12.0")
void old_method() { this->new_method(); }
```
## Deprecating config keys
For a renamed key, use the shared `cv.rename_key` validator with `removed_in` (and `component` for
context); it warns and migrates automatically:
```python
CONFIG_SCHEMA = cv.All(
cv.rename_key(
CONF_OLD_KEY, CONF_NEW_KEY, removed_in="2026.6.0", component="my_component"
),
cv.Schema({...}),
)
```
For other deprecations, warn manually during validation:
```python
# Remove before 2026.6.0
if CONF_OLD_KEY in config:
_LOGGER.warning(
f"'{CONF_OLD_KEY}' deprecated, use '{CONF_NEW_KEY}'. Removed in 2026.6.0"
)
config[CONF_NEW_KEY] = config.pop(CONF_OLD_KEY) # Auto-migrate
```
Cover the old syntax with a `validate.*.yaml` test (see the `component-tests` skill), and keep the language
schema correct (see the `config-validation` skill).
+11 -5
View File
@@ -9,11 +9,13 @@ ESPHome parses YAML into C++ firmware for memory-constrained microcontrollers
(ESP32, ESP8266, RP2040, LibreTiny). Review changes with that in mind: RAM and
flash are scarce, and code runs unattended for months.
`AGENTS.md` in the repository root is the full contributor guide and the
authority when it disagrees with this summary. The developer documentation at
https://developers.esphome.io explains the component lifecycle and the reasoning
behind these rules. This skill lists the concrete things worth flagging in a
review; read `AGENTS.md` for the detail behind any item.
`AGENTS.md` in the repository root is the contributor guide, and the skills it
lists (`component-codegen`, `config-validation`, `automations`,
`embedded-memory`, `component-tests`, `breaking-changes`) hold the detail. They
are the authority when they disagree with this summary. The developer
documentation at https://developers.esphome.io explains the component lifecycle
and the reasoning behind these rules. This skill lists the concrete things worth
flagging in a review; read the matching skill for the detail behind any item.
Only raise findings that the diff actually introduces or changes. Do not ask for
drive-by cleanup of pre-existing code the PR did not touch.
@@ -76,6 +78,10 @@ performance nit, because it fragments a small shared heap. Flag:
`if (blah := config.get(CONF_BLAH)) is not None:`.
- Reuse existing validators from `config_validation.py` (`cv.rename_key`,
`cv.has_exactly_one_key`, etc.) via `cv.All(...)` instead of hand-rolling.
- A new or changed validator function that wraps, chooses or builds a schema
must be decorated with `@schema_extractor(...)` and handle `SCHEMA_EXTRACT`,
or `script/build_language_schema.py` silently drops the keys behind it (see
the `config-validation` skill).
- `esphome/const.py` is frozen: no new `CONF_` constants there. Define them in
the component's own `.py`, or in `esphome/components/const/__init__.py` when
shared. The same constant defined in three or more component files fails CI.
+241
View File
@@ -0,0 +1,241 @@
---
name: component-codegen
description: Write the Python side of an ESPHome component - __init__.py and platform files (sensor.py, switch.py, ...), DOMAIN and other metadata, to_code, hub child entities with sub_sensors and friends, pins and referenced components, hub-forwarding entities (ApplyButton, ApplySwitch), uart/i2c/spi constructor helpers, and CORE.data state. Use when creating a component or changing its code generation.
---
# Component code generation
Read https://developers.esphome.io/architecture/components/ for the component lifecycle and how a
component is registered. Schema rules and schema extraction are in the `config-validation` skill;
automations (`on_*`, actions, conditions) in the `automations` skill.
## Files
```
components/[component_name]/
├── __init__.py # Component configuration schema and code generation
├── [component].h # C++ header file (if needed)
├── [component].cpp # C++ implementation (if needed)
└── [platform]/ # Platform-specific implementations
├── __init__.py # Platform-specific configuration
├── [platform].h # Platform C++ header
└── [platform].cpp # Platform C++ implementation
```
## Metadata
- `DOMAIN`: required in every component's `__init__.py`, set to the component's own name as a plain string
(e.g. `DOMAIN = "my_component"`). Other code refers to the component through it, e.g.
`from esphome.components.my_component import DOMAIN`. Keep it in alphabetical order with the other
metadata constants. CI (`lint_component_domain`) fails without it.
- `DEPENDENCIES`: list of required components.
- `AUTO_LOAD`: components to automatically load. Not a way to put entities under the component's own key;
see "Entities of a hub" below.
- `CONFLICTS_WITH`: incompatible components.
- `CODEOWNERS`: GitHub usernames responsible for maintenance.
- `MULTI_CONF`: whether multiple instances are allowed.
## Basic pattern
```python
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import CONF_KEY, CONF_ID
DOMAIN = "my_component"
CONF_PARAM = "param" # A constant that does not yet exist in esphome/const.py
my_component_ns = cg.esphome_ns.namespace("my_component")
MyComponent = my_component_ns.class_("MyComponent", cg.Component)
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(MyComponent),
cv.Required(CONF_KEY): cv.string,
cv.Optional(CONF_PARAM, default=42): cv.int_,
}
).extend(cv.COMPONENT_SCHEMA)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
cg.add(var.set_key(config[CONF_KEY]))
cg.add(var.set_param(config[CONF_PARAM]))
```
```cpp
namespace esphome::my_component {
class MyComponent : public Component {
public:
void setup() override;
void loop() override;
void dump_config() override;
void set_key(const char *key) { this->key_ = StringRef(key); }
void set_param(int param) { this->param_ = param; }
protected:
StringRef key_;
int param_{0};
};
} // namespace esphome::my_component
```
When the setter takes the value unchanged, use `cg.add_optional(var.set_blah, config.get(CONF_BLAH))`; it
is not awaited, and it skips only `None`, so `0` and `False` are still set. Required, invariant
dependencies are constructor arguments to `cg.new_Pvariable()`, not setters.
## Entity platforms
**Sensor:**
```python
from esphome.components import sensor
CONFIG_SCHEMA = sensor.sensor_schema(MySensor).extend(
cv.polling_component_schema("60s")
)
async def to_code(config):
var = await sensor.new_sensor(config)
await cg.register_component(var, config)
```
**Binary sensor:**
```python
from esphome.components import binary_sensor
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema().extend({...})
async def to_code(config):
var = await binary_sensor.new_binary_sensor(config)
```
**Switch:**
```python
from esphome.components import switch
CONFIG_SCHEMA = switch.switch_schema().extend({...})
async def to_code(config):
var = await switch.new_switch(config)
```
## Entities of a hub
A new component's entities go in platform files (`sensor.py`, `binary_sensor.py`, ...) that take the hub's
id, never under the hub's own key with their platforms added to `AUTO_LOAD` to make that work. Auto loading
a platform because the C++ uses its type is fine. See
https://developers.esphome.io/architecture/components/#exposing-multiple-entities.
```yaml
# Bad - entities under the hub's key
my_hub:
connected:
name: Connected
# Good - the hub, then one platform entry that holds its entities
my_hub:
id: hub1
binary_sensor:
- platform: my_hub
my_hub_id: hub1 # optional with a single hub
connected:
name: Connected
```
**Optional child entities of a hub:** bind the config once with `sensor.sub_sensors(config)` (or
`sub_binary_sensors`, `sub_text_sensors`, `sub_buttons`, `sub_switches`, `sub_numbers`, `sub_selects` in
their domains), adding `parent=hub` for entities that derive from `Parented<T>`, then make one call per
key, even when there is only one. A call creates the entity only when its key is configured, passes it to
the setter and returns it (or `None`); extra arguments such as `min_value` or `options` go on the call.
Always name the setter explicitly on the object that owns it, never with `getattr` and an f-string, and
keep that variable short (`var` for the component itself, `hub` for one fetched with `cg.get_variable`) so
the calls fit on one line. Loops whose setter also takes an index, such as `set_gate_threshold(x, n)`, stay
as they are.
```python
# my_hub/sensor.py
async def to_code(config):
hub = await cg.get_variable(config[CONF_MY_HUB_ID])
sensors = sensor.sub_sensors(config)
await sensors(CONF_TEMPERATURE, hub.set_temperature_sensor)
await sensors(CONF_HUMIDITY, hub.set_humidity_sensor)
# my_hub/button.py
async def to_code(config):
hub = await cg.get_variable(config[CONF_MY_HUB_ID])
buttons = button.sub_buttons(config, parent=hub)
await buttons(CONF_RESTART, hub.set_restart_button)
```
**Hub forwarding entities need no C++ class:** a button, switch, number or select that only calls its hub
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, 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)
await switches(CONF_BLUETOOTH, None, apply="set_bluetooth(state)", publish="after")
```
Restore an owned or standalone switch in `setup()` with `sw->restore()`, or `restore(default)` to still
drive a state when the restore mode is disabled. A hub that applies its switches' restored states itself
reads `sw->get_initial_write_state()`, which already applies `inverted`.
**Entities that each watch a register field:** one class taking register, shift, mask and match from a
Python tuple table, in typed `StaticVector`s sized by `cg.slot_counter`; not a template per bit, not a
virtual listener base (a second vptr per entity).
## Other helpers
- **Pins and referenced components:** set them with `await cg.add_pin(var.set_cs_pin, config[CONF_CS_PIN])`
and `await cg.add_variable(var.set_bus, config[CONF_BUS_ID])`; both skip a `None` value, so pass
`config.get(KEY)` for an optional key, and return what they created. Use `cg.register_parented` for
`set_parent`.
- `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.
- `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.
- `fv.get_declaring_config(id)` finds a hub's config in final validation.
## State during code generation
Use `CORE.data` for component state that needs to persist during configuration generation, namespaced
under the component's `DOMAIN` and held in a `@dataclass`. Avoid module-level mutable globals: they
persist between compilation runs if the host process (e.g. device-builder) doesn't fork/exec, whereas
`CORE.data` is cleared between runs.
```python
from dataclasses import dataclass, field
from esphome.core import CORE
DOMAIN = "my_component"
@dataclass
class MyComponentData:
feature_enabled: bool = False
item_count: int = 0
items: list[str] = field(default_factory=list)
def _get_data() -> MyComponentData:
if DOMAIN not in CORE.data:
CORE.data[DOMAIN] = MyComponentData()
return CORE.data[DOMAIN]
def request_feature() -> None:
_get_data().feature_enabled = True
```
Don't use flat keys such as `CORE.data["my_component_feature"] = True`. Some components use `TypedDict`
instead of a dataclass; both are acceptable.
+101
View File
@@ -0,0 +1,101 @@
---
name: component-tests
description: Write and run tests for ESPHome components - YAML build tests (test.*.yaml, validate.*.yaml, common.yaml) under tests/components, shared bus packages and CI test grouping, C++ gtest unit tests, and host integration tests including the uart_mock fixture. Use when adding or changing files under tests/, or when a code change needs test coverage.
---
# Component tests
## C++ unit tests
gtests live in `tests/components/<component>/*.cpp` and run with `script/cpp_unit_test.py <component>`; see
`tests/components/README.md`. Set the loop clock in a test with `LoopBlockingGuard{nullptr, nullptr,
now_ms}`; the runner resets it before every test.
## Integration tests
`tests/integration/` runs real firmware on the host. Serial components prove timeouts and recovery with the
`uart_mock` fixture (`tests/integration/test_uart_mock_*.py`). Its `responses` match on content every time
they see it; to answer a repeated request differently, use an `on_tx` lambda with a static counter and
`inject_to_rx_buffer` (see `uart_mock_ld2412_requery_after_giveup.yaml`).
## YAML build tests
```
tests/
├── test_build_components/
│ └── common/ # Shared bus packages (uart, i2c, spi, etc.)
│ ├── uart/ # UART at default baud rate
│ ├── uart_115200/ # UART at 115200 baud
│ ├── i2c/ # I2C bus
│ └── spi/ # SPI bus
└── components/[component]/
├── common.yaml # Component-only config (no bus definitions)
├── test.esp32-idf.yaml # config + compile
├── test.esp8266-ard.yaml # config + compile
├── test-variant.esp32-idf.yaml # variant test, config + compile
├── validate.esp32-idf.yaml # config-only (never compiled)
└── validate-legacy.esp32-idf.yaml # config-only variant
```
Run them with `script/test_build_components`. Use `-c <component>` to test specific components and
`-t <target>` for specific platforms.
- **Keep build-test variants few:** one `test.<platform>.yaml` per platform the code actually differs on.
A variant per board for platform-identical code only adds CI time.
- **Config-only test files (`validate.*.yaml`):** use this prefix when a YAML file only needs to exercise
schema/validation paths and does not need to be compiled. CI runs `validate.*.yaml` files with
`esphome config` only and skips them during compile. The grammar mirrors `test.*.yaml`:
- `validate.<platform>.yaml`: base config-only test
- `validate-<variant>.<platform>.yaml`: config-only variant
Use this for deprecated-syntax migration tests, schema edge cases, or platform-specific validation
branches where building firmware adds no signal. A component may have any mix of `test.*.yaml` and
`validate.*.yaml` files. Validate files never participate in bus grouping; each one runs as its own
`esphome config` invocation.
When a PR's only edits to a component are `validate.*.yaml` files (no source changes, no `test.*.yaml`
changes, and the component isn't pulled in as a dependency of another changed component), CI skips the
compile stage for that component and only runs config validation. This is decided in
`script/determine-jobs.py` via `_component_change_is_validate_only` and surfaced as the
`validate_only_components` output that the `test-build-components-split` job consumes.
## Grouping with packages
Components that use shared bus packages can be grouped together in CI to reduce build count. **Never define
buses (uart, i2c, spi, modbus) directly in test YAML files**; always use packages from
`test_build_components/common/`.
All includes in test files must go through dict-style `packages:` so that batch grouping works; the
grouping scripts only understand dict-style packages. Never use list-style packages
(`packages: [- !include ...]`) or top-level merge keys (`<<: !include common.yaml`). Bus packages are keyed
by the bus name; the component's `common.yaml` is keyed by the component name (e.g.
`cst328: !include common.yaml`):
```yaml
# test.esp32-idf.yaml - everything included via named packages
packages:
uart: !include ../../test_build_components/common/uart_115200/esp32-idf.yaml
my_component: !include common.yaml
```
```yaml
# common.yaml - component config only, NO bus definitions
my_component:
id: my_instance
sensor:
- platform: my_component
name: My Sensor
```
Components that define buses directly are flagged as "NEEDS MIGRATION" and cannot be grouped, increasing
CI build time. `!extend` and `!remove` in a `test.*.yaml` also make the component ungroupable; add a
standalone entity with its own id instead.
A test that needs a shared component in a particular state (`esp32_ble` security settings, an option that
PSRAM rejects) cannot be grouped: the merged block wins and the whole batch fails. Add the component to
`ISOLATED_COMPONENTS` in `script/analyze_component_buses.py`, or move the option to a `test-<variant>` file.
To verify that all components can be tested together without ID conflicts or configuration issues:
```bash
./script/test_component_grouping.py -e config --all
```
This tests all components in a single build to catch conflicts that might not appear when testing
components individually. Use `-e config` for fast configuration validation, or `-e compile` for full
compilation testing.
+124
View File
@@ -0,0 +1,124 @@
---
name: config-validation
description: Write or change ESPHome configuration validation - CONFIG_SCHEMA, cv.Schema, cv.typed_schema, custom validator functions, config keys and CONF_ constants, renamed or deprecated keys, and the language schema that script/build_language_schema.py extracts from them. Use whenever a change touches a component's schema or a validator in config_validation.py, automation.py or a component's .py files.
---
# Configuration validation
ESPHome validates YAML with `voluptuous` schemas built from `esphome/config_validation.py` (`cv`). The
same schemas are also walked by `script/build_language_schema.py`, which produces the JSON language schema
that editors and the dashboard use for completion and checking. A validation change is only finished when
both still work.
## Writing schemas
- **Type hints:** validators are typed like any other function: `def validate_x(config: ConfigType) ->
ConfigType:`, with `ConfigType` imported from `esphome.types`.
- **One schema per model:** when a component's options depend on a `model` key, use
`cv.typed_schema({...}, key=CONF_MODEL, default_type=...)` with each model's own keys and defaults, not
one schema plus a validator that rejects keys and fills defaults afterwards.
- **Reuse existing validators:** before writing a custom validator, check for an existing one in
`config_validation.py` and compose it in `cv.All(...)` rather than duplicating logic across components.
For example, rename a config key with `cv.rename_key(CONF_OLD, CONF_NEW, removed_in="2026.6.0")`, and
reject mutually-exclusive keys with `cv.has_at_most_one_key(...)` / `cv.has_exactly_one_key(...)`. See
how `api` composes `cv.has_exactly_one_key` + `cv.rename_key`.
- **Common validators:** `cv.int_`, `cv.float_`, `cv.string`, `cv.boolean`, `cv.int_range(min=0,
max=100)`, `cv.positive_int`, `cv.percentage`.
- **Complex validation:** `cv.All(cv.string, cv.Length(min=1, max=50))`, `cv.Any(cv.int_, cv.string)`.
- **Platform-specific:** `cv.only_on(["esp32", "esp8266"])`, `esp32.only_on_variant(...)`,
`cv.only_on_esp32`, `cv.only_on_esp8266`, `cv.only_on_rp2040`.
- **Framework-specific:** `cv.only_with_framework(...)`, `cv.only_with_arduino`. On the ESP32, Arduino is
built as a component of ESP-IDF, so an ESP-IDF API, sdkconfig option or version floor is there on both
frameworks: gate on `esp32.require_idf_version(cv.Version(5, 5, 3), "psram_dma")`, which checks the
platform and the ESP-IDF under either framework, as `spi`, `usb_host` and `wifi` do. Reserve
`cv.only_with_framework("esp-idf")` for a build that has been tried on Arduino and fails there, and write
the actual failure next to it (`sendspin`: arduino-esp32 below ESP-IDF 6.0 bundles a second libsodium,
and from 6.0 sendspin-cpp's enumerators collide with `Arduino.h` macros such as `DISPLAY`).
- **Schema extensions:**
```python
CONFIG_SCHEMA = cv.Schema({ ... })
.extend(cv.COMPONENT_SCHEMA)
.extend(uart.UART_DEVICE_SCHEMA)
.extend(i2c.i2c_device_schema(0x48))
.extend(spi.spi_device_schema(cs_pin_required=True))
```
- **Constants:** `esphome/const.py` is frozen; do not add new `CONF_` constants there. Define a
component-local constant in the component's own `.py`; for a constant shared by multiple components, add
it to `esphome/components/const/__init__.py`. CI (`lint_constants_usage`) fails if the same constant is
defined in three or more component files. Constants used in core files (those not under
`esphome/components`) may be added to `esphome/const.py` but will require adjustment to the CI check.
- **Renamed or removed keys:** see the `breaking-changes` skill for `cv.rename_key` and manual
deprecation warnings.
- **Config-only tests:** schema edge cases and deprecated-syntax migrations go in `validate.*.yaml` test
files (see the `component-tests` skill).
## Schema extraction
`script/build_language_schema.py` sets `esphome.schema_extractors.EnableSchemaExtraction = True` before it
imports any component, then walks every `CONFIG_SCHEMA` (and platform schema) recursively. It understands
`cv.Schema`, `cv.All`, `cv.Any`, dicts of `cv.Required` / `cv.Optional` keys, `.extend()`, `cv.ensure_list`,
`cv.typed_schema`, registries and the known `cv` validators. **A plain function it cannot see into**: a
custom validator that builds or picks a schema at validation time hides every key behind it, and the
dumper silently emits nothing for them. CI only runs the script with `--check`, which does not compare the
output, so a lost schema is not caught.
When a validator function wraps, chooses or builds a schema (rather than checking a single value), make it
visible to the dumper:
1. Decorate it with `@schema_extractor("<type>")` from `esphome.schema_extractors`.
2. At the top of the function, return the data for that type when it is called with `SCHEMA_EXTRACT`
instead of a config value. Compare with `is` (`value is SCHEMA_EXTRACT`); older code uses `==`.
```python
from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor
@schema_extractor("schema")
def _outgoing_connection_schema(config: ConfigType | None) -> ConfigType:
if config is SCHEMA_EXTRACT:
return _OUTGOING_CONNECTION_SCHEMA
if config is None:
config = {}
return _OUTGOING_CONNECTION_SCHEMA(config)
```
The type names the dumper accepts, and what `SCHEMA_EXTRACT` must return for each, are in the
`hidden_schemas` branch of `convert()` in `script/build_language_schema.py`. The common ones:
| Type | Return for `SCHEMA_EXTRACT` | Example |
|------|-----------------------------|---------|
| `"schema"` | the schema (or a representative one) to walk | `api` `_outgoing_connection_schema`, `restore_state_schema` in `esphome/core/entity_helpers.py`, `model_schema_extractor` in `esphome/components/mipi/__init__.py` |
| `"enum"` | the dict of options | `sensor_entity_category` in `esphome/components/sensor/__init__.py` |
| `"one_of"` | the list of options | `cv.one_of` |
| `"maybe"` | `(validator, key)` for a scalar shorthand | `cv.maybe_simple_value`, `maybe_conf` in `esphome/automation.py` |
| `"templatable"` | the inner validator | `cv.templatable` |
| `"automation"` | the automation schema | `automation.validate_automation` |
Points to watch:
- The dumper matches the function object by `repr`, so the decorated function must be the exact object
placed in the schema. In a factory that returns a new closure per call, decorate the inner function (as
`restore_state_schema` and `cv.maybe_simple_value` do), not the factory.
- The decorator only records anything when extraction is enabled, and that flag is set before imports, so
the decorator must run at import time (module level or inside a factory called at module level).
- A schema chosen per config value (for example by `model`) has no single answer: return a representative
schema, as `model_schema_extractor` does.
- Plain value checks (`cv.All(cv.string, my_check)`) need nothing: the dumper still sees the surrounding
types and keys.
- `cv.Schema`, `cv.typed_schema`, `cv.ensure_list` and the `cv` helpers are already handled; prefer
composing them over a custom function, which also avoids the extractor work.
### Checking the output
Build the language schema into a scratch directory and look at the component's JSON (it takes about ten
seconds):
```bash
python3 script/build_language_schema.py --output-path /tmp/schema
python3 -c "import json; print(json.dumps(json.load(open('/tmp/schema/my_component.json')), indent=1))" | less
```
Every key a user can write should appear under `config_vars` with a sensible `type`; compare against the
same output from `dev` when changing an existing schema. If the script prints `Unknown extracted schema
type` or raises, the decorator type or the value returned for `SCHEMA_EXTRACT` is wrong. Unit tests for
the dumper live in `tests/script/test_build_language_schema.py`.
+169
View File
@@ -0,0 +1,169 @@
---
name: embedded-memory
description: Choose ESPHome C++ containers and storage that avoid heap use and fragmentation on microcontrollers - std::array, StaticVector with cg.slot_counter, FixedVector, std::unique_ptr byte buffers, StringRef, RAMAllocator, and what to avoid (std::vector growth, std::map, std::deque, std::string, new (std::nothrow)). Use when adding or changing C++ members, containers, buffers, strings or registration lists, or when reducing RAM or flash use.
---
# Memory on embedded targets
ESP devices run for months with small heaps shared between Wi-Fi, BLE, LWIP, and application code. Over
time, repeated allocations of different sizes fragment the heap. Failures happen when the largest
contiguous block shrinks, even if total free heap is still large. We have seen field crashes caused by
this.
**Heap allocation after `setup()` should be avoided unless absolutely unavoidable.** Every
allocation/deallocation cycle contributes to fragmentation. ESPHome treats runtime heap allocation as a
long-term reliability bug, not a performance issue. Helpers that hide allocation (`std::string`,
`std::to_string`, string-returning helpers) are being deprecated and replaced with buffer and view based
APIs.
## Container guidelines
1. **Compile-time-known sizes:** use `std::array` instead of `std::vector` when size is known at compile
time.
```cpp
// Bad - generates STL realloc code
std::vector<int> values;
// Good - no dynamic allocation
std::array<int, MAX_VALUES> values;
```
Use `cg.add_define("MAX_VALUES", count)` to set the size from Python configuration.
**For byte buffers:** avoid `std::vector<uint8_t>` unless the buffer needs to grow. Use
`std::unique_ptr<uint8_t[]>` instead. It does **not** provide bounds checking or iterator support like
`std::vector<uint8_t>`; use it only when you do not need these features.
```cpp
// Bad - STL overhead for simple byte buffer
std::vector<uint8_t> buffer;
buffer.resize(256);
// Good - minimal overhead, single allocation
std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(256);
// Or if size is constant:
std::array<uint8_t, 256> buffer;
```
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
allocation).
```cpp
// Bad - generates STL realloc code (_M_realloc_insert)
std::vector<ServiceRecord> services;
services.reserve(5); // Still includes reallocation machinery
// Good - compile-time fixed size, no dynamic allocation
StaticVector<ServiceRecord, MAX_SERVICES> services;
services.push_back(record1);
```
Use `cg.add_define("MAX_SERVICES", count)` to set the size from Python configuration.
**Listener and child-entity registration lists are the most common case, and the most commonly
missed.** A `register_*()` method called once per child at code generation time has a count that is
known at compile time, so it should never be a `std::vector`. Use `cg.slot_counter()`: it returns a
function that each consumer calls once per slot it will occupy, and after every `to_code` has run it
emits the define with the final count. When nothing registers, no define is emitted and the storage plus
its registration method compile out entirely.
```python
# hub component's __init__.py
_request_listener_slot = cg.slot_counter("MY_COMPONENT_LISTENER_COUNT")
async def register_listener(hub: MockObj, var: MockObj) -> None:
_request_listener_slot()
cg.add(hub.register_listener(var))
```
When several instances each own a list declared at the same size (one per hub of a `MULTI_CONF`
component), pass the owning object as the key, `_request_listener_slot(str(hub))`; the define is then
the largest count any one key requested instead of the total.
```cpp
#ifdef MY_COMPONENT_LISTENER_COUNT
void register_listener(MyComponentListener *listener);
#endif
protected:
#ifdef MY_COMPONENT_LISTENER_COUNT
StaticVector<MyComponentListener *, MY_COMPONENT_LISTENER_COUNT> listeners_;
#endif
```
Request slots from `to_code`, not from a job that runs after `CoroPriority.FINAL`; a late request
raises rather than silently undercounting.
3. **Runtime-known sizes:** use `FixedVector` from `esphome/core/helpers.h` when the size is only known at
runtime initialization.
```cpp
// Bad - generates STL realloc code (_M_realloc_insert)
std::vector<TxtRecord> txt_records;
txt_records.reserve(5); // Still includes reallocation machinery
// Good - runtime size, single allocation, no reallocation machinery
FixedVector<TxtRecord> txt_records;
txt_records.init(record_count); // Initialize with exact size at runtime
```
This eliminates `_M_realloc_insert` and `_M_default_append` template instantiations (200-500 bytes per
instance), needs no upper bound, and is compatible with protobuf code generation when using
`[(fixed_vector) = true]`.
4. **Small datasets (1-16 elements):** use `std::vector` or `std::array` with simple structs instead of
`std::map`/`std::set`/`std::unordered_map`.
```cpp
// Bad - 2KB+ overhead for red-black tree/hash table
std::map<std::string, int> small_lookup;
std::unordered_map<int, std::string> tiny_map;
// Good - simple struct with linear search (std::vector is fine)
struct LookupEntry {
const char *key;
int value;
};
std::vector<LookupEntry> small_lookup = {
{"key1", 10},
{"key2", 20},
{"key3", 30},
};
// Or std::array if size is compile-time constant:
// std::array<LookupEntry, 3> small_lookup = {{ ... }};
```
Linear search on small datasets is often faster than hashing or tree overhead, but this depends on
lookup frequency; in hot paths the O(1) vs O(n) difference may still matter. It is the heavy containers
(`map`, `set`, `unordered_map`) that should be avoided for small datasets unless profiling shows
otherwise.
5. **Strings set once from configuration:** use `StringRef` (`esphome/core/string_ref.h`) rather than
`std::string`. Code generation passes a string literal that lives in flash for the life of the program,
so storing a `std::string` copies it onto the heap for nothing. `StringRef` is a non-owning pointer plus
length; it does not copy, and it must only ever refer to storage that outlives it (a string literal, or
a buffer owned elsewhere).
```cpp
// Bad - heap copy of a literal that is already in flash
void set_keys(std::string keys) { this->keys_ = std::move(keys); }
std::string keys_;
```
```cpp
// Good - no allocation
void set_keys(const char *keys) { this->keys_ = StringRef(keys); }
StringRef keys_;
```
6. **Avoid `std::deque`:** it allocates in 512-byte blocks regardless of element size, guaranteeing at
least 512 bytes of RAM usage immediately. This is a major source of crashes on memory-constrained
devices.
7. **Never use `new (std::nothrow)`:** on ESP-IDF exceptions are disabled, so a failed nothrow allocation
aborts instead of returning `nullptr`. Use `RAMAllocator` from `esphome/core/helpers.h`; CI rejects
`std::nothrow`.
8. **Detection:** look for these patterns in compiler output:
- Large code sections with STL symbols (vector, map, set)
- `alloc`, `realloc`, `dealloc` in symbol names
- `_M_realloc_insert`, `_M_default_append` (vector reallocation)
- Red-black tree code (`rb_tree`, `_Rb_tree`)
- Hash table infrastructure (`unordered_map`, `hash`)
Callback storage (`CallbackManager` vs `LazyCallbackManager`) and templated registration methods are
covered in the `automations` skill.
## Where to spend effort
Prioritize container optimization for core components (API, network, logger), widely used components
(mdns, wifi, ble), and components causing flash size complaints. Avoiding heap allocation after `setup()`
is always required regardless of component type; the priority list is about effort spent on container
migration (e.g. `std::vector` to `StaticVector`).
+14 -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 boards (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 | `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).
## Templates in `$SKILL/templates`
@@ -125,9 +125,26 @@ 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)
- Download mode is a hand strap: CEN to GND, TX2 to GND, release CEN, release TX2. A plain USB-UART
does not drive CEN, so neither ltchiptool nor `serial_capture.py --reset` can reset the chip.
- 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.
## 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 +189,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
- [`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
- [`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,46 @@ 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.
@@ -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,10 @@
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.
@@ -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,9 @@
# 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.
@@ -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,49 @@
"""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.
"""
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()
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()
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))
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])}"
)
@@ -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,155 @@
# 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; }
esp_ble_gattc_register_for_notify(id(cli)->get_gattc_if(), id(cli)->get_remote_bda(), chr);
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,32 @@
#!/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; trap - EXIT
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,78 @@
"""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,
the write 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")
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",
"encrypted write reached the server": "secure write received" in srv,
"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,78 @@
"""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 = {}
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
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)
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 last:
note("NO-DATA: no entity state arrived")
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,71 @@
"""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.
"""
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) -> 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 = 0
for line in rows:
m = re.match(r'(esphome_\w+)\{.*name="([^"]+)"\} (-?\d+)$', line)
if not m:
print(f" UNPARSED {line}")
continue
parsed += 1
metric, name, value = m.group(1), m.group(2), int(m.group(3))
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
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):
c.time_command(e.key, 23, 59, 59)
elif isinstance(e, DateTimeInfo):
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")
metrics("after setting 2040-03-04, 23:59:59 and 2040-03-04 05:06:07 UTC")
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"
Loaded 100 of 1169 files, more files were not shown because too many files have changed in this diff. Show more