Compare commits

..
1258 changed files with 9790 additions and 55612 deletions

No files matched your search

+6 -28
View File
@@ -67,17 +67,9 @@ 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. 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.
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.
## Flashing by chip family
@@ -119,11 +111,11 @@ ESP-IDF OTA image: `.esphome/build/<name>/build/firmware.ota.bin`. LibreTiny OTA
or exits 1 when a build, flash or port step failed.
Per-topic scripts, each described in the matching `reference/recipes/<component>.md`: `online_image/`
(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/`
(server, image generator, API driver), `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), `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).
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), `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), `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).
## Templates in `$SKILL/templates`
@@ -140,21 +132,7 @@ capture decoder), `api_outgoing/` (wake cycle and Wi-Fi drop timing readers), `l
`globals-storage-dut.yaml`, `usb-audio-waveshare-s3-eth-dut.yaml`, `usb-audio-sendspin-s3-eth-dut.yaml`,
`cast-pro-1-sendspin-control.yaml`, `aux-2-preprod-stock-dut.yaml`, `aux-2-preprod-usb-audio-dut.yaml`,
`dfrobot-sen0395-dut.yaml`, `aux-2-preprod-speaker-player-dut.yaml`, `web-server-sse-dut.yaml`,
`mqtt-transport-dut.yaml`, `mqtt-tls-dut.yaml`, `udp-write-dut.yaml`, `entity-icon-dut.yaml`,
`online-image-s3-eth-dut.yaml`,
and the directories `store_yaml/` (package with secrets one directory up, per-board files),
`http_request_update/` (manifest URL setter shapes, per-board files), `modem/` (modem only and modem plus
Wi-Fi boot checks), `ble_midi/` (fake BLE MIDI instrument and the client), `http_request_action/` (request
action package with per-board files and an OTA flash variant) `uart_sim/` (simulator header, common package, per-build parts and run files) and `remote_base/` (common
package, transmit script, per-board templates and the ESP8266 software sender).
## When the PR keeps moving
Record every head in the stack (`gh pr view N --json headRefOid`), build, and recheck before flashing; if anything
moved, wait five minutes and check again so the test runs on a settled head. When a head moved only by merging dev,
compare the PR's own diff (`git diff $(git merge-base OLD origin/dev) OLD` against the same for NEW); if it is
identical and the dev commits do not touch the code under test, earlier results still describe it, but rebuild so the
comment quotes the exact commits. Fetch `origin dev` before computing a merge base.
`mqtt-transport-dut.yaml`, `mqtt-tls-dut.yaml`, `udp-write-dut.yaml`, `entity-icon-dut.yaml`.
## When something looks wrong
@@ -50,9 +50,6 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
USB replug fixes it. Fallback: `esphome logs --device <name>.local` (API log stream, which drops lines
while Wi-Fi is off).
- The ESP32-P4 before silicon revision 3 is bricked by rev3-only firmware (boot loop at bootloader entry).
- A board left in the ROM bootloader after an upload (BOOT held, or the USB JTAG reset landing in download mode
again) starts its app without a replug through `esptool --port <port> --after watchdog-reset chip-id`; flash a
minimal Wi-Fi plus API image first when recovering from a crash-looping one.
## RP2040 / RP2350 (Pico W, Pico 2 W)
@@ -86,8 +83,6 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
from `~/.platformio/packages/toolchain-gccarmnoneeabi/bin/` (`raw_firmware.elf`, not `firmware.elf`).
Fault dumps print PC, LR and R0 to R3.
- The AmebaZ2 SDK sets `LWIP_TCPIP_CORE_LOCKING 0`.
- The `rtw_is_adapter_up` bus fault after `Disabling AP` happens on LibreTiny 1.13.0 and 1.14.0 alike
(2 of 4 and 3 of 3 runs in #21531); run at least four rounds per build before blaming a PR for it.
## BK7238, WB3S, CB3S (BK7231N) (LibreTiny bk72xx, CH340, RTS on CEN)
@@ -118,18 +113,6 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
SDK's saved register banks are usable. Code is compiled Thumb, the SDK assembly is ARM; in an exception
handler only r0 to r3 are shared by all modes. BK7231N ITCM is `0x3FEE00..0x400000` (4.5 KB); a `.noinit`
placed there after `.itcm.code` works for a crash record.
- Pick the board that matches the module's flash layout. A NiceMCU XH-WB3S (BK7238) needs `board: xh-wb3s` (plain
Beken layout, RF calibration at 0x1E0000). Built as `generic-bk7238-tuya` (calibration at 0x1E3000, download
partition over 0x1E0000) the firmware boots and may even join a known network, but scans come back empty and its
AP is invisible to clients, with no warning in the log. If scans are empty, check the layout first.
- 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.
@@ -177,12 +160,6 @@ Ports are not listed on purpose: they follow the USB hub port and change on ever
the port open, and the logger warns `logger took a long time`. Print one line per `loop()` instead.
- Zephyr settings survive a reflash: key a `restore_value` global by a `run` substitution when a test needs
a never-saved value.
- 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
@@ -4,27 +4,24 @@ Each flow names the pull requests it was used on, so their result tables show wh
One file per component, named after it:
- [`api.md`](api.md): noise handshake and OTA encryption on the ESP8266, outgoing connection wake timing on deep sleep and after a Wi-Fi drop, user defined action listing and execution with a raw plaintext client, store_yaml recovery over Noise or plaintext
- [`ble_midi.md`](ble_midi.md): BLE MIDI client against a fake ESP32 instrument, every packet shape and the send actions
- [`api.md`](api.md): noise handshake and OTA encryption on the ESP8266, outgoing connection wake timing on deep sleep and after a Wi-Fi drop, user defined action listing and execution with a raw plaintext client
- [`captive_portal.md`](captive_portal.md): fallback AP and /wifisave hammer
- [`cse7766.md`](cse7766.md): Sonoff S31 parser check over the API
- [`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
- [`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
- [`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
- [`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
- [`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
- [`online_image.md`](online_image.md): stalled and malformed downloads
- [`openthread.md`](openthread.md): border router on the S3 host plus H2 RCP
- [`ota.md`](ota.md): overlap and lock, timeouts, deflate, upload timing A/B per build and board with deflate and raw, on-device inflate benchmark
- [`ota.md`](ota.md): overlap and lock, timeouts, deflate
- [`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, reboots against a WPA2/WPA3 PMF access point, WISP and ALWAYS_ON AP switching, AP restarts with WPA3 mixed and LIGHT power save
- [`wifi.md`](wifi.md): reboot_timeout with a fallback AP, DHCP lease cache, Easy Connect (DPP), WISP bridge with an ethernet upstream
- [`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
@@ -34,10 +31,3 @@ One file per component, named after it:
- [`dfrobot_sen0395.md`](dfrobot_sen0395.md): SEN0395 mmWave command flow, module quirks and overlong lines through its error reply
- [`speaker.md`](speaker.md): media player pipeline tasks on the Connect AUX-2 with the `speaker` platform player
- [`web_server.md`](web_server.md): state SSE stress and the HTTPD task stack on web_server_idf, entity icon and device class readback
- [`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
- [`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
@@ -40,19 +40,3 @@ length delimited strings and `int[]` as repeated sint32 (field 7); `ALLOW_MISSIN
defaults) and `templates/api-actions-strings-dut.yaml` (required strings) log what arrived. String arguments are
`StringRef`s that are not null terminated: copy them with `snprintf("%.*s", size, c_str())` into a buffer before
logging, and do not pass `%.*s` to `logger.log`, whose validator counts it as one pattern.
## store_yaml recovery over the native API (#16445)
`scripts/api/syrecover.py HOST KEY OUTDIR [ORIGDIR]` (KEY `-` for plaintext) builds the client library's
`APINoiseFrameHelper` around a stub `APIConnection` subclass (the compiled helper type checks the connection, and
`ConnectionParams` needs every field), sends Hello, Authentication (never answered without a password) and
`DeviceCapabilitiesRequest`, then `GetYamlRequest` (161), collects `GetYamlResponse` (162) frames by field number
(1 data, 2 done, 3 total_size, 4 encoding) until done, requests again, decompresses with `compression.zstd` (Python 3.14, or the `zstandard` package) and
unpacks the envelope with the tree's `unpack_envelope` (run with `PYTHONPATH` on that tree). Configs in
`templates/store_yaml/`: entry files in `boards/`, a package one directory above them with `!secret` and an inline
OTA password,
so the redaction and the `..` paths are exercised. Repetitive YAML compresses into one chunk even at 22 KB; a 6 KB
include of random base64 lines with `include_secrets: true` gives four chunks (1390 byte packets). Rough edge at
0bd3738430: `include_secrets: true` fails the build when a package in another directory uses `!secret` and has no
`secrets.yaml` beside it; a copy next to the package works around it.
Results: https://github.com/esphome/esphome/pull/16445#issuecomment-6335435397
@@ -1,19 +0,0 @@
# ble_midi
## BLE MIDI client against a fake instrument (#18508)
No MIDI hardware needed: `templates/ble_midi/midiperi.yaml` turns a second ESP32 (an S3 with ethernet, so the
API stays reachable while BLE is busy) into a BLE MIDI peripheral with `esp32_ble_server`: the MIDI service
advertised, the MIDI characteristic with read, write, write without response and notify, an `on_write` that logs
the bytes, buttons that notify hand built packets (channel messages, two messages in one packet, running status,
SysEx in one packet, split over two, oversize, cut short, clock, aftertouch, orphan data bytes, a 50 packet burst)
and a restart button for the disconnect test. `midicli.yaml` is the component test config on a classic devkit with
`wifi:`, `api:`, the peripheral's BLE address in the `peri_mac` substitution, given on the command line with
`-s peri_mac <mac>` (the base MAC plus 2, printed by `esp32_ble` in `dump_config`), `on_sysex` and `on_message` lambdas that print the bytes, debug sensors and out of range send
buttons. Drive both over the plaintext API with `scripts/modem/mdrive.py HOST LOGFILE press:NAME wait:S` 3 s
apart and compare the peripheral's `TX` and `RX` lines with the client's decoded lines. Gotcha:
`ble_server.characteristic.set_value` latches the value of its first play and re-applies it before every notify,
so the peripheral script sets the value from a lambda (`id(midi_io).set_value(std::vector<uint8_t>(pkt));
id(midi_io).notify();`). At VERBOSE the client logs four lines per message, so a burst shows an
`esp32_ble took a long time` of a couple of seconds that is the serial port, not the parser.
Results: https://github.com/esphome/esphome/pull/18508#issuecomment-6348272717
@@ -1,17 +0,0 @@
# 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).
@@ -1,13 +0,0 @@
# GPIO expanders
## Interrupt driven base class (#21469, #21468)
Any device with a PCF8574 input expander whose INT line goes to an ESP32 GPIO works; the inputs should change
during the test (end switches on a gate or cover are ideal). Before flashing, check with `nm` that
`gpio_expander::interrupt_pin_isr` lands in IRAM (0x4008xxxx on a classic ESP32). Then confirm `dump_config` lists
the interrupt pin and the input states match reality, and that the `pcf8574` entry is absent from the runtime stats
while idle (its loop is disabled). Drive the inputs (for a cover, `cover_command(position=1.0)` and then `0.0` over
the API, waiting for each end state): every input edge should log, `pcf8574` should show a small count in that
minute's stats and vanish in the next. For a device that cannot be reached physically, boot the same code on a
bench board first and keep a merge base image built as the fallback; an ESP32 bootloader without rollback support
leaves only `safe_mode` to recover a bad image.
@@ -1,48 +0,0 @@
# http_request
## Update manifest URL changed at run time (#21373)
`scripts/http_request/manifest_server.py PORT [DELAY]` serves `stable.json`, `beta.json` and `slow.json` (answered
after DELAY s) with both chip families and logs every request. `templates/http_request_update/upd-common.yaml`
(secret `manifest_base` is the server URL) has the update entity on the stable manifest, buttons for every
`set_source_url` shape (`std::string` local, literal, temporary, `.c_str()` of a local, the current URL back in),
`Check Then Swap` (ESP32 task path: check the slow manifest and replace the URL in the same lambda), `Arm Swap In
Check` plus a `logger: on_message` lambda that replaces the URL from inside the inline check (ESP8266; the log line
from inside `on_message` is swallowed, judge by the next check's result), and a `Heap` button. `upd-base-common.yaml`
keeps only the shapes that compile on a tree with the bare pointer setter (for the base build, copy a board file
and point its `common` include at `../upd-base-common.yaml` with a different `name:`); `boards/upd8266.yaml` and `boards/upd32.yaml` are the
per-board files, one directory below the package their `../` include points at. Drive with `scripts/http_request/updrive.py HOST KEY LOGFILE press:NAME wait:S`, which prints every
update state (latest version, summary). The ESP8266 Arduino client gets `Error reading manifest: -1` on roughly a
quarter of the fetches from this Python server on every build, so count checks against the base before blaming a
PR. `http_request` on the ESP8266 needs `verify_ssl: false` even for plain http URLs.
Results: https://github.com/esphome/esphome/pull/21373#issuecomment-6337544933
## Non-blocking request actions (#21486)
`scripts/http_request/hsrv.py PORT` serves `/fast`, `/slow?d=S`, `/big` and `/chunked` (`n` bytes at `rate` B/s,
deterministic bytes `(i*7+3)&0xFF`), `/post` (echoes length and byte sum), `/redirect` and `/hang`.
`templates/http_request_action/hr-common.yaml` (substitutions `name`, `bufsize`; per-board files `hr32.yaml` and
`hr66.yaml`, `-s name hr32base` on the command line for the base build; `hrota32.yaml` adds the `otaflash` action
for `otadrive.py`) has API actions `req_get`, `req_post`, `burst` (N runs of a `mode: parallel` script on one action),
`cancel` (`mode: single` script run twice, then `script.stop`) and `reboot_during`, and logs
`RESULT n status len sum took maxgap`, where maxgap is the longest main loop gap during the request (an
`interval: 1ms` lambda plus the time since its last pass, so a fully blocking request counts too). Drive with
`scripts/http_request/hrdrive.py IP http://HOST:PORT LABEL [https]` (`ONLY=case,case` and `ROUNDS=n` env; the
`cross` case runs two actions on one component). `burstonly.py IP URL N` checks concurrency against the server's
completion times, `reboottest.py IP URL` times `App.safe_reboot()` with requests in flight, `updcheck.py IP LABEL N`
runs N update checks over the API (for real device configs that use `update: platform: http_request`) and
`otadrive.py` triggers `ota.http_request.flash` (the API variable is `sum`; `md5` is a reserved variable name).
`execute_service` must be awaited on current aioesphomeapi or nothing is sent. Keep the ESP32 `bufsize` at 32 KB or
less: the action copies the body into a `std::string` while the buffer is still held, and 80 KB aborts with out of
memory on dev and on the PR alike. `http_request` refuses BK72xx and RTL87xx at validation.
## OTA request cases with basic auth (#21556)
`scripts/http_request/ota_auth/`: `ho-common.yaml` (API actions for `ota.http_request.flash` with `md5_url`, `md5`
and basic auth, `flash()` with no URL, an invalid URL, the `md5_computed()`/`md5_expected()` getters), `fwsrv.py`
(serves a www dir, `/auth/` needs `otauser:otapass`), `hodrive.py` (11 cases, reconnects after each good flash) and
`run.sh BUILD BOARD` (compiles from `TREE`, serial flash, serves that exact image; `TREE`, `P32` or `P66`, `SC` and `HOST_IP` in
the environment). On the D1 mini the authenticated MD5 read fails
with `Error reading MD5: -1` on dev too, and stored credentials carry over to the next flash on both builds.
Results: https://github.com/esphome/esphome/pull/21556#issuecomment-6381067561
@@ -1,12 +0,0 @@
# 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.
@@ -1,10 +0,0 @@
# Addressable LED strips (#21447, #21445)
- To exercise a failed strip allocation, use a classic ESP32 without PSRAM with `num_leds: 65535` and
`channel_colors: GRBW` (262 kB, bigger than any internal block). `num_leds` is uint16 in the drivers, larger
values wrap. On dev such a strip boot-loops the board.
- Never force allocation failures by hogging RAM instead: Wi-Fi then aborts in `operator new` or the loop task
trips the task watchdog.
- 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.
@@ -1,18 +0,0 @@
# modem
## PPPoS modem component with no modem attached (#6721)
A boot check on a classic ESP32 devkit with the modem UART pins left open. `templates/modem/modem-common.yaml` is
the package (`api:`, debug `loop_time` and `free` sensors, uptime, buttons for `modem.enable`, `modem.disable` and
`modem.send_at`, a 20 s alive log); `modemo.yaml` is the modem only build with `reboot_timeout: 2min` and the
component test config's `on_boot` block at `priority: -100` (earlier, `modem.send_at` runs before the modem's
`setup()` and logs `Modem DCE not ready`); `modemw.yaml` adds `wifi:` with `reboot_timeout: 0s` so the API stays
reachable. Expect `Modem not responding at 115200 baud` once per pass with each pass blocking the loop about 1 s,
the reboot at the configured timeout (`SW_CPU_RESET`), and a `modem.disable` with no modem answering to block
the loop about 37 s (`Failed to leave data mode`, then the radio off timeout) without tripping the 30 s watchdog
floor because the component feeds it in between. Drive the Wi-Fi build with
`scripts/modem/mdrive.py HOST LOGFILE list press:NAME wait:S` (plaintext API; prints sensor and text sensor
states, saves the device log). Before 8cc8df4a1f a modem only config with `api:` failed validation because a
config dependent `AUTO_LOAD` added `network` after the dependency check; an explicit `network:` block was the
workaround. Results: https://github.com/esphome/esphome/pull/6721#issuecomment-6347395159 and
https://github.com/esphome/esphome/pull/6721#issuecomment-6348520416
@@ -51,31 +51,3 @@ context rejects a CA that lacks a `keyUsage` extension (`CA cert does not includ
on the device accepts it, which is why the test CA carries `basicConstraints` and `keyUsage`. A broker kill shows as one
`Last esp-tls error: 0x8008` on every build, TLS or not. Results:
https://github.com/esphome/esphome/pull/14318#issuecomment-6311863827
## MAC suffix topics (#9315)
`scripts/mqtt/mac_suffix/run.sh X BUILD` compiles (from `TREE`) and flashes variant X (a defaults, b custom `topic_prefix`, c explicit topics,
d no suffix) of BUILD (`pr` or `base`) on an ESP32 and a D1 mini, records the broker with
`mosquitto_sub -F '@H:@M:@S r=%r %t %p'`, presses Restart through the `cmd_t` found in the discovery payloads, then
holds both chips in the bootloader for 40 s (`esptool --after no-reset chip-id`) so the broker sends the will; a
plain reset only gives "session taken over" and no will. The two boards' configs live in separate folders because
variants a to c share a `name` (the MAC suffix tells them apart), and the same name in one folder shares a build
directory. A D1 mini CH340 can garble the serial capture after an RTS reset, so read its topics from the broker.
`esphome logs --device MQTT` on a current tree needs paho-mqtt 2.x; an older venv with 1.6.1 fails, so use a venv
made from the tree's requirements.txt. A Restart press never delivered the shutdown message on any build tested.
## Shutdown message delivery (#21566)
`scripts/mqtt/shutdown/`: `sd-common.yaml` sets birth/will/shutdown payloads `hello`/`dead`/`bye` so the shutdown
message and the will cannot be confused, and takes `restart`, `disable` and `sleep` on `<name>/cmd`.
`sdrun.sh V N` (`TREE`, `P32` and `P66` in the environment) compiles and flashes the ESP32 and D1 mini, restarts each N times, disables MQTT once and deep sleeps the ESP32 three
times (never the D1 mini: without the GPIO16 to RST wire it never wakes); `match.py OUT` counts a `bye` within 5 s of
each command. Dev: ESP32 0/10 restarts, D1 mini 1 to 3/10. Put the broker address (`broker_ip`) in the secrets.yaml next to
the included package, and quote `"${name}/status"` inside flow mappings.
Results: https://github.com/esphome/esphome/pull/21566#issuecomment-6381448061
Retest at c9cf3c2813 (shutdown message sent at QoS 1, teardown waits for the broker's ack): 10/10 restarts on both
boards and 3/3 deep sleeps, against 1/10, 3/10 and 0/3 on base. An earlier 100 ms hold gave 3/10, 6/10 and 2/3, so
judge a delivery fix by counts over 10 or more restarts, never one or two presses.
Results: https://github.com/esphome/esphome/pull/21566#issuecomment-6382076613
@@ -4,10 +4,3 @@
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.
@@ -18,47 +18,3 @@ ends with `Error downloading image: -28679` (EAGAIN) after the transport timeout
and cut chunked cases and every later update logs `Image already being updated.`, so a baseline run needs
a reboot per group, the driver's 45 s cap per case, and an outer `timeout` that covers the whole list.
A case expected as `any` passes on `finished` or `error`, never on no outcome.
## PNG decode time limit (#21364, #21391)
The same server also serves any plain file in its www directory by name (404 for a missing file or a path
outside it). `scripts/online_image/make_big_pngs.py <www>` (after `make_images.py`) writes a 320x240 gradient (618 B, also as `ok.png` so the misbehaviour cases carry a
real multi-row PNG), a flat 640x480 PNG (1.6 KB for 307200 pixels), 231 KB of noise and a JPEG. The device is
`templates/online-image-dut.yaml` with `type: BINARY` on the main image (a 640x480 RGB565 does not fit a classic
ESP32 without PSRAM) and `debug` loop time and heap sensors at 2 s; the 256 byte buffer image stays RGB565, so do
not point big images at it (out of memory on every build). `scripts/online_image/pngdrive.py HOST KEY LOGFILE
BASEURL LABEL` (default case set `png`; `CASES=short` for the six case list) calls the actions, waits for the
finished or error line and reports the case time, the highest loop time and the lowest free heap. The per pass `online_image.image took a long time` values come from
the serial capture and only print on a new maximum, so read the first fetch of each image. The pass that decodes a
whole buffer is the decoder cost (before the change 510 ms gradient and 1980 ms flat, after it 77 and 140 ms); for
the noisy PNG the longest pass is the blocking 64 KB read on both builds (0.7 to 3.7 s). Alternate PR, base, PR
for a timing claim.
For a replacement PR, compare against the parent PR head, not dev. `CASES=noise` fetches the noisy PNG three times
(run it right after a boot, alternating builds); `CASES=end` runs flat and gradient as plain, `noclen_`, `chunked_`,
`half_` and `stall_` through the prefixed server cases below.
## JPEG decoded as it downloads (#21342)
`oi_server.py` serves prefixed cases on any file: `half_<file>` (first half, matching Content-Length),
`noclen_<file>` (close delimited), `chunked_<file>` (1 KB chunks), `stall_<file>` (a third, then the socket held
40 s). `scripts/online_image/make_jpegs.py <www>` writes noise, gradient, 12 KB EXIF and progressive JPEGs. Device:
`templates/online-image-dut.yaml` with `type: BINARY` on both entities and `buffer_size: 4096` on the second;
`CASES=jpeg scripts/online_image/pngdrive.py HOST KEY LOGFILE BASEURL LABEL` runs the JPEG list; every case set
prints case time, highest loop time and lowest free heap. Before the change a JPEG needs a contiguous block of its file size (233 KB never
allocates on a classic ESP32, and after a few failures 69 KB does not either until a reboot); after it the 64 KB
buffer stays 64 KB and 4 KB is enough for a baseline JPEG. The first pass still reads up to `buffer_size` in one
blocking read, so the 64 KB entity blocks 1.7 to 4 s and the 4 KB one 272 ms at most; judge the decode budget on
the small buffer entity. Already on dev: a JPEG without Content-Length (plain or chunked) ends with `Could not open
image for decoding: 4` then `Invalid type`.
## BMP and QOI decode time limit (#21392)
Use a wired board (`templates/online-image-s3-eth-dut.yaml`: Waveshare ESP32-S3-ETH, W5500, PSRAM, `type: RGB565`)
rather than a classic ESP32 on Wi-Fi: with a weak link the reads block up to the 4.5 s timeout and the per case loop
numbers are noise. `scripts/online_image/make_bmp_qoi.py <www>` writes 1 bit BMP 640x480, 8 and 24 bit BMP 320x240,
QOI 640x480 one colour (all runs) and checkerboard, QOI 320x240 gradient and noise. `pngdrive.py` with
`CASES=bmpqoi` runs each as plain, `noclen_`, `chunked_`, `half_` plus stalls. The `loop_time` sensor sits at 75
to 160 ms even for a 16x16 image, so for decode passes use `scripts/online_image/firstpass.py HOST KEY BASEURL
LABEL IMAGE...`: it reboots the device before each fetch and reports that fetch's `took a long time` maximum. A
`half_` file with matching Content-Length reports `download finished` with "not caching it" on dev too.
@@ -6,46 +6,3 @@ 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.
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
@@ -1,30 +0,0 @@
# remote_base / remote_receiver
## Loopback on one pin, no IR hardware (#21560 to #21563)
`templates/remote_base/`: `rb-common.yaml` (API action `tx_all`, a dumper registered from `on_boot` through
`register_dumper()` standing in for an external component), `rb-txscript.yaml` (14 `remote_transmitter.transmit_*`
frames with `tx <proto>` log markers), `rb32.tmpl` and `rb66.tmpl` (`@V@` is the build label).
`scripts/remote_base/run.sh LABEL B N` (`TREE`, `P32` or `P66`, `SC` in the environment) writes the run file from the
template, builds and flashes it from `TREE` (`esphome run --no-logs`), finds the IP and runs `rbdrive.py IP N`, which segments the API log by the
markers and prints what each sent frame decoded as.
- ESP32: `remote_transmitter` and two `remote_receiver`s on the same GPIO (`allow_other_uses`), carrier 100%, no
inversion. RMT reads its own output, every frame decodes. Second receiver `dump: [nec, raw]` shows raw runs only
where no primary matched.
- ESP8266: the transmitter sends with interrupts off, so a receiver on the same pin sees nothing. `softtx.hpp`
bit-bangs frames built with each protocol's `encode()` with interrupts on, and an `interval` sets the pin back to
OUTPUT after the receiver's setup. Bit-banged NEC decodes as NEC about 2 of 3 times (timing), on every build.
- Dish never decodes in loopback on dev either. Pronto matches every frame, so raw on `dump: all` never prints.
- API log lines can drop under bursts; rerun with more rounds before calling a shortfall.
- `register_dumper()` returns nothing, so the config logs `ext dumper register called`, not whether it stuck. On dev
the list has a fixed size and a dumper beyond it is dropped with `No dumper slot` (ERROR); judge by that line and by
`ext dumper saw` counts in the `rbdrive.py` table, which only appear when the dumper is really registered.
`rbdrive.py` exits 1 when the external dumper saw no frame, so a build that rejects the registration fails the
drive; set `EXPECT_REGISTER=1` on `run.sh` to also fail the run on any `No dumper slot` line.
Results: https://github.com/esphome/esphome/pull/21563#issuecomment-6381304387
Retest of the moved stack with 5 rounds per build: https://github.com/esphome/esphome/pull/21563#issuecomment-6382075726.
A D1 mini CH340 sometimes fails the 460800 baud upload; esphome retries at 115200 by itself, but a runner that reads
only the last line sees "Failed to upload" first, so rerun before blaming the build.
@@ -1,19 +0,0 @@
# Simulated UART sensors on a classic ESP32 (#21449, #21446)
No sensor needed. `templates/uart_sim/sim.hpp` (included with `esphome: includes:`) has frame builders for wts01,
ds1603l, sm300d2 and ufm01, `sim::loopback(id(uart))` (ESP-IDF `uart_set_loop_back` on the component's own UART),
`sim::send()` that logs the bytes, and `sim::probe`, a SEN0465 responder polled from a 10 ms interval. The run files
`fra.yaml`, `frb.yaml` and `frc.yaml` set the name and include `fr-common.yaml` plus their `fr*-parts.yaml` as
packages; copy them with a different name (`frabase` and so on) for the base build.
- Push-style sensors: put the component on a UART, switch it to loopback in `on_boot`, and inject frames from
template buttons (`fra-parts.yaml`, `frb-parts.yaml`). ufm01 enters its active stream by itself when a 1 s
interval streams frames during its 2 s startup wait.
- Request/response sensors: cross-wire two UARTs through the GPIO matrix (UART1 tx 25 rx 26, UART2 tx 26 rx 25,
`allow_other_uses: true` on all four pins); the second UART runs the simulated device (`frc-parts.yaml`).
A select sets the probe's misbehaviour (tail, FF tail, silent, split, wrong gas).
- Polled readers: run `update()` from a script and log `micros()` around it to measure blocking
(sm300d2 on dev blocks about 104 ms on an empty buffer).
- The logger stays on UART0, so three builds cover five components. Drive with `scripts/uart_sim/frdrive.py HOST
LOG press:NAME sel:NAME=OPT num:NAME=V wait:S`, or `scripts/uart_sim/run.sh NAME TREE SECONDS OPS...` (build
and flash from TREE with `esphome run --no-logs`, capture, drive; `PORT` and `SC` in the environment).
@@ -37,44 +37,3 @@ 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.
@@ -1,36 +0,0 @@
# 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).
- 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.
@@ -1,221 +0,0 @@
"""Pull the store_yaml blob off a device over the native API (plaintext or Noise) and unpack it.
usage: syrecover.py HOST KEY OUTDIR [ORIGDIR] (KEY of - means a plaintext API)
Prints the capability flag, chunk count, advertised and received sizes, encoding, the envelope's files, and
when ORIGDIR is given compares each recovered file with ORIGDIR/<path>.
Run with PYTHONPATH pointing at the esphome tree that has store_yaml (for unpack_envelope). Needs Python 3.14
(compression.zstd) or the zstandard package.
"""
import asyncio
from pathlib import Path
import sys
import time
from aioesphomeapi import api_pb2
from aioesphomeapi._frame_helper.noise import APINoiseFrameHelper
from aioesphomeapi._frame_helper.plain_text import APIPlaintextFrameHelper
from aioesphomeapi.connection import APIConnection, ConnectionParams
from aioesphomeapi.zeroconf import ZeroconfManager
from esphome.components.store_yaml import unpack_envelope
try:
from compression import zstd
except ImportError:
try:
import zstandard as zstd
except ImportError:
sys.exit("needs Python 3.14 (compression.zstd) or the zstandard package")
HOST, KEY, OUT = sys.argv[1], sys.argv[2], Path(sys.argv[3])
ORIG = Path(sys.argv[4]) if len(sys.argv) > 4 else None
HELLO, HELLO_RESP, CONNECT, CONNECT_RESP = 1, 2, 3, 4
DISCONNECT_REQ = 5
FATAL = -1 # queued by report_fatal_error so a waiting expect() stops at once
CAPS_REQ, CAPS_RESP = 149, 150
GET_YAML_REQ, GET_YAML_RESP = 161, 162
def decode_varint(buf: bytes, pos: int) -> tuple[int, int]:
value = shift = 0
while True:
b = buf[pos]
pos += 1
value |= (b & 0x7F) << shift
if not b & 0x80:
return value, pos
shift += 7
def fields(payload: bytes) -> dict[int, list]:
out: dict[int, list] = {}
pos = 0
while pos < len(payload):
key, pos = decode_varint(payload, pos)
fnum, wt = key >> 3, key & 7
if wt == 0:
v, pos = decode_varint(payload, pos)
elif wt == 2:
ln, pos = decode_varint(payload, pos)
v = payload[pos : pos + ln]
pos += ln
elif wt == 5:
v = payload[pos : pos + 4]
pos += 4
else:
raise ValueError(f"wire type {wt}")
out.setdefault(fnum, []).append(v)
return out
async def main() -> None:
loop = asyncio.get_running_loop()
queue: asyncio.Queue[tuple[int, bytes]] = asyncio.Queue()
errors: list[Exception] = []
class Shim(APIConnection):
"""Only the two callbacks the frame helper uses; the real connection logic is bypassed."""
def process_packet(self, msg_type_proto, data) -> None:
queue.put_nowait((msg_type_proto, bytes(data)))
def report_fatal_error(self, err: Exception) -> None:
errors.append(err)
queue.put_nowait((FATAL, b""))
params = ConnectionParams(
addresses=[HOST],
port=6053,
password=None,
client_info="syrecover",
keepalive=15,
zeroconf_manager=ZeroconfManager(),
noise_psk=None if KEY == "-" else KEY,
expected_name=None,
expected_mac=None,
timezone=None,
provide_time=True,
)
shim = Shim(params, None, False, HOST)
if KEY == "-":
helper = APIPlaintextFrameHelper(
connection=shim, client_info="syrecover", log_name=HOST
)
else:
helper = APINoiseFrameHelper(
connection=shim,
noise_psk=KEY,
expected_name=None,
expected_mac=None,
client_info="syrecover",
log_name=HOST,
)
await loop.create_connection(lambda: helper, HOST, 6053)
try:
await asyncio.wait_for(helper.ready_future, 10)
except Exception as exc: # noqa: BLE001
sys.exit(f"handshake failed: {exc!r} {errors}")
print(f"transport {'plaintext' if KEY == '-' else 'noise'}: handshake done")
async def expect(msg_type: int, timeout: float = 10) -> bytes:
while True:
t, d = await asyncio.wait_for(queue.get(), timeout)
if t == msg_type:
return d
if t == FATAL:
sys.exit(
f"transport error while waiting for message {msg_type}: {errors}"
)
if t == DISCONNECT_REQ:
sys.exit(
f"device closed the connection while waiting for message {msg_type}"
)
print(f"skipping message type {t} while waiting for {msg_type}")
hello = api_pb2.HelloRequest(
client_info="syrecover", api_version_major=1, api_version_minor=10
)
helper.write_packets([(HELLO, hello.SerializeToString())], False)
await expect(HELLO_RESP)
# Sent like the client library does; a device without a password never answers it
helper.write_packets(
[(CONNECT, api_pb2.AuthenticationRequest().SerializeToString())], False
)
helper.write_packets(
[(CAPS_REQ, api_pb2.DeviceCapabilitiesRequest().SerializeToString())], False
)
caps = fields(await expect(CAPS_RESP))
supported = None
if 7 in caps:
supported = fields(caps[7][0]).get(1) == [1]
print(f"capabilities: store_yaml field present={7 in caps} supported={supported}")
t0 = time.monotonic()
helper.write_packets([(GET_YAML_REQ, b"")], False)
chunks: list[bytes] = []
total = encoding = None
done = False
while not done:
f = fields(await expect(GET_YAML_RESP, 20))
if 1 in f:
chunks.append(f[1][0])
done = f.get(2) == [1]
if 3 in f:
total = f[3][0]
if 4 in f:
encoding = f[4][0].decode()
dt = time.monotonic() - t0
compressed = b"".join(chunks)
print(f"chunks {len(chunks)} sizes {[len(c) for c in chunks]}")
print(
f"received {len(compressed)} bytes, advertised {total}, encoding {encoding!r}, {dt:.2f} s"
)
# a second request right after: the device must answer again, not stay stuck
helper.write_packets([(GET_YAML_REQ, b"")], False)
again = 0
done = False
while not done:
f = fields(await expect(GET_YAML_RESP, 20))
again += len(f.get(1, [b""])[0])
done = f.get(2) == [1]
print(f"second request: {again} bytes")
helper.close()
if errors:
sys.exit(f"transport errors: {errors}")
if encoding != "zstd":
sys.exit(f"unexpected encoding {encoding!r}, expected 'zstd'")
if total is not None and len(compressed) != total:
sys.exit(f"received {len(compressed)} bytes but the device advertised {total}")
if again != len(compressed):
sys.exit(
f"the second request returned {again} bytes, the first {len(compressed)}"
)
envelope = zstd.decompress(compressed)
files = unpack_envelope(envelope)
print(
f"envelope {len(envelope)} bytes, {len(files)} files, ratio {len(compressed) / len(envelope):.2f}"
)
OUT.mkdir(parents=True, exist_ok=True)
for rel, content in files.items():
target = OUT / rel.replace("../", "up_/")
if not target.resolve().is_relative_to(OUT.resolve()):
print("skipping a path outside the output directory:", rel)
continue
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(content)
note = ""
if ORIG is not None:
orig = (ORIG / rel).resolve()
if orig.exists():
note = (
"IDENTICAL to original"
if orig.read_bytes() == content
else f"DIFFERS from original ({orig.stat().st_size} bytes)"
)
else:
note = "no original"
print(f" {rel}: {len(content)} bytes {note}")
asyncio.run(main())
@@ -1,90 +0,0 @@
"""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)
@@ -1,100 +0,0 @@
"""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])
)
)
)
@@ -1,17 +0,0 @@
#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);
}
@@ -1,36 +0,0 @@
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"
@@ -1,44 +0,0 @@
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
@@ -1,31 +0,0 @@
#!/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
@@ -1,44 +0,0 @@
"""Run the burst action once and print each queued request as it completes.
Usage: burstonly.py IP URL N"""
import asyncio
import re
import sys
import time
import aioesphomeapi
IP, URL, N = sys.argv[1], sys.argv[2], int(sys.argv[3])
async def main():
c = aioesphomeapi.APIClient(IP, 6053, None)
await c.connect(login=True)
_, svcs = await c.list_entities_services()
s = {x.name: x for x in svcs}
t0 = time.monotonic()
done = []
errors = []
def on_log(m):
t = re.sub(r"\x1b\[[0-9;]*m", "", m.message.decode(errors="replace"))
if "BURSTRESP status=200 " in t:
done.append(t)
elif "BURSTRESP" in t or "BURSTERR" in t:
errors.append(t)
if "hrt" in t or "Too many" in t:
print(f"{time.monotonic() - t0:6.2f} {t[:120]}", flush=True)
c.subscribe_logs(on_log, log_level=aioesphomeapi.LogLevel.LOG_LEVEL_INFO)
await asyncio.sleep(1)
t0 = time.monotonic()
await c.execute_service(s["burst"], {"url": URL, "count": N})
await asyncio.sleep(14)
await c.disconnect()
print(
f"{len(done)} of {N} burst requests answered, {len(errors)} failed", flush=True
)
return 0 if len(done) >= N else 1
sys.exit(asyncio.run(main()))
@@ -1,159 +0,0 @@
"""Drive the http_request action test device over the API and collect its hrt log lines.
Usage: hrdrive.py DEVICE_IP SERVER_BASE LABEL [https]"""
import asyncio
import os
import re
import sys
import time
import aioesphomeapi
IP, BASE, LABEL = sys.argv[1], sys.argv[2], sys.argv[3]
HTTPS = len(sys.argv) > 4
CASES = [
("get", "fast", BASE + "/fast"),
("get", "slow2s", BASE + "/slow?d=2"),
("get", "big70k", BASE + "/big?n=70000&rate=20000"),
("get", "chunked70k", BASE + "/chunked?n=70000&rate=20000"),
("post", "post500", BASE + "/post"),
("get", "redirect", BASE + "/redirect"),
("get", "hang", BASE + "/hang?d=20"),
("get", "unreachable", "http://192.0.2.1:81/"),
]
if HTTPS:
CASES += [
("get", "https_get", "https://www.howsmyssl.com/a/check"),
("post", "https_post", "https://httpbin.org/post"),
]
ONLY = os.environ.get("ONLY")
if ONLY:
CASES = [c for c in CASES if c[1] in ONLY.split(",")]
ROUNDS = int(os.environ.get("ROUNDS", "2"))
# cases whose request must fail (past the 8 s timeout, or an address that never answers)
EXPECT_ERROR = {"hang", "unreachable"}
EXTRAS = not ONLY
timeouts: list[str] = []
mismatches: list[str] = []
async def main() -> int:
c = aioesphomeapi.APIClient(IP, 6053, None)
await c.connect(login=True)
_, services = await c.list_entities_services()
svc = {s.name: s for s in services}
lines = []
def on_log(m):
t = (
m.message.decode(errors="replace")
if isinstance(m.message, bytes)
else m.message
)
t = re.sub(r"\x1b\[[0-9;]*m", "", t)
if (
"[hrt" in t
or "http_request" in t
or "Script" in t
or "already running" in t
):
lines.append(t)
print(f"{LABEL} {t}", flush=True)
def bad_burst(ln: str) -> bool:
return "BURSTERR" in ln or ("BURSTRESP" in ln and "status=200 " not in ln)
def mismatch(what: str, why: str) -> None:
print(f"{LABEL} {what} MISMATCH: {why}", flush=True)
mismatches.append(what)
async def wait_until(done, secs: float, what: str) -> None:
"""Poll done() until it holds; print a TIMEOUT marker when the deadline passes first."""
end = time.monotonic() + secs
while not done():
if time.monotonic() >= end:
print(f"{LABEL} {what} TIMEOUT", flush=True)
timeouts.append(what)
return
await asyncio.sleep(0.2)
c.subscribe_logs(on_log, log_level=aioesphomeapi.LogLevel.LOG_LEVEL_DEBUG)
await asyncio.sleep(1)
for rnd in range(1, ROUNDS + 1):
for kind, name, url in CASES:
n0 = len(lines)
print(f"{LABEL} == {name} round {rnd}", flush=True)
if kind == "get":
await c.execute_service(svc["req_get"], {"url": url})
else:
await c.execute_service(
svc["req_post"], {"url": url, "payload": "x" * 500}
)
await wait_until(
lambda n0=n0: any("RESULT" in ln for ln in lines[n0:]),
40,
f"{name} round {rnd}",
)
result = next((ln for ln in lines[n0:] if "RESULT" in ln), None)
if result is not None and (
("status=200 " not in result)
if name not in EXPECT_ERROR
else (" error " not in result)
):
mismatch(f"{name} round {rnd}", result)
await asyncio.sleep(1.5)
if not EXTRAS:
continue
print(f"{LABEL} == burst round {rnd}", flush=True)
n0 = len(lines)
await c.execute_service(svc["burst"], {"url": BASE + "/slow?d=1", "count": 6})
await wait_until(
lambda n0=n0: (
sum("BURSTRESP" in ln or "BURSTERR" in ln for ln in lines[n0:]) >= 6
),
30,
f"burst round {rnd}",
)
if any(bad_burst(ln) for ln in lines[n0:]):
mismatch(f"burst round {rnd}", "a burst request failed or was not 200")
await asyncio.sleep(2)
print(f"{LABEL} == cancel round {rnd}", flush=True)
n0 = len(lines)
await c.execute_service(svc["cancel"], {"url": BASE + "/slow?d=2"})
await asyncio.sleep(9)
if not any("CANCEL stopped running=0" in ln for ln in lines[n0:]):
mismatch(
f"cancel round {rnd}", "script.stop did not leave the script stopped"
)
print(f"{LABEL} == cross round {rnd}", flush=True)
n0 = len(lines)
await c.execute_service(svc["req_get"], {"url": BASE + "/slow?d=2&tag=cross"})
await c.execute_service(
svc["burst"], {"url": BASE + "/slow?d=1&tag=crossburst", "count": 3}
)
await wait_until(
lambda n0=n0: (
sum("BURSTRESP" in ln or "BURSTERR" in ln for ln in lines[n0:]) >= 3
and any("RESULT" in ln for ln in lines[n0:])
),
30,
f"cross round {rnd}",
)
if any(
bad_burst(ln) or ("RESULT" in ln and "status=200 " not in ln)
for ln in lines[n0:]
):
mismatch(f"cross round {rnd}", "a request failed")
await asyncio.sleep(2)
await c.disconnect()
if timeouts:
print(f"{LABEL} TIMEOUTS: {', '.join(timeouts)}", flush=True)
if mismatches:
print(f"{LABEL} MISMATCHES: {', '.join(mismatches)}", flush=True)
return 1 if timeouts or mismatches else 0
sys.exit(asyncio.run(main()))
@@ -1,78 +0,0 @@
"""Test server for http_request actions: deterministic bodies, slow and chunked responses."""
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import sys
import time
from urllib.parse import parse_qs, urlparse
def body_bytes(n):
return bytes((i * 7 + 3) & 0xFF for i in range(n))
class H(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, fmt, *a):
sys.stdout.write(f"{time.time():.3f} {self.client_address[0]} {fmt % a}\n")
sys.stdout.flush()
def _q(self):
u = urlparse(self.path)
return u.path, {k: v[0] for k, v in parse_qs(u.query).items()}
def _send(self, data, code=200, ctype="application/octet-stream"):
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_POST(self):
n = int(self.headers.get("Content-Length", 0))
got = self.rfile.read(n)
self._send(
b"posted %d %d" % (len(got), sum(got) & 0xFFFFFFFF), ctype="text/plain"
)
def do_GET(self):
path, q = self._q()
if path == "/fast":
self._send(b"hello", ctype="text/plain")
elif path == "/slow":
time.sleep(float(q.get("d", "2")))
self._send(b"slow ok", ctype="text/plain")
elif path == "/redirect":
self.send_response(302)
self.send_header("Location", "/fast")
self.send_header("Content-Length", "0")
self.end_headers()
elif path == "/hang":
time.sleep(float(q.get("d", "30")))
elif path in ("/big", "/chunked"):
n = int(q.get("n", "70000"))
rate = float(q.get("rate", "20000"))
data = body_bytes(n)
self.send_response(200)
self.send_header("Content-Type", "application/octet-stream")
if path == "/big":
self.send_header("Content-Length", str(n))
else:
self.send_header("Transfer-Encoding", "chunked")
self.end_headers()
step = 1000
for i in range(0, n, step):
part = data[i : i + step]
if path == "/big":
self.wfile.write(part)
else:
self.wfile.write(b"%x\r\n" % len(part) + part + b"\r\n")
self.wfile.flush()
time.sleep(len(part) / rate)
if path == "/chunked":
self.wfile.write(b"0\r\n\r\n")
else:
self._send(b"nope", 404)
ThreadingHTTPServer(("0.0.0.0", int(sys.argv[1])), H).serve_forever()
@@ -1,58 +0,0 @@
"""Serve update manifests: stable.json, beta.json and slow.json (answered after a delay); logs every request."""
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import sys
import time
PORT = int(sys.argv[1])
DELAY = float(sys.argv[2]) if len(sys.argv) > 2 else 4.0
def manifest(name: str, version: str) -> bytes:
builds = [
{
"chipFamily": fam,
"ota": {
"path": f"/{name}.bin",
"md5": "d41d8cd98f00b204e9800998ecf8427e",
"summary": f"{name} channel",
},
}
for fam in ("ESP8266", "ESP32")
]
return json.dumps(
{"name": f"Bench {name}", "version": version, "builds": builds}
).encode()
DOCS = {
"/stable.json": manifest("stable", "1.0.0"),
"/beta.json": manifest("beta", "2.0.0-beta1"),
"/slow.json": manifest("slow", "3.0.0-slow"),
}
class Handler(BaseHTTPRequestHandler):
def do_GET(self) -> None: # noqa: N802
body = DOCS.get(self.path)
print(
f"{time.strftime('%H:%M:%S')} {self.client_address[0]} GET {self.path} -> {404 if body is None else 200}",
flush=True,
)
if body is None:
self.send_error(404)
return
if self.path == "/slow.json":
time.sleep(DELAY)
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args) -> None: # quiet default log
return
ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever()
@@ -1,10 +0,0 @@
esphome:
name: ho32base
esp32:
board: esp32dev
framework:
type: esp-idf
packages:
common: !include ../../ho-common.yaml
@@ -1,11 +0,0 @@
esphome:
name: ho66base
esp8266:
board: d1_mini
packages:
common: !include ../../ho-common.yaml
http_request:
verify_ssl: false
@@ -1,32 +0,0 @@
"""Serve a www dir for ota.http_request tests; /auth/ needs basic auth otauser:otapass.
Usage: fwsrv.py WWW PORT"""
import base64
import functools
import http.server
import sys
WWW, PORT = sys.argv[1], int(sys.argv[2])
GOOD = "Basic " + base64.b64encode(b"otauser:otapass").decode()
class H(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path.startswith("/auth/") and self.headers.get("Authorization") != GOOD:
self.send_response(401)
self.send_header("WWW-Authenticate", 'Basic realm="ota"')
self.send_header("Content-Length", "0")
self.end_headers()
return
super().do_GET()
def log_message(self, fmt, *args):
print(
f"{self.address_string()} auth={'Authorization' in self.headers} {fmt % args}",
flush=True,
)
http.server.ThreadingHTTPServer(
("0.0.0.0", PORT), functools.partial(H, directory=WWW)
).serve_forever()
@@ -1,60 +0,0 @@
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
power_save_mode: none
logger:
level: DEBUG
api:
reboot_timeout: 0s
actions:
- action: fl_md5url
variables: {url: string, md5url: string}
then:
- ota.http_request.flash:
url: !lambda return url;
md5_url: !lambda return md5url;
- action: fl_md5
variables: {url: string, sum: string}
then:
- ota.http_request.flash:
url: !lambda return url;
md5: !lambda return sum;
- action: fl_auth
variables: {url: string, md5url: string, user: string, pw: string}
then:
- ota.http_request.flash:
url: !lambda return url;
md5_url: !lambda return md5url;
username: !lambda return user;
password: !lambda return pw;
- action: fl_nourl
then:
- lambda: id(hota).flash();
- action: fl_badurl
then:
- lambda: |-
id(hota).set_url("not a url");
id(hota).flash();
- action: getters
then:
- lambda: |-
ESP_LOGI("hot", "getters computed='%s' expected='%s'", id(hota).md5_computed().c_str(),
id(hota).md5_expected().c_str());
esphome:
on_boot:
priority: -100
then:
- lambda: |-
ESP_LOGI("hot", "boot getters computed='%s' expected='%s'", id(hota).md5_computed().c_str(),
id(hota).md5_expected().c_str());
http_request:
timeout: 10s
ota:
- platform: esphome
- platform: http_request
id: hota
@@ -1,142 +0,0 @@
"""Drive the ota.http_request cases over the API.
Usage: hodrive.py IP BASEURL MD5FILE (BASEURL serves fw.bin, fw.md5, bad.md5, auth/fw.bin, auth/fw.md5)"""
import asyncio
import pathlib
import re
import sys
import time
import aioesphomeapi
if len(sys.argv) != 4:
sys.exit(__doc__)
IP, BASE = sys.argv[1:3]
SUM = pathlib.Path(sys.argv[3]).read_text(encoding="utf-8").strip()
T0 = time.monotonic()
lines: list[str] = []
failed: list[str] = []
def out(s: str) -> None:
print(f"{time.monotonic() - T0:7.2f} {s}", flush=True)
async def connect() -> tuple[aioesphomeapi.APIClient, dict]:
last: Exception | None = None
for _ in range(90):
c = aioesphomeapi.APIClient(IP, 6053, None)
try:
await c.connect(login=True)
except (
aioesphomeapi.InvalidAuthAPIError,
aioesphomeapi.InvalidEncryptionKeyAPIError,
aioesphomeapi.RequiresEncryptionAPIError,
):
raise # a key or password problem never fixes itself
except Exception as exc: # noqa: BLE001
last = exc
await asyncio.sleep(2)
continue
i = await c.device_info()
out(f"connected {i.name} {i.compilation_time}")
_, svcs = await c.list_entities_services()
def on_log(m):
t = re.sub(r"\x1b\[[0-9;]*m", "", m.message.decode(errors="replace"))
if re.search(r"\[hot|http_request|ota|OTA|MD5|md5", t):
lines.append(t)
out(t[:170])
c.subscribe_logs(on_log, log_level=aioesphomeapi.LogLevel.LOG_LEVEL_DEBUG)
return c, {x.name: x for x in svcs}
raise SystemExit(f"device never came back (last error {last!r})")
async def case(c, s, name, args, want, timeout=60.0):
out(f"=== {name} {args} (want {want})")
start = len(lines)
await c.execute_service(s[name], args)
end = time.monotonic() + timeout
while time.monotonic() < end:
if any(re.search(want, x) for x in lines[start:]):
out(f"RESULT {name} PASS")
return True
await asyncio.sleep(0.2)
out(f"RESULT {name} FAIL (no '{want}')")
failed.append(name)
return False
async def flash_ok(c, s, name, args):
"""A good flash: wait for the device to drop and come back."""
out(f"=== {name} {args} (want reboot)")
start = len(lines)
await c.execute_service(s[name], args)
end = time.monotonic() + 120
while (
time.monotonic() < end
and c._connection is not None
and c._connection.is_connected
): # noqa: SLF001
await asyncio.sleep(0.5)
# a good flash needs both the device's own success line and the connection dropping for the reboot
dropped = c._connection is None or not c._connection.is_connected # noqa: SLF001
logged = any(
re.search(r"(?i)update complete|rebooting|successful", x) for x in lines[start:]
)
if not dropped:
out(f"{name}: the device never dropped the connection within 120 s")
ok = logged and dropped
await c.disconnect()
await asyncio.sleep(5)
c, s = await connect()
out(f"RESULT {name} {'PASS' if ok else 'FAIL'}")
if not ok:
failed.append(name)
return c, s
async def main():
c, s = await connect()
u, m = f"{BASE}/fw.bin", f"{BASE}/fw.md5"
await case(c, s, "getters", {}, r"computed='' expected=''")
await case(c, s, "fl_nourl", {}, r"URL not set")
await case(c, s, "fl_badurl", {}, r"URL not set")
await case(c, s, "getters", {}, r"computed='' expected=''")
await case(c, s, "fl_md5", {"url": u, "sum": "0" * 32}, r"MD5 mismatch")
await case(c, s, "getters", {}, r"getters computed=")
await case(
c,
s,
"fl_auth",
{
"url": f"{BASE}/auth/fw.bin",
"md5url": f"{BASE}/auth/fw.md5",
"user": "otauser",
"pw": "wrong",
},
r"HTTP Request failed; URL: \S*/auth/fw\.md5; Code: 401",
)
c, s = await flash_ok(
c,
s,
"fl_auth",
{
"url": f"{BASE}/auth/fw.bin",
"md5url": f"{BASE}/auth/fw.md5",
"user": "otauser",
"pw": "otapass",
},
)
c, s = await flash_ok(c, s, "fl_md5url", {"url": u, "md5url": m})
c, s = await flash_ok(c, s, "fl_md5", {"url": u, "sum": SUM})
await case(c, s, "getters", {}, r"computed='' expected=''")
await c.disconnect()
out(
f"SUMMARY {'all cases passed' if not failed else 'FAILED: ' + ', '.join(failed)}"
)
return 1 if failed else 0
sys.exit(asyncio.run(main()))
@@ -1,10 +0,0 @@
esphome:
name: ho32pr
esp32:
board: esp32dev
framework:
type: esp-idf
packages:
common: !include ../../ho-common.yaml
@@ -1,11 +0,0 @@
esphome:
name: ho66pr
esp8266:
board: d1_mini
packages:
common: !include ../../ho-common.yaml
http_request:
verify_ssl: false
@@ -1,30 +0,0 @@
#!/bin/bash
# run.sh BUILD(pr|base) BOARD(32|66) : serial flash ho<BOARD><BUILD>, serve its own image, drive the cases
# Copy this directory to a scratch directory (secrets.yaml next to ho-common.yaml) and run it there.
# env: TREE (esphome checkout for BUILD), P32 or P66 (serial port of the board), SC (path to serial_capture.py),
# HOST_IP (this host's address as the device reaches it), PY (checkout python)
D=$(cd "$(dirname "$0")" && pwd); V=$1; B=$2; N=ho$B$V; T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}
SC=${SC:?set SC}; HOST=${HOST_IP:?set HOST_IP}
if [ "$B" = 32 ]; then P=${P32:?set P32}; else P=${P66:?set P66}; fi
OUT=$D/out-$V-$B; rm -rf "$OUT"; mkdir -p "$OUT"
pkill -f "[s]erial_capture.py $P"
(cd "$T" && $PY -m esphome compile "$D/$V/$B/$N.yaml" > "$OUT/compile.log" 2>&1) || { echo "compile failed"; exit 1; }
(cd "$T" && $PY -m esphome upload "$D/$V/$B/$N.yaml" --device "$P" > "$OUT/upload.log" 2>&1) || { echo "upload failed"; exit 1; }
# the exact image of this config, just compiled, never one found elsewhere
if [ "$B" = 32 ]; then IMG=$D/$V/$B/.esphome/build/$N/build/firmware.ota.bin
else IMG=$D/$V/$B/.esphome/build/$N/.pioenvs/$N/firmware.bin; fi
[ -f "$IMG" ] || { echo "no image for $N at $IMG"; exit 1; }
echo "image $IMG"
W=$OUT/www; mkdir -p "$W/auth"; cp "$IMG" "$W/fw.bin"; cp "$IMG" "$W/auth/fw.bin"
$PY -c "import hashlib,sys;print(hashlib.md5(open(sys.argv[1],'rb').read()).hexdigest())" "$IMG" > "$W/fw.md5"
cp "$W/fw.md5" "$W/auth/fw.md5"; echo 00000000000000000000000000000000 > "$W/bad.md5"
$PY "$SC" "$P" 400 "$OUT/serial.txt" --reset > /dev/null 2>&1 & CAP=$!
trap 'kill $CAP $SRV 2>/dev/null' EXIT
pkill -f "[f]wsrv.py"; $PY "$D/fwsrv.py" "$W" 8093 > "$OUT/server.txt" 2>&1 & SRV=$!
for i in $(seq 60); do IP=$(grep -a -o 'IP Address: [0-9.]*' "$OUT/serial.txt" | tail -1 | cut -d' ' -f3); [ -z "$IP" ] && IP=$(python3 -c "import socket;print(socket.gethostbyname('$N.local'))" 2>/dev/null); [ -n "$IP" ] && break; sleep 2; done
[ -n "$IP" ] || { echo "device not found"; exit 1; }
echo "device up"
$PY "$D/hodrive.py" "$IP" "http://$HOST:8093" "$W/fw.md5" > "$OUT/drive.txt" 2>&1; RC=$?
kill $SRV; pkill -f "[s]erial_capture.py $P"
grep -E 'RESULT|SUMMARY|never came back' "$OUT/drive.txt"; echo "server requests: $(grep -c . "$OUT/server.txt")"
exit $RC
@@ -1,74 +0,0 @@
"""Trigger ota.http_request.flash over the API, optionally during a burst of action requests.
Usage: otadrive.py IP FWURL MD5 BASE [burst]"""
import asyncio
import contextlib
import re
import sys
import time
import aioesphomeapi
IP, FW, SUM, BASE = sys.argv[1:5]
BURST = len(sys.argv) > 5
async def main():
c = aioesphomeapi.APIClient(IP, 6053, None)
await c.connect(login=True)
i = await c.device_info()
print("before:", i.name, i.compilation_time, flush=True)
_, svcs = await c.list_entities_services()
s = {x.name: x for x in svcs}
t0 = time.monotonic()
seen: list[str] = []
def on_log(m):
t = re.sub(r"\x1b\[[0-9;]*m", "", m.message.decode(errors="replace"))
seen.append(t)
if re.search(r"hrt|http_request|ota|OTA|Too many", t):
print(f"{time.monotonic() - t0:7.2f} {t[:170]}", flush=True)
c.subscribe_logs(on_log, log_level=aioesphomeapi.LogLevel.LOG_LEVEL_INFO)
await asyncio.sleep(1)
if BURST:
await c.execute_service(s["burst"], {"url": BASE + "/slow?d=1", "count": 6})
await asyncio.sleep(0.5)
await c.execute_service(s["otaflash"], {"url": FW, "sum": SUM})
end = time.monotonic() + 45
while (
time.monotonic() < end
and c._connection is not None # noqa: SLF001
and c._connection.is_connected # noqa: SLF001
):
await asyncio.sleep(0.5)
dropped = c._connection is None or not c._connection.is_connected # noqa: SLF001
with contextlib.suppress(Exception):
await c.disconnect()
for _ in range(30):
try:
c2 = aioesphomeapi.APIClient(IP, 6053, None)
await c2.connect(login=True)
i = await c2.device_info()
print("after:", i.name, i.compilation_time, flush=True)
await c2.disconnect()
break
except Exception: # noqa: BLE001
await asyncio.sleep(2)
else:
print("RESULT FAIL: not reachable after the flash", flush=True)
return 1
if not dropped:
print("RESULT FAIL: the device never rebooted", flush=True)
return 1
if any("OTAFLASH returned" in t for t in seen):
print("RESULT FAIL: the flash action returned, the update failed", flush=True)
return 1
if not any(re.search(r"(?i)update complete|rebooting|successful", t) for t in seen):
print("RESULT FAIL: no update complete line before the reboot", flush=True)
return 1
print("RESULT PASS", flush=True)
return 0
sys.exit(asyncio.run(main()))
@@ -1,68 +0,0 @@
"""Call reboot_during (a slow request in flight, another waiting, then App.safe_reboot) and time the reboot.
Usage: reboottest.py IP URL"""
import asyncio
import contextlib
import re
import sys
import time
import aioesphomeapi
IP, URL = sys.argv[1], sys.argv[2]
async def main():
c = aioesphomeapi.APIClient(IP, 6053, None)
await c.connect(login=True)
_, svcs = await c.list_entities_services()
s = {x.name: x for x in svcs}
t0 = time.monotonic()
def on_log(m):
t = re.sub(r"\x1b\[[0-9;]*m", "", m.message.decode(errors="replace"))
if re.search(
r"hrt|http_request|safe_mode|shutdown|Rebooting|reboot", t, re.IGNORECASE
):
print(f"{time.monotonic() - t0:7.2f} {t[:150]}", flush=True)
c.subscribe_logs(on_log, log_level=aioesphomeapi.LogLevel.LOG_LEVEL_DEBUG)
await asyncio.sleep(1)
t0 = time.monotonic()
await c.execute_service(s["reboot_during"], {"url": URL})
dropped = False
while time.monotonic() - t0 < 30:
try:
await asyncio.wait_for(c.device_info(), 1.0)
await asyncio.sleep(0.2)
except TimeoutError:
continue # a slow reply is not a reboot; only a closed connection counts
except Exception: # noqa: BLE001
dropped = True
print(f"{time.monotonic() - t0:7.2f} API connection gone", flush=True)
break
with contextlib.suppress(Exception):
await c.disconnect()
if not dropped:
print(f"{time.monotonic() - t0:7.2f} NO REBOOT within 30 s", flush=True)
return 1
last: Exception | None = None
for _ in range(60):
try:
c2 = aioesphomeapi.APIClient(IP, 6053, None)
await asyncio.wait_for(c2.connect(login=True), 3)
i = await c2.device_info()
print(f"{time.monotonic() - t0:7.2f} back: {i.name}", flush=True)
await c2.disconnect()
return 0
except Exception as exc: # noqa: BLE001
last = exc
await asyncio.sleep(1)
print(
f"{time.monotonic() - t0:7.2f} NOT BACK after reboot (last error {last!r})",
flush=True,
)
return 1
sys.exit(asyncio.run(main()))
@@ -1,66 +0,0 @@
"""Run N update checks over the API and print the update state plus http_request/update/long-operation log lines.
Usage: updcheck.py IP LABEL N"""
import asyncio
import re
import sys
import time
import aioesphomeapi
IP, LABEL, N = sys.argv[1], sys.argv[2], int(sys.argv[3])
async def main():
c = aioesphomeapi.APIClient(IP, 6053, None)
await c.connect(login=True)
info = await c.device_info()
print(
f"{LABEL} device {info.name} {info.esphome_version} {info.compilation_time}",
flush=True,
)
ents, _ = await c.list_entities_services()
upd = next(e for e in ents if isinstance(e, aioesphomeapi.UpdateInfo))
states = []
def on_state(s):
if s.key == upd.key:
states.append(s)
print(
f"{LABEL} {time.monotonic() - t0:7.2f} UPDATE in_progress={s.in_progress} current={s.current_version} latest={s.latest_version} title={s.title!r}",
flush=True,
)
def on_log(m):
t = (
m.message.decode(errors="replace")
if isinstance(m.message, bytes)
else m.message
)
t = re.sub(r"\x1b\[[0-9;]*m", "", t)
if re.search(
r"http_request|update|took a long time|Guru|abort|heap|Free",
t,
re.IGNORECASE,
):
print(f"{LABEL} {time.monotonic() - t0:7.2f} {t[:200]}", flush=True)
t0 = time.monotonic()
c.subscribe_states(on_state)
c.subscribe_logs(on_log, log_level=aioesphomeapi.LogLevel.LOG_LEVEL_DEBUG)
await asyncio.sleep(3)
missing = []
for i in range(N):
print(f"{LABEL} {time.monotonic() - t0:7.2f} CHECK {i + 1}", flush=True)
before = len(states)
c.update_command(upd.key, aioesphomeapi.UpdateCommand.CHECK)
await asyncio.sleep(25)
if not any(not st.in_progress for st in states[before:]):
print(f"{LABEL} CHECK {i + 1} got no finished update state", flush=True)
missing.append(i + 1)
await c.disconnect()
print(f"{LABEL} {N - len(missing)} of {N} checks reported a state", flush=True)
return 1 if missing else 0
sys.exit(asyncio.run(main()))
@@ -1,129 +0,0 @@
"""Drive the http_request update harness over the API: press buttons, print every update state and save the log.
usage: updrive.py HOST KEY(- for plaintext) LOGFILE OP [OP ...]
OP: list | press:NAME | set:NAME=VALUE | sel:NAME=OPTION | wait:SECONDS
"""
import asyncio
import pathlib
import sys
import time
from aioesphomeapi import (
APIClient,
BinarySensorState,
ButtonInfo,
LogLevel,
NumberInfo,
NumberState,
SelectInfo,
SelectState,
SensorInfo,
SensorState,
TextSensorInfo,
TextSensorState,
UpdateState,
)
HOST, KEY, LOGFILE = sys.argv[1], sys.argv[2], sys.argv[3]
OPS = sys.argv[4:]
T0 = time.time()
def stamp() -> str:
return f"{time.time() - T0:7.3f}"
async def main() -> None:
with pathlib.Path(LOGFILE).open("w", encoding="utf-8") as log:
c = APIClient(HOST, 6053, None, noise_psk=None if KEY == "-" else KEY)
await c.connect(login=True)
info = await c.device_info()
print(
f"device {info.name} esphome {info.esphome_version} compiled {info.compilation_time}"
)
ents, _ = await c.list_entities_services()
by_key = {e.key: e for e in ents}
buttons = {e.name: e for e in ents if isinstance(e, ButtonInfo)}
selects = {e.name: e for e in ents if isinstance(e, SelectInfo)}
def on_state(s) -> None:
e = by_key.get(s.key)
if e is None:
return
if isinstance(s, TextSensorState):
print(
f"{stamp()} TXT {e.name} = {s.state!r}{' (missing)' if s.missing_state else ''}",
flush=True,
)
elif isinstance(s, UpdateState):
print(
f"{stamp()} UPD {e.name} latest={s.latest_version!r} title={s.title!r} summary={s.release_summary!r} in_progress={s.in_progress}{' (missing)' if s.missing_state else ''}",
flush=True,
)
elif isinstance(s, BinarySensorState):
print(
f"{stamp()} BIN {e.name} = {s.state}{' (missing)' if s.missing_state else ''}",
flush=True,
)
elif isinstance(s, NumberState):
print(
f"{stamp()} NUM {e.name} = {s.state:.0f}{' (missing)' if s.missing_state else ''}",
flush=True,
)
elif isinstance(s, SelectState):
print(
f"{stamp()} SEL {e.name} = {s.state!r}{' (missing)' if s.missing_state else ''}",
flush=True,
)
elif isinstance(s, SensorState) and isinstance(e, SensorInfo):
print(f"{stamp()} SEN {e.name} = {s.state:.0f}", flush=True)
def on_log(msg) -> None:
log.write(f"{stamp()} {msg.message.decode(errors='replace')}\n")
c.subscribe_states(on_state)
c.subscribe_logs(on_log, log_level=LogLevel.LOG_LEVEL_VERBOSE)
await asyncio.sleep(1.5)
for op in OPS:
if op == "list":
for n in sorted(buttons):
print("button:", n)
for n in sorted(selects):
print("select:", n, selects[n].options)
for e in ents:
if isinstance(e, TextSensorInfo):
print("text_sensor:", e.name)
continue
kind, _, rest = op.partition(":")
if kind == "wait":
await asyncio.sleep(float(rest))
continue
if kind == "press":
if rest not in buttons:
sys.exit(f"no button named {rest!r}; have {sorted(buttons)}")
print(f"{stamp()} >>> press {rest}", flush=True)
log.write(f"{stamp()} >>> press {rest}\n")
c.button_command(buttons[rest].key)
elif kind == "set":
name, _, value = rest.partition("=")
numbers = {e.name: e for e in ents if isinstance(e, NumberInfo)}
if name not in numbers:
sys.exit(f"no number named {name!r}")
print(f"{stamp()} >>> set {name} = {value}", flush=True)
log.write(f"{stamp()} >>> set {name} = {value}\n")
c.number_command(numbers[name].key, float(value))
elif kind == "sel":
name, _, value = rest.partition("=")
if name not in selects:
sys.exit(f"no select named {name!r}; have {sorted(selects)}")
print(f"{stamp()} >>> select {name} = {value}", flush=True)
log.write(f"{stamp()} >>> select {name} = {value}\n")
c.select_command(selects[name].key, value)
else:
sys.exit(f"unknown op {op!r}")
await asyncio.sleep(2.0)
await asyncio.sleep(1)
await c.disconnect()
asyncio.run(main())
@@ -1,79 +0,0 @@
# 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));
@@ -1,50 +0,0 @@
#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);
}
@@ -1,29 +0,0 @@
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();
@@ -1,86 +0,0 @@
"""Drive the modem test build over the API: press buttons, print sensor states, save the device log.
usage: mdrive.py HOST LOGFILE OP [OP ...]
OP: list | press:NAME | wait:SECONDS
"""
import asyncio
import pathlib
import sys
import time
from aioesphomeapi import (
APIClient,
ButtonInfo,
LogLevel,
SensorInfo,
SensorState,
TextSensorInfo,
TextSensorState,
)
HOST, LOGFILE = sys.argv[1], sys.argv[2]
OPS = sys.argv[3:]
T0 = time.time()
def stamp() -> str:
return f"{time.time() - T0:7.3f}"
async def main() -> None:
with pathlib.Path(LOGFILE).open("w", encoding="utf-8") as log:
c = APIClient(HOST, 6053, None)
await c.connect(login=True)
info = await c.device_info()
print(
f"device {info.name} esphome {info.esphome_version} compiled {info.compilation_time}"
)
ents, _ = await c.list_entities_services()
by_key = {e.key: e for e in ents}
buttons = {e.name: e for e in ents if isinstance(e, ButtonInfo)}
def on_state(s) -> None:
e = by_key.get(s.key)
if e is None:
return
if isinstance(s, TextSensorState):
print(
f"{stamp()} TXT {e.name} = {s.state!r}{' (missing)' if s.missing_state else ''}",
flush=True,
)
elif isinstance(s, SensorState) and isinstance(e, SensorInfo):
print(f"{stamp()} SEN {e.name} = {s.state:.1f}", flush=True)
def on_log(msg) -> None:
log.write(f"{stamp()} {msg.message.decode(errors='replace')}\n")
log.flush()
c.subscribe_states(on_state)
c.subscribe_logs(on_log, log_level=LogLevel.LOG_LEVEL_DEBUG)
await asyncio.sleep(1.5)
for op in OPS:
if op == "list":
for n in sorted(buttons):
print("button:", n)
for e in ents:
if isinstance(e, (TextSensorInfo, SensorInfo)):
print("entity:", type(e).__name__, e.name)
continue
kind, _, rest = op.partition(":")
if kind == "wait":
await asyncio.sleep(float(rest))
continue
if kind == "press":
if rest not in buttons:
sys.exit(f"no button named {rest!r}; have {sorted(buttons)}")
print(f"{stamp()} >>> press {rest}", flush=True)
log.write(f"{stamp()} >>> press {rest}\n")
c.button_command(buttons[rest].key)
else:
sys.exit(f"unknown op {op!r}")
await asyncio.sleep(2.0)
await asyncio.sleep(1)
await c.disconnect()
asyncio.run(main())
@@ -1,8 +0,0 @@
substitutions: {name: mqabase, suffix: "true"}
esp32:
board: esp32dev
framework: {type: esp-idf}
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
@@ -1,9 +0,0 @@
substitutions: {name: mqbbase, suffix: "true"}
esp32:
board: esp32dev
framework: {type: esp-idf}
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
topic_prefix: custpre32
@@ -1,18 +0,0 @@
substitutions: {name: mqcbase, suffix: "true"}
esp32:
board: esp32dev
framework: {type: esp-idf}
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
log_topic: explicit32/log
birth_message:
topic: explicit32/avail
payload: up
will_message:
topic: explicit32/avail
payload: down
shutdown_message:
topic: explicit32/avail
payload: bye
@@ -1,8 +0,0 @@
substitutions: {name: mqd32base, suffix: "false"}
esp32:
board: esp32dev
framework: {type: esp-idf}
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
@@ -1,7 +0,0 @@
substitutions: {name: mqabase, suffix: "true"}
esp8266:
board: d1_mini
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
@@ -1,8 +0,0 @@
substitutions: {name: mqbbase, suffix: "true"}
esp8266:
board: d1_mini
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
topic_prefix: custpre66
@@ -1,17 +0,0 @@
substitutions: {name: mqcbase, suffix: "true"}
esp8266:
board: d1_mini
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
log_topic: explicit66/log
birth_message:
topic: explicit66/avail
payload: up
will_message:
topic: explicit66/avail
payload: down
shutdown_message:
topic: explicit66/avail
payload: bye
@@ -1,7 +0,0 @@
substitutions: {name: mqd66base, suffix: "false"}
esp8266:
board: d1_mini
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
@@ -1,24 +0,0 @@
# Package for esphome#9315, included by the per-variant files under pr/ and base/ (substitutions name, suffix).
esphome:
name: ${name}
name_add_mac_suffix: ${suffix}
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
power_save_mode: none
logger:
level: DEBUG
ota:
- platform: esphome
button:
- platform: restart
name: Restart
interval:
- interval: 10s
then:
- logger.log: "alive"
@@ -1,8 +0,0 @@
substitutions: {name: mqapr, suffix: "true"}
esp32:
board: esp32dev
framework: {type: esp-idf}
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
@@ -1,9 +0,0 @@
substitutions: {name: mqbpr, suffix: "true"}
esp32:
board: esp32dev
framework: {type: esp-idf}
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
topic_prefix: custpre32
@@ -1,18 +0,0 @@
substitutions: {name: mqcpr, suffix: "true"}
esp32:
board: esp32dev
framework: {type: esp-idf}
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
log_topic: explicit32/log
birth_message:
topic: explicit32/avail
payload: up
will_message:
topic: explicit32/avail
payload: down
shutdown_message:
topic: explicit32/avail
payload: bye
@@ -1,8 +0,0 @@
substitutions: {name: mqd32pr, suffix: "false"}
esp32:
board: esp32dev
framework: {type: esp-idf}
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
@@ -1,7 +0,0 @@
substitutions: {name: mqapr, suffix: "true"}
esp8266:
board: d1_mini
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
@@ -1,8 +0,0 @@
substitutions: {name: mqbpr, suffix: "true"}
esp8266:
board: d1_mini
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
topic_prefix: custpre66
@@ -1,17 +0,0 @@
substitutions: {name: mqcpr, suffix: "true"}
esp8266:
board: d1_mini
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
log_topic: explicit66/log
birth_message:
topic: explicit66/avail
payload: up
will_message:
topic: explicit66/avail
payload: down
shutdown_message:
topic: explicit66/avail
payload: bye
@@ -1,7 +0,0 @@
substitutions: {name: mqd66pr, suffix: "false"}
esp8266:
board: d1_mini
packages: {mq: !include ../../mq-common.yaml}
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
@@ -1,51 +0,0 @@
#!/bin/bash
# run.sh X BUILD : flash variant X (a..d) of BUILD (pr|base) on both boards, record broker traffic, restart, hard reset
# Copy this directory to a scratch directory and run it there; secrets.yaml (wifi_ssid, wifi_password, broker_ip)
# goes next to mq-common.yaml and in every board folder.
# env: TREE (esphome checkout for BUILD), P32 and P66 (ESP32 and ESP8266 serial ports), SC (path to
# serial_capture.py), PY (checkout python)
M=$(cd "$(dirname "$0")" && pwd); X=$1; V=$2; T=${TREE:?set TREE to the checkout under test}
P32=${P32:?set P32}; P66=${P66:?set P66}; SC=${SC:?set SC}
PY=${PY:-$T/venv/bin/python}; OUT=$M/out-$X-$V; mkdir -p $OUT
pkill -f "[s]erial_capture.py $P32"; pkill -f "[s]erial_capture.py $P66"; pkill -f "[m]osquitto_sub -h 127.0.0.1"
# compile one at a time (shared tool caches), then flash both boards at once; upload alone never builds
for b in 32 66; do
(cd $T && $PY -m esphome compile $M/$V/$b/mq${X}$b$V.yaml > $OUT/c$b.log 2>&1) || { echo "compile$b failed, see $OUT/c$b.log"; exit 1; }
done
(cd $T && $PY -m esphome upload $M/$V/32/mq${X}32$V.yaml --device $P32 > $OUT/u32.log 2>&1) & U32=$!
(cd $T && $PY -m esphome upload $M/$V/66/mq${X}66$V.yaml --device $P66 > $OUT/u66.log 2>&1) & U66=$!
wait $U32 || { echo "upload32 failed, see $OUT/u32.log"; exit 1; }
wait $U66 || { echo "upload66 failed, see $OUT/u66.log"; exit 1; }
mosquitto_sub -h 127.0.0.1 -v -t '#' -F '@H:@M:@S r=%r %t %p' > $OUT/broker.txt 2>&1 &
SUB=$!
$PY $SC $P32 170 $OUT/s32.txt --reset > /dev/null 2>&1 &
$PY $SC $P66 170 $OUT/s66.txt > /dev/null 2>&1 &
sleep 60
TOPICS=$(grep "homeassistant/button/" $OUT/broker.txt | grep "\"name\":\"mq${X}" | grep -o '"cmd_t":"[^"]*"' | cut -d'"' -f4 | sort -u)
ERR=0
[ "$(echo "$TOPICS" | grep -c .)" -ge 2 ] || { echo "ERROR: expected a Restart command topic per board, found: ${TOPICS:-none}"; ERR=1; }
for t in $TOPICS; do
mosquitto_pub -h 127.0.0.1 -t "$t" -m PRESS && echo "$(date +%T) press $t" || { echo "$(date +%T) ERROR: publish to $t failed"; ERR=1; }
done
sleep 45
pkill -f "[s]erial_capture.py $P32"; pkill -f "[s]erial_capture.py $P66"; sleep 1
echo "$(date +%T) hold both in the bootloader for 40 s (will test)"
$PY -m esptool --port $P32 --after no-reset chip-id > $OUT/hold32.log 2>&1 & H32=$!
$PY -m esptool --port $P66 --after no-reset chip-id > $OUT/hold66.log 2>&1 & H66=$!
wait $H32 || { echo "ERROR: ESP32 not held in the bootloader, no will expected (see $OUT/hold32.log)"; ERR=1; }
wait $H66 || { echo "ERROR: ESP8266 not held in the bootloader, no will expected (see $OUT/hold66.log)"; ERR=1; }
sleep 40
REL=$(date +%T); echo "$REL release both"
$PY $SC $P32 40 $OUT/s32b.txt --reset > /dev/null 2>&1 &
$PY $SC $P66 40 $OUT/s66b.txt --reset > /dev/null 2>&1 &
sleep 42
kill $SUB
for f in s32 s66; do echo "== $f"; grep -a -E "Topic Prefix|Log Topic|Availability|Client ID" $OUT/$f.txt | head -4 | sed 's/^\[[0-9:]*\]//'; done
echo "== broker (excluding discovery and entity state)"
grep -v -E " homeassistant/| [^ ]*/(sensor|button|binary_sensor)/| esphome/discover/" $OUT/broker.txt | awk '$3 ~ /(debug|log)$/ { if (seen[$3]++) next; print $1, $2, $3, "(log lines:", "see file)"; next } { print }' | head -40
echo "== log line counts per topic"; awk '$3 ~ /(debug|log)$/ {c[$3]++} END {for (t in c) print t, c[t]}' $OUT/broker.txt
# each board must publish its birth message (default "online", explicit variant "up") after the release;
# a missing will is the measured result and does not fail the run
BIRTHS=$(awk -v t="$REL" '$1 >= t && ($4 == "online" || $4 == "up") {print $3}' $OUT/broker.txt | sort -u | grep -c .)
[ "$BIRTHS" -ge 2 ] || { echo "ERROR: $BIRTHS of 2 boards published a birth message after the release"; ERR=1; }
exit $ERR
@@ -1,9 +0,0 @@
substitutions: {name: sd32base}
esphome:
name: sd32base
esp32:
board: esp32dev
framework: {type: esp-idf}
deep_sleep:
id: ds
packages: {c: !include ../sd-common.yaml}
@@ -1,8 +0,0 @@
substitutions: {name: sd66base}
esphome:
name: sd66base
esp8266:
board: d1_mini
deep_sleep:
id: ds
packages: {c: !include ../sd-common.yaml}
@@ -1,33 +0,0 @@
"""match.py OUTDIR: for each event, say whether a bye/dead for that board arrived within 5 s."""
import pathlib
import sys
d = pathlib.Path(sys.argv[1])
def secs(stamp: str) -> int:
h, m, s = (int(x) for x in stamp.split(":"))
return h * 3600 + m * 60 + s
ev = [ln.split() for ln in (d / "events.txt").read_text(encoding="utf-8").splitlines()]
br = [
f
for f in (
ln.split() for ln in (d / "broker.txt").read_text(encoding="utf-8").splitlines()
)
if len(f) >= 3 and f[2] in ("bye", "dead")
]
rows = {}
for ts, kind, b in ev:
hit = [
p
for s, top, p in br
if top.startswith(f"sd{b}") and 0 <= secs(s) - secs(ts) <= 5
]
rows.setdefault((b, kind), []).append(
"bye" if "bye" in hit else (hit[0] if hit else "-")
)
for (b, kind), r in sorted(rows.items()):
print(f"{b} {kind:8s} {r.count('bye')}/{len(r)} bye {' '.join(r)}")
@@ -1,9 +0,0 @@
substitutions: {name: sd32pr}
esphome:
name: sd32pr
esp32:
board: esp32dev
framework: {type: esp-idf}
deep_sleep:
id: ds
packages: {c: !include ../sd-common.yaml}
@@ -1,8 +0,0 @@
substitutions: {name: sd66pr}
esphome:
name: sd66pr
esp8266:
board: d1_mini
deep_sleep:
id: ds
packages: {c: !include ../sd-common.yaml}
@@ -1,40 +0,0 @@
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
power_save_mode: none
logger:
level: DEBUG
mqtt:
broker: !secret broker_ip
reboot_timeout: 0s
discovery: false
birth_message: {topic: "${name}/status", payload: hello}
will_message: {topic: "${name}/status", payload: dead}
shutdown_message: {topic: "${name}/status", payload: bye}
on_message:
- topic: ${name}/cmd
payload: restart
then:
- button.press: restart_btn
- topic: ${name}/cmd
payload: disable
then:
- mqtt.disable:
- delay: 5s
- mqtt.enable:
- topic: ${name}/cmd
payload: sleep
then:
- deep_sleep.enter:
id: ds
sleep_duration: 5s
ota:
- platform: esphome
button:
- platform: restart
id: restart_btn
name: Restart
@@ -1,44 +0,0 @@
#!/bin/bash
# sdrun.sh V(pr|base) [N] : flash both boards, restart each N times over MQTT, then disable, then deep sleep (ESP32)
# Copy this directory to a scratch directory (secrets.yaml with wifi_ssid, wifi_password and broker_ip next to
# sd-common.yaml) and run it there with a local mosquitto on this host.
# env: TREE (esphome checkout for V), P32 and P66 (ESP32 and ESP8266 serial ports), PY (checkout python)
S=$(cd "$(dirname "$0")" && pwd); V=$1; N=${2:-10}; T=${TREE:?set TREE}; PY=${PY:-$T/venv/bin/python}
P32=${P32:?set P32}; P66=${P66:?set P66}; OUT=$S/out-$V; rm -rf "$OUT"; mkdir -p "$OUT"
pkill -f "[s]erial_capture.py $P32"; pkill -f "[s]erial_capture.py $P66"
# compile one at a time (shared tool caches), then flash both boards at once; upload alone never builds
for b in 32 66; do
(cd "$T" && $PY -m esphome compile "$S/$V/sd$b$V.yaml" > "$OUT/c$b.log" 2>&1) || { echo "compile$b failed, see $OUT/c$b.log"; exit 1; }
done
(cd "$T" && $PY -m esphome upload "$S/$V/sd32$V.yaml" --device "$P32" > "$OUT/u32.log" 2>&1) & U32=$!
(cd "$T" && $PY -m esphome upload "$S/$V/sd66$V.yaml" --device "$P66" > "$OUT/u66.log" 2>&1) & U66=$!
wait $U32 || { echo "upload32 failed"; exit 1; }; wait $U66 || { echo "upload66 failed"; exit 1; }
mosquitto_sub -h 127.0.0.1 -R -v -t "sd32$V/status" -t "sd66$V/status" -F '@H:@M:@S %t %p' > "$OUT/broker.txt" 2>&1 & SUB=$!
# cmd KIND BOARD: publish the command and record the event only when the publish worked
ERR=0
cmd() {
local ts; ts=$(date +%T)
if mosquitto_pub -h 127.0.0.1 -t "sd$2$V/cmd" -m "$1"; then echo "$ts $1 $2" >> "$OUT/events.txt"
else echo "$ts ERROR: publish $1 to board $2 failed"; ERR=1; fi
}
sleep 40
for b in 32 66; do
grep -q "sd$b$V/status hello" "$OUT/broker.txt" || { echo "ERROR: sd$b$V never sent its birth message"; kill $SUB; exit 1; }
done
for i in $(seq "$N"); do
for b in 32 66; do cmd restart $b; done
sleep 25
done
for b in 32 66; do cmd disable $b; done
sleep 30
for i in 1 2 3; do cmd sleep 32; sleep 30; done
kill -0 $SUB 2>/dev/null || { echo "ERROR: the broker subscriber died, counts are incomplete"; ERR=1; }
kill $SUB 2>/dev/null
for b in 32 66; do echo "sd$b$V: $(grep -c "sd$b$V/status hello" "$OUT/broker.txt") hello, $(grep -c "sd$b$V/status bye" "$OUT/broker.txt") bye, $(grep -c "sd$b$V/status dead" "$OUT/broker.txt") dead"; done
# each restart, the disable (a reconnect) and each ESP32 deep sleep is followed by a new birth message
for b in 32 66; do
want=$((N + 2)); [ $b = 32 ] && want=$((want + 3))
got=$(grep -c "sd$b$V/status hello" "$OUT/broker.txt")
[ "$got" -ge "$want" ] || { echo "ERROR: sd$b$V sent $got birth messages, expected $want (a board did not come back)"; ERR=1; }
done
exit $ERR
@@ -1,115 +0,0 @@
"""Reboot the DUT before each fetch and report the longest online_image loop pass of that one fetch.
usage: firstpass.py HOST KEY BASEURL LABEL IMAGE...
The component warning prints only on a new maximum, so a fresh boot per image gives that image's own maximum.
"""
import asyncio
import contextlib
import re
import sys
import time
from aioesphomeapi import (
APIClient,
ButtonInfo,
InvalidAuthAPIError,
InvalidEncryptionKeyAPIError,
LogLevel,
RequiresEncryptionAPIError,
UserService,
)
HOST, KEY, BASE, LABEL = sys.argv[1:5]
IMAGES = sys.argv[5:]
TOOK = re.compile(r"online_image\.image took a long time for an operation \((\d+) ms\)")
OUTCOME = re.compile(r"download (finished|error): img\b")
async def connect() -> tuple[APIClient, dict, int]:
last: Exception | None = None
for _ in range(30):
c = APIClient(HOST, 6053, None, noise_psk=KEY)
try:
await c.connect(login=True)
break
except (
InvalidAuthAPIError,
InvalidEncryptionKeyAPIError,
RequiresEncryptionAPIError,
):
raise # a wrong key never fixes itself
except Exception as exc: # noqa: BLE001
last = exc
await asyncio.sleep(2)
else:
raise RuntimeError(f"device did not come back (last error {last!r})")
ents, services = await c.list_entities_services()
reboot = next(
(e.key for e in ents if isinstance(e, ButtonInfo) and e.name == "Reboot"), None
)
if reboot is None:
raise RuntimeError("the device has no button named Reboot")
return c, {s.name: s for s in services if isinstance(s, UserService)}, reboot
async def rebooted(c: APIClient, reboot: int) -> bool:
"""Press Reboot and wait up to 15 s for the API connection to drop."""
c.button_command(reboot)
end = time.monotonic() + 15
while time.monotonic() < end:
try:
await asyncio.wait_for(c.device_info(), 1.0)
except TimeoutError:
continue # a slow reply is not a reboot; only a closed connection counts
except Exception: # noqa: BLE001
return True
await asyncio.sleep(0.2)
return False
async def main() -> int:
failed = []
for img in IMAGES:
c, actions, reboot = await connect()
ok = await rebooted(c, reboot)
with contextlib.suppress(Exception):
await c.disconnect()
if not ok:
print(f"{LABEL} {img:22} SKIPPED: no reboot within 15 s", flush=True)
failed.append(img)
continue
await asyncio.sleep(8)
c, actions, reboot = await connect()
lines: list[str] = []
c.subscribe_logs(
lambda m, lines=lines: lines.append(m.message.decode(errors="replace")),
log_level=LogLevel.LOG_LEVEL_DEBUG,
)
await asyncio.sleep(3)
lines.clear()
t0 = time.monotonic()
await c.execute_service(actions["fetch"], {"url": f"{BASE}/{img}"})
outcome = None
while time.monotonic() - t0 < 60 and outcome is None:
await asyncio.sleep(0.2)
outcome = next(
(m.group(1) for ln in lines if (m := OUTCOME.search(ln))), None
)
took = time.monotonic() - t0
await asyncio.sleep(1)
passes = [int(m.group(1)) for ln in lines if (m := TOOK.search(ln))]
print(
f"{LABEL} {img:22} {outcome or 'none':9} {took:5.1f}s longest pass {max(passes) if passes else '<50'} ms {passes}",
flush=True,
)
if (
outcome != "finished"
): # a decode timing is only meaningful for a complete image
failed.append(img)
await c.disconnect()
if failed:
print(f"{LABEL} not finished: {', '.join(failed)}", flush=True)
return 1 if failed else 0
sys.exit(asyncio.run(main()))
@@ -1,32 +0,0 @@
"""Build the large PNGs for the decode time test: a compressible gradient (also saved as ok.png so every server case
carries a multi-row PNG), a flat 640x480 image whose few KB hold 307200 pixels, incompressible noise, and a JPEG."""
from pathlib import Path
import random
import sys
from PIL import Image
www = Path(sys.argv[1])
im = Image.new("RGB", (320, 240))
px = im.load()
for y in range(240):
for x in range(320):
px[x, y] = (x * 255 // 319, y * 255 // 239, 128)
im.save(www / "ok.png", "PNG", optimize=True)
im.save(www / "gradient.png", "PNG", optimize=True)
im.save(www / "gradient.jpg", "JPEG", quality=85)
Image.new("RGB", (640, 480), (40, 90, 200)).save(www / "flat.png", "PNG", optimize=True)
random.seed(1)
noise = Image.new("RGB", (320, 240))
npx = noise.load()
for y in range(240):
for x in range(320):
npx[x, y] = (
random.randrange(256),
random.randrange(256),
random.randrange(256),
)
noise.save(www / "noise.png", "PNG")
for p in sorted(www.iterdir()):
print(p.name, p.stat().st_size)
@@ -1,93 +0,0 @@
"""Write big BMP (1, 8, 24 bit) and QOI test images into a www directory."""
from pathlib import Path
import random
import struct
import sys
from PIL import Image
www = Path(sys.argv[1])
def gradient(w, h):
im = Image.new("RGB", (w, h))
im.putdata(
[
((x * 255) // w, (y * 255) // h, ((x + y) * 255) // (w + h))
for y in range(h)
for x in range(w)
]
)
return im
def checker(w, h):
im = Image.new("1", (w, h))
im.putdata(
[255 if ((x // 16) + (y // 16)) % 2 else 0 for y in range(h) for x in range(w)]
)
return im
checker(640, 480).save(www / "bmp1_640.bmp")
gradient(320, 240).convert("P", palette=Image.ADAPTIVE).save(www / "bmp8_320.bmp")
gradient(320, 240).save(www / "bmp24_320.bmp")
def qoi(im, path):
im = im.convert("RGBA")
w, h = im.size
out = bytearray(b"qoif" + struct.pack(">IIBB", w, h, 4, 0))
idx = [(0, 0, 0, 0)] * 64
prev = (0, 0, 0, 255)
run = 0
px = list(im.getdata())
for i, p in enumerate(px):
if p == prev:
run += 1
if run == 62 or i == len(px) - 1:
out.append(0xC0 | (run - 1))
run = 0
continue
if run:
out.append(0xC0 | (run - 1))
run = 0
h_ = (p[0] * 3 + p[1] * 5 + p[2] * 7 + p[3] * 11) % 64
if idx[h_] == p:
out.append(h_)
else:
idx[h_] = p
if p[3] == prev[3]:
dr, dg, db = (
((p[0] - prev[0] + 128) % 256) - 128,
((p[1] - prev[1] + 128) % 256) - 128,
((p[2] - prev[2] + 128) % 256) - 128,
)
drg, dbg = dr - dg, db - dg
if -2 <= dr <= 1 and -2 <= dg <= 1 and -2 <= db <= 1:
out.append(0x40 | (dr + 2) << 4 | (dg + 2) << 2 | (db + 2))
elif -32 <= dg <= 31 and -8 <= drg <= 7 and -8 <= dbg <= 7:
out += bytes([0x80 | (dg + 32), (drg + 8) << 4 | (dbg + 8)])
else:
out += bytes([0xFE, p[0], p[1], p[2]])
else:
out += bytes([0xFF, *p])
prev = p
out += b"\x00" * 7 + b"\x01"
path.write_bytes(out)
qoi(
Image.new("RGB", (640, 480), (0, 0, 0)).copy(), www / "qoi_flat.qoi"
) # all runs, 62 pixels a byte
qoi(checker(640, 480).convert("RGB"), www / "qoi_check.qoi")
qoi(gradient(320, 240), www / "qoi_grad.qoi")
random.seed(1)
noise = Image.frombytes(
"RGB", (320, 240), bytes(random.getrandbits(8) for _ in range(320 * 240 * 3))
)
qoi(noise, www / "qoi_noise.qoi")
for f in sorted(www.glob("*_*.*")):
print(f.name, f.stat().st_size)
@@ -1,42 +0,0 @@
"""Build the JPEGs for the streaming decode test: noise 320x240 (also ok.jpg) and 640x480, a 640x480 gradient, the
320x240 noise with a 12 KB EXIF segment in front of the frame header, and a progressive one."""
from pathlib import Path
import random
import sys
from PIL import Image
www = Path(sys.argv[1])
random.seed(2)
def noise(w: int, h: int) -> Image.Image:
im = Image.new("RGB", (w, h))
px = im.load()
for y in range(h):
for x in range(w):
px[x, y] = (
random.randrange(256),
random.randrange(256),
random.randrange(256),
)
return im
n320 = noise(320, 240)
n320.save(www / "noise320.jpg", "JPEG", quality=90)
n320.save(www / "ok.jpg", "JPEG", quality=90)
noise(640, 480).save(www / "noise640.jpg", "JPEG", quality=85)
g = Image.new("RGB", (640, 480))
px = g.load()
for y in range(480):
for x in range(640):
px[x, y] = (x * 255 // 639, y * 255 // 479, 128)
g.save(www / "gradient640.jpg", "JPEG", quality=85)
n320.save(
www / "bigexif320.jpg", "JPEG", quality=90, exif=b"Exif\x00\x00" + bytes(12000)
)
n320.save(www / "progressive320.jpg", "JPEG", quality=90, progressive=True)
for p in sorted(www.iterdir()):
print(p.name, p.stat().st_size)
@@ -5,16 +5,7 @@ from pathlib import Path
import sys
import time
WWW = Path(sys.argv[1]).resolve()
NOT_FOUND = b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
def www_file(rel: str) -> Path | None:
"""The file under WWW named by a request path, or None if missing or outside WWW."""
file = (WWW / rel).resolve()
return file if file.is_relative_to(WWW) and file.is_file() else None
WWW = Path(sys.argv[1])
PORT = int(sys.argv[2])
LOG = Path(sys.argv[3]).open("a", encoding="utf-8", buffering=1) # noqa: SIM115
@@ -117,34 +108,8 @@ async def respond(path: str, req: bytes, w: asyncio.StreamWriter) -> str:
if name == "huge": # claims 20 MB so the JPEG buffer resize fails
w.write(headers(ctype, [b"Content-Length: 20000000"]) + body)
return f"claims 20000000, sent {len(body)} bytes"
prefix, _, rest = name.partition("_")
if prefix in ("half", "noclen", "chunked", "stall") and rest:
# 404 when the base file is missing, so a typo never passes as the misbehaviour under test
file = www_file(rest + "." + ext)
else:
prefix, file = "", www_file(path.lstrip("/"))
if file is None:
w.write(NOT_FOUND)
return "404"
data = file.read_bytes()
if prefix == "half": # the first half of a file, Content-Length matching
cut = data[: len(data) // 2]
w.write(headers(ctype, [b"Content-Length: %d" % len(cut)]) + cut)
return f"half {len(cut)} of {len(data)} bytes"
if prefix == "noclen": # a file without Content-Length, delimited by close
w.write(headers(ctype, []) + data)
return f"no content-length, full {len(data)} bytes"
if prefix == "chunked": # a file in 1 KB chunks
w.write(headers(ctype, [b"Transfer-Encoding: chunked"]) + chunked(data, 1024))
return f"chunked full {len(data)} bytes"
if prefix == "stall": # claims the full length, sends a third, holds the socket
part = data[: len(data) // 3]
w.write(headers(ctype, [b"Content-Length: %d" % len(data)]) + part)
await w.drain()
await asyncio.sleep(40)
return f"stalled after {len(part)} of {len(data)} bytes"
w.write(headers(ctype, [b"Content-Length: %d" % len(data), *tag]) + data)
return f"file {file.name} {len(data)} bytes"
w.write(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
return "404"
async def handle(r: asyncio.StreamReader, w: asyncio.StreamWriter) -> None:
@@ -1,261 +0,0 @@
"""Fetch images through the online_image API actions and report outcome, time, loop time maximum and heap minimum per case.
usage: [CASES=png|noise|end|bmpqoi|short|jpeg] pngdrive.py HOST KEY LOGFILE BASEURL LABEL
"""
import asyncio
import contextlib
import os
import pathlib
import re
import sys
import time
import urllib.error
import urllib.request
from aioesphomeapi import APIClient, LogLevel, SensorInfo, SensorState, UserService
HOST, KEY, LOGFILE, BASE, LABEL = sys.argv[1:6]
CAP_S = 60
OUTCOME = re.compile(r"download (finished|error): (\w+)")
INTEREST = re.compile(
r"took a long time|Error|error|Download ended|No data received|Waiting for more|Decoded|cut off|already being|headers do not fit|buffer_size|Downloading image|fully downloaded|allocat|not caching"
)
PNG = [
("gradient 320x240 png", "fetch", "gradient.png", "finished"),
("gradient again", "fetch", "gradient.png", "finished"),
("gradient again", "fetch", "gradient.png", "finished"),
("flat 640x480 png", "fetch", "flat.png", "finished"),
("flat again", "fetch", "flat.png", "finished"),
("flat again", "fetch", "flat.png", "finished"),
("gradient jpeg", "fetch", "gradient.jpg", "finished"),
("ok bmp 16x16", "fetch", "ok.bmp", "finished"),
("ok png 16x16 body = gradient", "fetch", "ok.png", "finished"),
("chunked png", "fetch", "chunked.png", "finished"),
("chunked png cut in half", "fetch", "chunked_cut.png", "any"),
("closed early png", "fetch", "closed_early.png", "error"),
("stalled png", "fetch", "stall.png", "error"),
("slow png", "fetch", "slow.png", "finished"),
("empty png", "fetch", "empty.png", "error"),
("no content-length png", "fetch", "noclen.png", "any"),
("truncated bmp", "fetch", "truncated.bmp", "error"),
("gradient after errors", "fetch", "gradient.png", "finished"),
("gradient refetch 304", "refetch", "", "finished"),
("noise 320x240 png", "fetch", "noise.png", "finished"),
("noise again", "fetch", "noise.png", "finished"),
]
NOISE = [("noise 320x240 png", "fetch", "noise.png", "finished")] * 3
END = [
(f"{pre}{img}", "fetch", f"{pre}{img}", exp)
for img in ("flat.png", "gradient.png")
for pre, exp in (
("", "finished"),
("noclen_", "finished"),
("chunked_", "finished"),
("half_", "any"),
("stall_", "error"),
)
] + [("gradient after", "fetch", "gradient.png", "finished")]
BMPQOI = [
(f"{pre}{img}", "fetch", f"{pre}{img}", exp)
for img in (
"bmp1_640.bmp",
"bmp8_320.bmp",
"bmp24_320.bmp",
"qoi_flat.qoi",
"qoi_check.qoi",
"qoi_grad.qoi",
"qoi_noise.qoi",
)
for pre, exp in (
("", "finished"),
("", "finished"),
("noclen_", "any"),
("chunked_", "any"),
("half_", "error"),
)
] + [
("ok bmp 16x16", "fetch", "ok.bmp", "finished"),
("ok qoi 16x16", "fetch", "ok.qoi", "finished"),
("truncated bmp", "fetch", "truncated.bmp", "error"),
("stall_bmp1_640.bmp", "fetch", "stall_bmp1_640.bmp", "error"),
("stall_qoi_flat.qoi", "fetch", "stall_qoi_flat.qoi", "error"),
("qoi_flat after", "fetch", "qoi_flat.qoi", "finished"),
]
SHORT = [
("gradient 320x240 png", "fetch", "gradient.png", "finished"),
("gradient again", "fetch", "gradient.png", "finished"),
("noise 320x240 png", "fetch", "noise.png", "finished"),
("noise again", "fetch", "noise.png", "finished"),
("noise again", "fetch", "noise.png", "finished"),
("gradient after noise", "fetch", "gradient.png", "finished"),
]
JPEG = [
("noise 320x240 jpeg 69 KB", "fetch", "noise320.jpg", "finished"),
("noise 320x240 again", "fetch", "noise320.jpg", "finished"),
("noise 320x240 again", "fetch", "noise320.jpg", "finished"),
("noise 640x480 jpeg 233 KB", "fetch", "noise640.jpg", "finished"),
("noise 640x480 again", "fetch", "noise640.jpg", "finished"),
("gradient 640x480 jpeg 14 KB", "fetch", "gradient640.jpg", "finished"),
("4 KB buffer: noise 320x240", "fetch_small", "noise320.jpg", "finished"),
("4 KB buffer: noise 640x480", "fetch_small", "noise640.jpg", "finished"),
("4 KB buffer: 12 KB exif", "fetch_small", "bigexif320.jpg", "any"),
("64 KB buffer: 12 KB exif", "fetch", "bigexif320.jpg", "finished"),
("progressive jpeg", "fetch", "progressive320.jpg", "any"),
("no content-length", "fetch", "noclen_noise320.jpg", "finished"),
("chunked", "fetch", "chunked_noise320.jpg", "finished"),
("half with matching length", "fetch", "half_noise320.jpg", "error"),
("closed early", "fetch", "closed_early.jpg", "error"),
("stalled after a third", "fetch", "stall_noise320.jpg", "error"),
("empty", "fetch", "empty.jpg", "error"),
("noise 320x240 after errors", "fetch", "noise320.jpg", "finished"),
("refetch 304", "refetch", "", "finished"),
("ok png 16x16", "fetch", "ok.png", "finished"),
("ok bmp 16x16", "fetch", "ok.bmp", "finished"),
("4 KB buffer: noise 640x480 again", "fetch_small", "noise640.jpg", "finished"),
("4 KB buffer: half", "fetch_small", "half_noise320.jpg", "error"),
("4 KB buffer: stalled", "fetch_small", "stall_noise320.jpg", "error"),
(
"4 KB buffer: noise 320x240 after errors",
"fetch_small",
"noise320.jpg",
"finished",
),
]
CASE_SETS = {
"png": PNG,
"noise": NOISE,
"end": END,
"bmpqoi": BMPQOI,
"short": SHORT,
"jpeg": JPEG,
}
CASES = CASE_SETS[os.environ.get("CASES", "png")]
def missing_base_files() -> list[str]:
"""Base files behind prefixed cases that the server does not serve (any HTTP error, or no server).
A failed fetch ends as a download error on the device, which would pass the half_ and stall_ cases untested.
"""
builtin = {"chunked_cut", "closed_early", "large_header"}
missing = []
for _, _, path, _ in CASES:
stem = path.rsplit(".", 1)[0]
prefix, _, rest = path.partition("_")
if (
stem in builtin
or prefix not in ("half", "noclen", "chunked", "stall")
or not rest
):
continue
try:
with urllib.request.urlopen(f"{BASE}/{rest}", timeout=10):
pass
except (urllib.error.URLError, OSError) as exc: # HTTPError is a URLError
missing.append(f"{rest} ({exc})")
return sorted(set(missing))
async def main() -> int:
if missing := missing_base_files():
print(
f"server has no {', '.join(missing)}; run the image generators first",
flush=True,
)
return 2
c = APIClient(HOST, 6053, None, noise_psk=KEY)
await c.connect(login=True)
ents, services = await c.list_entities_services()
actions = {s.name: s for s in services if isinstance(s, UserService)}
loop_key = next(
e.key for e in ents if isinstance(e, SensorInfo) and e.name == "Loop Time"
)
heap_key = next(
e.key for e in ents if isinstance(e, SensorInfo) and e.name == "Heap Free"
)
state = {"loop": [], "heap": None, "heap_min": None, "lines": []}
def on_state(s) -> None:
if isinstance(s, SensorState) and s.key == loop_key:
state["loop"].append(s.state)
elif isinstance(s, SensorState) and s.key == heap_key:
state["heap"] = s.state
if state["heap_min"] is None or s.state < state["heap_min"]:
state["heap_min"] = s.state
def on_log(msg) -> None:
line = msg.message.decode(errors="replace")
log.write(f"{time.strftime('%H:%M:%S')} {line}\n")
state["lines"].append(line)
with pathlib.Path(LOGFILE).open("w", encoding="utf-8") as log:
c.subscribe_states(on_state)
c.subscribe_logs(on_log, log_level=LogLevel.LOG_LEVEL_DEBUG)
await asyncio.sleep(3)
print(f"{LABEL}: heap at start {state['heap']}")
rows = []
for label, action, path, expect in CASES:
img = "img_small" if action.endswith("_small") else "img"
state["loop"].clear()
state["lines"].clear()
state["heap_min"] = None
args = {} if action.startswith("refetch") else {"url": f"{BASE}/{path}"}
t0 = time.monotonic()
log.write(f">>> {label} {path}\n")
try:
await c.execute_service(actions[action], args)
except Exception as exc: # noqa: BLE001
print(f" api call failed ({exc!r}); reconnecting", flush=True)
with contextlib.suppress(Exception):
await c.disconnect()
await asyncio.sleep(10)
await c.connect(login=True)
ents, services = await c.list_entities_services()
actions = {s.name: s for s in services if isinstance(s, UserService)}
c.subscribe_states(on_state)
c.subscribe_logs(on_log, log_level=LogLevel.LOG_LEVEL_DEBUG)
await asyncio.sleep(2)
state["lines"].clear()
t0 = time.monotonic()
await c.execute_service(actions[action], args)
outcome = "no outcome"
while time.monotonic() - t0 < CAP_S:
await asyncio.sleep(0.25)
for line in state["lines"]:
m = OUTCOME.search(line)
if m and m.group(2) == img:
outcome = m.group(1)
if outcome != "no outcome":
break
took = time.monotonic() - t0
await asyncio.sleep(4.5) # two loop time reports after the case
notes = [
ln for ln in state["lines"] if INTEREST.search(ln) and "Loop" not in ln
]
loop_max = max(state["loop"]) if state["loop"] else float("nan")
ok = outcome == expect or (expect == "any" and outcome != "no outcome")
rows.append((label, path, expect, outcome, took, loop_max, ok))
print(
f"{'PASS' if ok else 'FAIL'} {label:30s} {path:18s} expected {expect:9s} got {outcome:10s} {took:5.1f}s loop max {loop_max:7.0f} ms heap min {state['heap_min']}",
flush=True,
)
for n in notes[:8]:
print(f" {n.strip()}", flush=True)
await c.disconnect()
print(
"\nSUMMARY",
"all expectations met"
if all(r[6] for r in rows)
else "MISMATCHES: " + ", ".join(r[0] for r in rows if not r[6]),
)
return 0 if all(r[6] for r in rows) else 1
sys.exit(asyncio.run(main()))
@@ -1,43 +0,0 @@
"""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)
@@ -1,42 +0,0 @@
# 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();
@@ -1,44 +0,0 @@
# 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();
@@ -1,54 +0,0 @@
#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");
}
@@ -1,42 +0,0 @@
#!/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; }
@@ -1,43 +0,0 @@
"""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")
@@ -1,77 +0,0 @@
"""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]
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,
}
print("RESULT", json.dumps(result), flush=True)
sys.exit(1 if rc else 0)
@@ -1,65 +0,0 @@
#!/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"
@@ -1,43 +0,0 @@
"""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)
@@ -1,24 +0,0 @@
"""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)
@@ -1,75 +0,0 @@
"""Run the tx_all script N times over the API and count what each sent frame decoded as.
Usage: rbdrive.py IP N"""
import asyncio
import collections
import re
import sys
import aioesphomeapi
IP, N = sys.argv[1], int(sys.argv[2])
lines: list[str] = []
async def main() -> None:
c = aioesphomeapi.APIClient(IP, 6053, None)
await c.connect(login=True)
i = await c.device_info()
print("device", i.name, i.compilation_time, flush=True)
_, svcs = await c.list_entities_services()
s = {x.name: x for x in svcs}
def on_log(m):
lines.append(re.sub(r"\x1b\[[0-9;]*m", "", m.message.decode(errors="replace")))
c.subscribe_logs(on_log, log_level=aioesphomeapi.LogLevel.LOG_LEVEL_DEBUG)
await asyncio.sleep(1)
complete = 0
for rnd in range(1, N + 1):
start = len(lines)
await c.execute_service(s["tx_all"], {})
for _ in range(200):
if any("tx done" in x for x in lines[start:]):
complete += 1
break
await asyncio.sleep(0.1)
else:
print(f"round {rnd}: no tx done within 20 s", flush=True)
await asyncio.sleep(1)
await c.disconnect()
# per sent protocol: what was decoded
table: dict[str, collections.Counter] = collections.defaultdict(collections.Counter)
cur = None
for x in lines:
if m := re.search(r"\]: tx (\w+)$", x):
cur = m[1]
continue
if cur is None or cur == "done":
continue
if m := re.search(r"Received ([A-Za-z0-9_ ]+?):", x):
table[cur][m[1]] += 1
elif "ext dumper saw" in x:
table[cur]["ext"] += 1
print(f"{complete} of {N} rounds complete", flush=True)
for proto, cnt in table.items():
print(
f"{proto:11s} " + ", ".join(f"{k}={v}" for k, v in sorted(cnt.items())),
flush=True,
)
for x in lines:
if "ext dumper saw" not in x and re.search(
r"rbt|error|Error|overflow|Guru|panic", x
):
print(" ", x[:160])
if not any(k != "ext" for cnt in table.values() for k in cnt):
print("nothing decoded", flush=True)
return 1
if not any(cnt["ext"] for cnt in table.values()):
print("the external dumper saw no frame", flush=True)
return 1
return 0 if complete == N else 1
sys.exit(asyncio.run(main()))
@@ -1,24 +0,0 @@
#!/bin/bash
# run.sh LABEL B(32|66) [N] : write rb<B><LABEL> from templates/remote_base on every run, flash it, run rbdrive.py for N rounds
# Copy this directory and templates/remote_base into one scratch directory (secrets.yaml next to rb-common.yaml).
# env: TREE (esphome checkout to build from), P32 or P66 (serial port of the board), SC (path to
# serial_capture.py), PY (checkout python), EXPECT_REGISTER=1 (fail when the dumper registration was rejected)
R=$(cd "$(dirname "$0")" && pwd); V=$1; B=$2; N=${3:-3}; NAME=rb$B$V; T=${TREE:?set TREE}
PY=${PY:-$T/venv/bin/python}; SC=${SC:?set SC}
if [ "$B" = 32 ]; then P=${P32:?set P32}; else P=${P66:?set P66}; fi
mkdir -p "$R/$V"; sed "s/@V@/$V/g" "$R/rb$B.tmpl" > "$R/$V/$NAME.yaml" # always from the current template
OUT=$R/out-$V-$B; rm -rf "$OUT"; mkdir -p "$OUT"
pkill -f "[s]erial_capture.py $P"
(cd "$T" && $PY -m esphome run --no-logs "$R/$V/$NAME.yaml" --device "$P" > "$OUT/upload.log" 2>&1) || { echo "build or upload failed"; exit 1; }
$PY "$SC" "$P" 150 "$OUT/serial.txt" --reset > /dev/null 2>&1 & CAP=$!
trap 'kill $CAP 2>/dev/null' EXIT
for i in $(seq 60); do IP=$(grep -a -o 'IP Address: [0-9.]*' "$OUT/serial.txt" 2>/dev/null | tail -1 | cut -d' ' -f3); [ -z "$IP" ] && IP=$(python3 -c "import socket;print(socket.gethostbyname('$NAME.local'))" 2>/dev/null); [ -n "$IP" ] && break; sleep 2; done
[ -n "$IP" ] || { echo "device not found"; exit 1; }
$PY "$R/rbdrive.py" "$IP" "$N" > "$OUT/drive.txt" 2>&1; RC=$?
pkill -f "[s]erial_capture.py $P"
[ -s "$OUT/serial.txt" ] || { echo "serial capture got nothing, crash check invalid"; exit 1; }
CRASH=$(grep -a -c -i 'guru\|panic\|exception\|rst cause' "$OUT/serial.txt")
REJECTED=$(grep -a -c 'No dumper slot' "$OUT/serial.txt")
cat "$OUT/drive.txt"; echo "serial: $(grep -a -c 'ext dumper register called' "$OUT/serial.txt") register calls, $REJECTED rejected, $CRASH crash lines"
if [ "${EXPECT_REGISTER:-0}" = 1 ] && [ "$REJECTED" != 0 ]; then echo "the dumper registration was rejected"; exit 1; fi
[ "$RC" = 0 ] && [ "$CRASH" = 0 ]
@@ -1,103 +0,0 @@
"""Drive the FrameReader simulation builds over the API: press buttons, set selects/numbers, print states.
usage: frdrive.py HOST LOGFILE OP [OP ...]
OP: list | press:NAME | sel:NAME=OPTION | num:NAME=VALUE | wait:SECONDS
"""
import asyncio
import math
import pathlib
import sys
import time
from aioesphomeapi import (
APIClient,
BinarySensorState,
ButtonInfo,
LogLevel,
NumberInfo,
SelectInfo,
SensorInfo,
SensorState,
)
HOST, LOGFILE = sys.argv[1], sys.argv[2]
OPS = sys.argv[3:]
T0 = time.time()
SKIP = {"Heap Free", "Loop Time"}
def stamp() -> str:
return f"{time.time() - T0:7.3f}"
async def main() -> int:
with pathlib.Path(LOGFILE).open("w", encoding="utf-8") as log:
c = APIClient(HOST, 6053, None)
await c.connect(login=True)
info = await c.device_info()
print(f"device {info.name} compiled {info.compilation_time}", flush=True)
ents, _ = await c.list_entities_services()
by_key = {e.key: e for e in ents}
def find(kind: type, name: str):
for e in ents:
if isinstance(e, kind) and e.name == name:
return e
sys.exit(f"no {kind.__name__} named {name!r}")
def on_state(s) -> None:
e = by_key.get(s.key)
if e is None or e.name in SKIP:
return
if isinstance(s, SensorState) and isinstance(e, SensorInfo):
v = "nan" if math.isnan(s.state) else f"{s.state:.2f}"
line = f"{stamp()} SEN {e.name} = {v}"
elif isinstance(s, BinarySensorState):
line = f"{stamp()} BIN {e.name} = {s.state}"
else:
return
print(line, flush=True)
log.write(line + "\n")
states.append(line)
def on_log(msg) -> None:
log.write(f"{stamp()} {msg.message.decode(errors='replace')}\n")
log.flush()
states: list[str] = []
c.subscribe_states(on_state)
c.subscribe_logs(on_log, log_level=LogLevel.LOG_LEVEL_VERBOSE)
await asyncio.sleep(2)
states.clear() # count only states published while the ops ran
for op in OPS:
kind, _, rest = op.partition(":")
if kind == "list":
for e in ents:
print(type(e).__name__, e.name)
continue
if kind == "wait":
await asyncio.sleep(float(rest))
continue
line = f"{stamp()} >>> {op}"
print(line, flush=True)
log.write(line + "\n")
if kind == "press":
c.button_command(find(ButtonInfo, rest).key)
elif kind == "sel":
name, _, value = rest.partition("=")
c.select_command(find(SelectInfo, name).key, value)
elif kind == "num":
name, _, value = rest.partition("=")
c.number_command(find(NumberInfo, name).key, float(value))
else:
sys.exit(f"unknown op {op!r}")
await asyncio.sleep(2.5)
await asyncio.sleep(1)
await c.disconnect()
if any(not op.startswith(("list", "wait")) for op in OPS) and not states:
print("no sensor state was published while the ops ran", flush=True)
return 1
return 0
sys.exit(asyncio.run(main()))
@@ -1,19 +0,0 @@
#!/bin/bash
# usage: run.sh NAME TREE SECONDS OP... flash over serial, capture serial, drive over the API
# Copy this, frdrive.py and the templates/uart_sim files into one scratch directory and run it there.
# env: PORT (the devkit serial port), SC (path to serial_capture.py), PY (checkout python); TREE is the esphome
# checkout to build from
D=$(cd "$(dirname "$0")" && pwd); N=$1; T=$2; S=$3; shift 3; P=${PORT:?set PORT}; PY=${PY:-$T/venv/bin/python}
(cd $T && PYTHONUNBUFFERED=1 timeout 1500 $PY -m esphome run --no-logs $D/$N.yaml --device $P > $D/$N-upload.log 2>&1) || { echo "build or upload failed"; exit 1; }
$PY ${SC:?set SC} $P $S $D/$N-cap.txt > $D/$N-cap.err 2>&1 &
CAP=$!
trap 'kill $CAP 2>/dev/null' EXIT
UP=0
for i in $(seq 1 40); do $PY -c "import socket;socket.create_connection(('$N.local',6053),2)" 2>/dev/null && { UP=1; break; }; sleep 2; done
[ $UP = 1 ] || { echo "device $N.local not reachable on port 6053"; exit 1; }
cd $D && PYTHONUNBUFFERED=1 timeout $((S - 5)) $PY frdrive.py $N.local $N-api.log "$@" > $N-drive.txt 2>&1; RC=$?; echo "drive rc=$RC"
wait $CAP; CAPRC=$?; trap - EXIT
[ "$CAPRC" = 0 ] || { echo "serial capture failed (rc $CAPRC), crash check invalid"; exit 1; }
CRASH=$(grep -acE 'Guru|abort\(\)|rst:0x' $D/$N-cap.txt)
echo "crash lines: $CRASH"
[ "$RC" = 0 ] && [ "$CRASH" = 0 ]
@@ -1,95 +0,0 @@
"""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)
@@ -1,58 +0,0 @@
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
@@ -1,13 +0,0 @@
# 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
@@ -1,13 +0,0 @@
# 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
@@ -1,56 +0,0 @@
#!/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+=($!)
[ -n "$CB" ] && { $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"
@@ -1,3 +0,0 @@
#pragma once
#include <esp_wifi.h>
#include <esp_event.h>
@@ -1,95 +0,0 @@
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);
@@ -1,16 +0,0 @@
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
@@ -1,16 +0,0 @@
esphome:
name: ${name}
esp32:
board: esp32dev
framework:
type: ${framework}
logger:
level: DEBUG
api:
reboot_timeout: 0s
ota:
- platform: esphome
Loaded 100 of 1258 files, more files were not shown because too many files have changed in this diff. Show more