mirror of
https://github.com/esphome/esphome.git
synced 2026-10-24 06:55:37 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a17ddfec99 | ||
|
|
227097a36e | ||
|
|
d7472891f0 | ||
|
|
1080e9d285 | ||
|
|
a04e6a0508 | ||
|
|
8c242a46ee |
No files matched your search
@@ -1,116 +0,0 @@
|
||||
---
|
||||
name: code-review
|
||||
description: Review guidance for ESPHome pull requests. Use this when reviewing a pull request that changes ESPHome Python, C++, or component code, to check it against the project's coding conventions, embedded-systems memory rules, testing requirements, and breaking-change policy.
|
||||
---
|
||||
|
||||
# Reviewing ESPHome pull requests
|
||||
|
||||
ESPHome parses YAML into C++ firmware for memory-constrained microcontrollers
|
||||
(ESP32, ESP8266, RP2040, LibreTiny). Review changes with that in mind: RAM and
|
||||
flash are scarce, and code runs unattended for months.
|
||||
|
||||
`AGENTS.md` in the repository root is the full contributor guide and the
|
||||
authority when it disagrees with this summary. The developer documentation at
|
||||
https://developers.esphome.io explains the component lifecycle and the reasoning
|
||||
behind these rules. This skill lists the concrete things worth flagging in a
|
||||
review; read `AGENTS.md` for the detail behind any item.
|
||||
|
||||
Only raise findings that the diff actually introduces or changes. Do not ask for
|
||||
drive-by cleanup of pre-existing code the PR did not touch.
|
||||
|
||||
## Memory and embedded constraints (highest value)
|
||||
|
||||
Heap allocation after `setup()` is treated as a reliability bug, not a
|
||||
performance nit, because it fragments a small shared heap. Flag:
|
||||
|
||||
- New heap allocation on a hot path or after setup that could be avoided.
|
||||
- `std::vector` where the size is known at compile time (use `std::array`, or
|
||||
`StaticVector<T, N>` when a `push_back` API is needed) or fixed at runtime
|
||||
init (use `FixedVector<T>`).
|
||||
- Listener / child-entity registration lists stored as `std::vector`; these have
|
||||
a compile-time-known count and should use `cg.slot_counter()` plus
|
||||
`StaticVector`.
|
||||
- `std::vector<uint8_t>` for a byte buffer that never grows: prefer
|
||||
`std::unique_ptr<uint8_t[]>` or `std::array`.
|
||||
- `std::map` / `std::set` / `std::unordered_map` for small datasets (1-16
|
||||
elements): a `std::vector` of a small struct with linear search is lighter.
|
||||
- `std::deque` anywhere: it allocates 512-byte blocks and should be avoided.
|
||||
- `std::string` storing a value set once from config: prefer `StringRef` (the
|
||||
literal already lives in flash).
|
||||
- `std::string` / `std::to_string` / string-returning helpers on hot paths where
|
||||
a buffer or view API exists.
|
||||
|
||||
## C++ conventions
|
||||
|
||||
- Include what you use: a file referencing a symbol must include the header that
|
||||
declares it, even if it currently arrives transitively. New or changed uses of
|
||||
a symbol need the matching include.
|
||||
- Prefix all member access with `this->`.
|
||||
- Naming: `lower_snake_case` for functions/methods/variables, `UpperCamelCase`
|
||||
for classes/structs/enums, `UPPER_SNAKE_CASE` for namespace-scope constants,
|
||||
trailing underscore on protected/private fields.
|
||||
- `enum class` values must be prefixed with the enum name in `UPPER_SNAKE_CASE`
|
||||
(e.g. `UARTFlushResult::UART_FLUSH_RESULT_SUCCESS`). Bare names like `SUCCESS`,
|
||||
`FAIL`, or `OK` collide with SDK macros on some platforms and break the build.
|
||||
- Prefer `const`/`enum` over `#define`; `#define` is only for conditional
|
||||
compilation and code-generation sizes.
|
||||
- Never call `millis()` in a `loop()` body; use
|
||||
`App.get_loop_component_start_time()`. A rate-limit gate below ~16 ms (the loop
|
||||
period) does nothing.
|
||||
- Pick the timing primitive by cadence: gated `loop()` under 250 ms,
|
||||
`set_interval` at 500 ms and above.
|
||||
- Do not override a base method to return the value it already returns (e.g.
|
||||
`get_setup_priority()` returning `setup_priority::DATA`).
|
||||
- Wrap string literals passed as printf `%s` args in `LOG_STR_LITERAL()`.
|
||||
- Required, invariant dependencies should be constructor parameters, not setters.
|
||||
- Callback registration methods must be templated (`template<typename F>`), not
|
||||
typed as `std::function`, so lightweight forwarders avoid a heap allocation.
|
||||
- Two-space indent, `using` over `typedef`, wrap at 120 columns.
|
||||
|
||||
## Python conventions
|
||||
|
||||
- Type-annotate every new function signature (params and return), new dataclass
|
||||
fields, and new module-level variables. Import `ConfigType` from
|
||||
`esphome.types`.
|
||||
- Use the walrus operator to avoid a double lookup, e.g.
|
||||
`if (blah := config.get(CONF_BLAH)) is not None:`.
|
||||
- Reuse existing validators from `config_validation.py` (`cv.rename_key`,
|
||||
`cv.has_exactly_one_key`, etc.) via `cv.All(...)` instead of hand-rolling.
|
||||
- `esphome/const.py` is frozen: no new `CONF_` constants there. Define them in
|
||||
the component's own `.py`, or in `esphome/components/const/__init__.py` when
|
||||
shared. The same constant defined in three or more component files fails CI.
|
||||
- State that must persist during code generation goes in `CORE.data` namespaced
|
||||
under the component `DOMAIN` (a `@dataclass`), not module-level mutable globals.
|
||||
- Prefer callback-based triggers via `build_callback_automation()`; only use a
|
||||
`Trigger<Ts...>` subclass when the forwarder needs mutable state.
|
||||
|
||||
## Testing and coverage
|
||||
|
||||
- New and changed lines and branches need test coverage, including defensive
|
||||
early-returns, error paths, and no-op guards. A mocked-out function is not
|
||||
covered; exercise the real call path too.
|
||||
- Component YAML tests live in `tests/components/<component>/`. Never define
|
||||
buses (uart, i2c, spi, modbus) directly in a test file: pull them from
|
||||
`tests/test_build_components/common/` through dict-style `packages:` so CI can
|
||||
group builds. List-style packages or top-level merge keys block grouping.
|
||||
- Config-only checks use the `validate.*.yaml` prefix; compiled checks use
|
||||
`test.*.yaml`.
|
||||
|
||||
## Breaking changes and public API
|
||||
|
||||
- Base classes under `esphome/core/` and documented config options are public
|
||||
API. Undocumented `public` members of a component are internal.
|
||||
- A breaking change needs justification, a migration path in the PR description,
|
||||
and a deprecation window where feasible (`ESPDEPRECATED` in C++,
|
||||
`cv.rename_key(..., removed_in=...)` in Python). Changing a codegen-injected
|
||||
lambda signature is not a breaking change.
|
||||
|
||||
## Process and PR hygiene
|
||||
|
||||
- PR titles start with a `[tag]` prefix: the component name (e.g. `[uart] ...`)
|
||||
or `[core]` for shared code.
|
||||
- Prose in docs, comments, and commit messages should be plain English. Keep
|
||||
inline comments short and only where the code is not self-explanatory; do not
|
||||
restate what the code says.
|
||||
- Verify the PR fills out `.github/PULL_REQUEST_TEMPLATE.md` and adds
|
||||
`CODEOWNERS` entries for a new component.
|
||||
@@ -1,156 +0,0 @@
|
||||
---
|
||||
name: display-test
|
||||
description: Test an ESPHome display driver on a real panel with a camera. Use when a task asks to verify a display (LCD, e-paper, OLED, RLCD) on hardware, check orientation/rotation, partial updates, colours, contrast, or that text and shapes render correctly. Covers finding the USB port, flashing a test pattern, capturing the panel with any camera, and reading the photo.
|
||||
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
|
||||
---
|
||||
|
||||
# Display testing with a camera
|
||||
|
||||
Point a camera at the panel to get visual evidence that a driver renders correctly. Any camera
|
||||
and capture tool works; this skill covers the common ones. `$SKILL` below is this directory
|
||||
(`.agents/skills/display-test`).
|
||||
|
||||
## Ask before using a camera
|
||||
|
||||
A camera can show people and rooms, not only the panel. Before the first capture, ask the user
|
||||
for permission and for which camera to use. List the cameras the host has (the commands below
|
||||
show how), name the one you intend to use, and wait for the user to confirm it. Do not pick a
|
||||
camera yourself, and do not fall back to another camera if the chosen one fails; ask again.
|
||||
|
||||
The permission covers this session and the camera the user named. Ask again for a different
|
||||
camera or in a new session. If the user declines, stop and report that the display was not
|
||||
checked visually.
|
||||
|
||||
## Capturing a frame
|
||||
|
||||
Grab a still image, skipping the first few frames so auto-exposure and white balance settle.
|
||||
Read the JPEG with the Read tool; the image is shown visually.
|
||||
|
||||
### macOS
|
||||
|
||||
The bundled Swift tool uses AVFoundation and avoids the frame-grabbing problems some USB
|
||||
cameras have with other tools:
|
||||
|
||||
```bash
|
||||
mkdir -p /tmp/camsnap /tmp/display-test
|
||||
swiftc -O "$SKILL/scripts/camsnap.swift" -o /tmp/camsnap/camsnap
|
||||
/tmp/camsnap/camsnap <camera-name-substring> /tmp/display-test/after.jpg 30
|
||||
```
|
||||
|
||||
The camera argument is a case-insensitive substring of the name AVFoundation reports. If it does
|
||||
not match, the tool lists the cameras it found, so a run with a name that matches nothing lists
|
||||
the cameras without capturing. Use a substring that matches only the camera the user approved.
|
||||
It creates the output directory if needed and reports encoding or write errors on stderr. Other
|
||||
options include `ffmpeg` with `avfoundation` input, `imagesnap`, or Photo Booth's still capture.
|
||||
|
||||
### Linux
|
||||
|
||||
Use `ffmpeg` with the v4l2 input, `fswebcam`, or `v4l2-ctl`. With `ffmpeg`, `-ss 2` after the
|
||||
input discards the first two seconds of frames while exposure settles:
|
||||
|
||||
```bash
|
||||
mkdir -p /tmp/display-test
|
||||
ffmpeg -f v4l2 -i /dev/video0 -ss 2 -frames:v 1 -y /tmp/display-test/after.jpg
|
||||
# or
|
||||
fswebcam -d /dev/video0 --skip 10 /tmp/display-test/after.jpg
|
||||
```
|
||||
|
||||
List devices with `v4l2-ctl --list-devices`.
|
||||
|
||||
### Windows
|
||||
|
||||
Use `ffmpeg` with the DirectShow input (`-ss 2` skips the first frames, as on Linux), or any
|
||||
camera application that can save a still image:
|
||||
|
||||
```powershell
|
||||
mkdir C:\temp -Force | Out-Null
|
||||
ffmpeg -f dshow -list_devices true -i dummy # find the device name
|
||||
ffmpeg -f dshow -i video="<device name>" -ss 2 -frames:v 1 -y C:\temp\after.jpg
|
||||
```
|
||||
|
||||
### Camera caveats
|
||||
|
||||
- The board may sit at an angle. Do not trust absolute pixel positions or aspect ratios from the
|
||||
photo; judge orientation, ordering and approximate spacing, using the corner markers as
|
||||
references.
|
||||
- Reflections or a glossy cover can brighten one side. Capture again if a region is unclear.
|
||||
- A moving pattern is caught at an arbitrary phase. Take several captures, or use a static marker
|
||||
per position.
|
||||
|
||||
## Board and port
|
||||
|
||||
Find the port; names change on every replug:
|
||||
|
||||
```bash
|
||||
python3 "$SKILL/../hardware-test/scripts/ports.py"
|
||||
```
|
||||
|
||||
Native-USB ESP32-S3/C3/C6/H2 boards show up as `USB JTAG/serial debug unit` and need
|
||||
`logger: hardware_uart: USB_SERIAL_JTAG`.
|
||||
|
||||
## Test pattern
|
||||
|
||||
Write a scratch config outside the checkout. Use one `name:` per board and include:
|
||||
|
||||
- a white background, a black border and a filled square at the centre, drawn in the first
|
||||
update (full-window check and scale);
|
||||
- a 60x20 bar near each corner, one bar per later update with `auto_clear_enabled: false`, so
|
||||
each bar is written by its own partial window. The bars are wider than tall, which shows a
|
||||
90 or 270 degree rotation; the corners exercise the window alignment;
|
||||
- a 20x20 square under the left end of the top-left bar, drawn in the same update, which marks
|
||||
the top-left corner and shows a 180 degree rotation or a mirrored image.
|
||||
|
||||
Use `Color::BLACK` and `Color::WHITE` in lambdas. Do not use the old `COLOR_OFF`/`COLOR_ON`
|
||||
constants; black must mean black.
|
||||
|
||||
A ready template is in `$SKILL/templates/display-pattern.yaml`. Substitute the display platform,
|
||||
pins and (for a driver with fonts) a font. The marker pattern needs no font.
|
||||
|
||||
## Build, flash, capture
|
||||
|
||||
Run from the worktree under test so `python -m esphome` imports the checkout, not an installed
|
||||
copy:
|
||||
|
||||
```bash
|
||||
cd <worktree>
|
||||
python3 -c "import esphome; print(esphome.__file__)" # must print the worktree path
|
||||
PYTHONUNBUFFERED=1 python3 -m esphome compile /tmp/display-test/display-pattern.yaml
|
||||
PYTHONUNBUFFERED=1 python3 -m esphome upload /tmp/display-test/display-pattern.yaml \
|
||||
--device /dev/cu.usbmodemXXXX
|
||||
sleep 6 # boot plus a few update intervals
|
||||
<capture command> /tmp/display-test/after.jpg
|
||||
```
|
||||
|
||||
The device path differs by OS and host; use the path printed by `ports.py`. If the USB console
|
||||
wedges during flashing (esptool `No serial data received`), replug the board and retry. A board
|
||||
powered only by a battery may need the USB cable for flashing; the panel keeps its image when
|
||||
power is removed, which is useful for checking that an image is bistable.
|
||||
|
||||
## What to check
|
||||
|
||||
1. **Orientation**: the extra square sits under the bar in the expected top-left corner. If it is
|
||||
in another corner, the image is rotated or mirrored. Test `rotation:` values with the same
|
||||
pattern. The logical width and height swap at 90 and
|
||||
270 degrees, so the 60x20 corner bars should then appear taller than wide on the physical
|
||||
panel.
|
||||
2. **Coverage**: the border touches all four edges, with no dead rows or columns at the edges.
|
||||
3. **Partial updates**: with `auto_clear_enabled: false`, draw one marker per update. Each should
|
||||
appear exactly at its requested position with no smearing, offset or mirrored placement.
|
||||
Include all four corners.
|
||||
4. **Text and contrast**: sharp glyphs, correct polarity (black text on white, not inverted), no
|
||||
ghosting from the previous frame.
|
||||
5. **Speed**: if the driver logs transfer sizes, check that a full refresh and a partial window
|
||||
take the expected times.
|
||||
|
||||
Record the build commit, board, config, and the captured image path when reporting results.
|
||||
|
||||
## When a partial update looks wrong
|
||||
|
||||
Take a marker-only capture before assuming the mapping is wrong: the camera's perspective makes
|
||||
absolute positions deceptive. If markers land in mirrored positions, the controller's address
|
||||
order (`MADCTL` MX/MY/MV) or the RAM block mapping is inverted for the window; verify the
|
||||
full-frame path separately, then fix the window computation.
|
||||
|
||||
## Add findings
|
||||
|
||||
Add new capture tools, panel quirks, or recovery steps here so the next session starts ahead.
|
||||
@@ -1,71 +0,0 @@
|
||||
// camsnap <camera name substring> <output.jpg> [frames to skip]
|
||||
// macOS only: grabs one frame from an AVFoundation camera after letting exposure settle.
|
||||
// See SKILL.md for capture tools on other systems.
|
||||
import AVFoundation
|
||||
import AppKit
|
||||
import CoreImage
|
||||
|
||||
let args = CommandLine.arguments
|
||||
guard args.count >= 3 else {
|
||||
FileHandle.standardError.write("usage: camsnap <camera name> <out.jpg> [skip]\n".data(using: .utf8)!)
|
||||
exit(2)
|
||||
}
|
||||
let wanted = args[1].lowercased()
|
||||
let outPath = args[2]
|
||||
let skip = args.count > 3 ? Int(args[3]) ?? 30 : 30
|
||||
|
||||
let discovery = AVCaptureDevice.DiscoverySession(
|
||||
deviceTypes: [.external, .builtInWideAngleCamera], mediaType: .video, position: .unspecified)
|
||||
guard let device = discovery.devices.first(where: { $0.localizedName.lowercased().contains(wanted) }) else {
|
||||
let names = discovery.devices.map { $0.localizedName }.joined(separator: ", ")
|
||||
FileHandle.standardError.write("no camera matching '\(wanted)'; found: \(names)\n".data(using: .utf8)!)
|
||||
exit(1)
|
||||
}
|
||||
|
||||
final class Grabber: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
|
||||
var seen = 0
|
||||
let skip: Int
|
||||
let out: String
|
||||
init(skip: Int, out: String) { self.skip = skip; self.out = out }
|
||||
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer,
|
||||
from connection: AVCaptureConnection) {
|
||||
seen += 1
|
||||
guard seen > skip, let pixels = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
|
||||
let image = CIImage(cvPixelBuffer: pixels)
|
||||
let rep = NSBitmapImageRep(ciImage: image)
|
||||
guard let jpeg = rep.representation(using: .jpeg, properties: [.compressionFactor: 0.9]) else {
|
||||
FileHandle.standardError.write("failed to encode \(out) as JPEG\n".data(using: .utf8)!)
|
||||
exit(1)
|
||||
}
|
||||
let url = URL(fileURLWithPath: out)
|
||||
try? FileManager.default.createDirectory(
|
||||
at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
do {
|
||||
try jpeg.write(to: url)
|
||||
} catch {
|
||||
FileHandle.standardError.write("failed to write \(out): \(error)\n".data(using: .utf8)!)
|
||||
exit(1)
|
||||
}
|
||||
print("saved \(out) after \(seen) frames")
|
||||
exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
let session = AVCaptureSession()
|
||||
session.sessionPreset = .high
|
||||
guard let input = try? AVCaptureDeviceInput(device: device), session.canAddInput(input) else {
|
||||
FileHandle.standardError.write("cannot open \(device.localizedName)\n".data(using: .utf8)!)
|
||||
exit(1)
|
||||
}
|
||||
session.addInput(input)
|
||||
let output = AVCaptureVideoDataOutput()
|
||||
output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]
|
||||
let grabber = Grabber(skip: skip, out: outPath)
|
||||
output.setSampleBufferDelegate(grabber, queue: DispatchQueue(label: "camsnap"))
|
||||
session.addOutput(output)
|
||||
session.startRunning()
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 15) {
|
||||
FileHandle.standardError.write("timed out waiting for frames\n".data(using: .utf8)!)
|
||||
exit(1)
|
||||
}
|
||||
RunLoop.main.run()
|
||||
@@ -1,43 +0,0 @@
|
||||
# Display test pattern: corner markers, centre reference and partial-update markers.
|
||||
# Replace the display platform and pins with the driver under test.
|
||||
esphome:
|
||||
name: display-pattern
|
||||
|
||||
esp32:
|
||||
board: esp32-s3-devkitc-1
|
||||
framework:
|
||||
type: esp-idf
|
||||
|
||||
logger:
|
||||
hardware_uart: USB_SERIAL_JTAG
|
||||
level: DEBUG
|
||||
|
||||
spi:
|
||||
clk_pin: GPIO11
|
||||
mosi_pin: GPIO12
|
||||
|
||||
display:
|
||||
- platform: st7305
|
||||
id: test_display
|
||||
cs_pin: GPIO40
|
||||
dc_pin: GPIO5
|
||||
reset_pin: GPIO41
|
||||
update_interval: 1s
|
||||
auto_clear_enabled: false
|
||||
lambda: |-
|
||||
static int frame = 0;
|
||||
if (frame == 0) {
|
||||
it.fill(Color::WHITE);
|
||||
it.rectangle(0, 0, it.get_width(), it.get_height(), Color::BLACK);
|
||||
it.filled_rectangle(it.get_width() / 2 - 10, it.get_height() / 2 - 10, 20, 20, Color::BLACK);
|
||||
} else if (frame == 1) {
|
||||
it.filled_rectangle(20, 20, 60, 20, Color::BLACK);
|
||||
it.filled_rectangle(20, 50, 20, 20, Color::BLACK);
|
||||
} else if (frame == 2) {
|
||||
it.filled_rectangle(20, it.get_height() - 40, 60, 20, Color::BLACK);
|
||||
} else if (frame == 3) {
|
||||
it.filled_rectangle(it.get_width() - 80, 20, 60, 20, Color::BLACK);
|
||||
} else if (frame == 4) {
|
||||
it.filled_rectangle(it.get_width() - 80, it.get_height() - 40, 60, 20, Color::BLACK);
|
||||
}
|
||||
frame++;
|
||||
@@ -1,165 +0,0 @@
|
||||
---
|
||||
name: hardware-test
|
||||
description: Test an ESPHome change on real boards over USB. Use this whenever a task asks to test, verify, reproduce, bench, A/B or soak a pull request, a branch or a crash on hardware, or mentions flashing, serial logs, esphome upload, a captive portal or fallback AP test, or results to post on a PR. Covers finding the serial ports, building from the right checkout, flashing each chip family (including the LibreTiny kits that stock tools cannot flash), bounded log capture, proven test flows and how to report results.
|
||||
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
|
||||
---
|
||||
|
||||
# Hardware testing
|
||||
|
||||
The goal of a hardware test is evidence a reviewer can trust: which build ran on which board, what was
|
||||
driven, what the logs show, and the same flow on a `dev` build when a quirk could be pre-existing.
|
||||
`$SKILL` below is this directory (`.agents/skills/hardware-test`).
|
||||
|
||||
## Ground rules
|
||||
|
||||
1. **Serial ports cannot be shared.** One bounded capture per port, stopped before any flash on that
|
||||
port, never an open-ended `esphome logs`. Stop a capture with `pkill -f "[s]erial_capture.py <port> "`,
|
||||
naming the port so a capture on another board survives; the bracket keeps the pattern from matching
|
||||
the shell that runs it. When more than one agent session shares the bench, run a copy of the script
|
||||
under a session-specific name (`cap<topic>.py`) so another session's `pkill` cannot take your capture
|
||||
down. Never run `esphome logs` in a `while true` loop: the loop respawns it and holds the port.
|
||||
2. **Credentials stay local.** Put a `secrets.yaml` next to the scratch configs and reference it with
|
||||
`!secret`. A copy of a device's own config keeps using the secrets file next to that config: two
|
||||
checkouts can hold different networks, and the wrong one leaves the device unreachable after the OTA. Never paste a config with credentials into a PR, never commit scratch configs or logs.
|
||||
3. **Build from the tree under test.** `python -m esphome` puts the current directory first on
|
||||
`sys.path`, so run it with the checkout or worktree as the working directory and pass the yaml by
|
||||
its absolute path. A venv `esphome` entry point may import an installed snapshot instead of the
|
||||
checkout. Confirm with `python -c 'import esphome; print(esphome.__file__)'`, and for an A/B grep
|
||||
the build's `src/` for the change before trusting any number. Tool calls sent together share one
|
||||
shell, so a `cd` in one can land another's compile in the wrong tree: pass `PYTHONPATH=<worktree>` on
|
||||
every compile and upload command and print `esphome.__file__` into the compile log.
|
||||
4. **PR build and baseline build get different `name:` values.** Builds share
|
||||
`.esphome/build/<name>`, so the same name means `esphome upload` can flash the wrong binary. Saved
|
||||
Wi-Fi credentials are keyed by the config hash when the config has `networks:`, so a test that must
|
||||
start unprovisioned gets a fresh name every run. A config with `ap:` only and no `networks:` uses one
|
||||
fixed key shared by every such config on the board, so a new name does not help there: wipe once at
|
||||
boot with an `on_boot` lambda that resets the preferences and saves a marker key
|
||||
(`templates/dut-ap-only-wipe-once-bk72xx.yaml`).
|
||||
5. **Flash and RAM deltas are measured against the PR's merge base** (`git merge-base origin/dev HEAD`
|
||||
checked out in a throwaway worktree), with the baseline commit named in the table. When a delta
|
||||
looks odd, diff symbol sizes (`nm -S -C --size-sort` from the matching toolchain) before quoting it.
|
||||
6. **Prove a quirk is pre-existing before blaming the PR:** run the identical flow on a `dev` build in
|
||||
the same session and say so in the results.
|
||||
7. **Pipe safely.** Set `PYTHONUNBUFFERED=1` on any `esphome run` or `esphome logs` whose output is
|
||||
piped, or lines land minutes late. Bound every long command with `timeout` (coreutils) or
|
||||
`perl -e 'alarm shift; exec @ARGV' <seconds> <command>` on macOS without it.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. **Find the boards:** `python $SKILL/scripts/ports.py` (any Python with pyserial, for example the
|
||||
ESPHome venv). Port names follow the USB hub port and change on every replug, so never reuse a name
|
||||
from an earlier session. CH340 adapters (D1 mini, BW15 kit, BK7238, CB3S) all look the same; tell
|
||||
them apart with a 10 s capture using `serial_capture.py --reset` (ESP8266 prints its ROM banner at
|
||||
74880 baud, LibreTiny boards print `[LT]` and ESPHome lines, BK7238 prints its bootloader version).
|
||||
`ports.py --wait 2e8a` blocks until a Pico re-enumerates.
|
||||
2. **Make a scratch directory** outside the checkout, with `secrets.yaml` and the templates you need.
|
||||
One yaml per board per variant, file name equal to `name:`.
|
||||
3. **Compile** in the right tree:
|
||||
`(cd <worktree> && PYTHONUNBUFFERED=1 timeout 1500 python -m esphome compile <abs yaml> > <name>-compile.log 2>&1)`.
|
||||
Keep the RAM and flash lines at the end. Two ESP-IDF or two LibreTiny builds at the same time race
|
||||
over tool caches; run them one at a time.
|
||||
4. **Flash** per chip family (table below). Stop the capture on that port first.
|
||||
5. **Capture** with `serial_capture.py PORT SECONDS OUT` in the background, then poll the file with
|
||||
`grep` in an `until ... sleep 2` loop with a cap. USB CDC boards (Pico, nRF52, native USB ESP32)
|
||||
drop the port on reboot; the script reopens it until its deadline.
|
||||
6. **Drive** the test: a second board running a client config, `curl`, an aioesphomeapi script that
|
||||
presses a template button and subscribes to logs, MQTT publishes, or `interval:` and `on_boot:`
|
||||
automations in the config itself.
|
||||
7. **Analyze** with `grep -a -c` counts over the capture and keep an `-events.txt` extract of the lines
|
||||
that matter. Decode crashes with the platform's `addr2line` (see `reference/boards.md`).
|
||||
8. **Report** on the PR as a table: build SHA, board and framework, what was driven, counts, result,
|
||||
plus the `dev` control row and the exact flow in a `<details>` block. No credentials, no port names,
|
||||
no IP addresses.
|
||||
|
||||
## Flashing by chip family
|
||||
|
||||
| Board | Flash | Log |
|
||||
|---|---|---|
|
||||
| ESP8266 D1 mini (CH340) | `python -m esphome upload <yaml> --device <port>` | `serial_capture.py` at 115200; `esphome logs` on some CH340s emits garbage after the RTS reset. A failed esptool write can wedge the adapter until the board is replugged. `esptool erase_flash` before a test that needs an unprovisioned device: the preference sector survives a reflash |
|
||||
| ESP32 devkit (CP2102 or CH340) | `esphome upload --device <port>`, ESP-IDF or Arduino | `serial_capture.py`. Default Wi-Fi light sleep delays API driven actions by seconds; judge timing from device logs. `power_save_mode: none` for OTA overlap tests |
|
||||
| ESP32-S3, C3, C6, H2 native USB | `esphome upload --device /dev/cu.usbmodem*` | `logger: hardware_uart: USB_SERIAL_JTAG`. The USB console can wedge when the app takes over the console (0 bytes, esptool `No serial data received`); replug, or watch through `esphome logs --device <name>.local` |
|
||||
| Pico W / Pico 2 W | `esphome upload --device <port>` (1200 baud touch); first flash ever via BOOTSEL and `--device /Volumes/RPI-RP2` or `RP2350` | port re-enumerates after upload: `ports.py --wait 2e8a` then capture |
|
||||
| BW15 kit (RTL8720CF, rtl87xx) | `~/.platformio/penv/.libretiny/bin/python $SKILL/scripts/flash_rtl87xx_kit.py flash write -d <port> <build>/.pioenvs/<name>/*.uf2`. Plain `esphome upload` and plain ltchiptool time out because opening the port asserts DTR/RTS and holds the chip in reset | `serial_capture.py --released`, never `esphome logs` |
|
||||
| BK7238 / CB3S (bk72xx, RTS on CEN) | `~/.platformio/penv/.libretiny/bin/python $SKILL/scripts/flash_bk72xx.py flash write -d <port> <uf2>` (about 75 s) | logs are on UART2 by default; `logger: hardware_uart: UART1` puts them on the flashing adapter. `serial_capture.py --reset` gives a chip-enable reset; a plain open may or may not reset it, check for the bootloader banner |
|
||||
| LN882H | ltchiptool forces 1 Mbaud for writes; weak adapters need `LN882H_YM_BAUDRATE` patched to 115200 in the penv's `ln882htool.py`; short BOOT to GND while the tool connects | OTA after the first flash |
|
||||
| nRF52840 Dongle (PCA10059) | Nordic `nrfutil nrf5sdk-tools dfu usb-serial` on the bootloader port, or `dfu: true` in the config so the 1200 baud touch pin-resets into the bootloader; adafruit-nrfutil is refused | app has two CDC ports, ESPHome log on the second |
|
||||
| Adafruit-style nRF52 (UF2 bootloader) | `UF2BOOT` volume or adafruit-nrfutil; `dfu: true` works through GPREGRET | single CDC port |
|
||||
| Any reachable device | `esphome upload <yaml> --device <ip or name.local>`; `--file <bin>` for a prebuilt image | `esphome logs --device <ip>` bounded with `timeout` |
|
||||
|
||||
ESP-IDF OTA image: `.esphome/build/<name>/build/firmware.ota.bin`. LibreTiny OTA port is 8892.
|
||||
|
||||
## Scripts in `$SKILL/scripts`
|
||||
|
||||
- `ports.py`: list ports with VID:PID, product, serial and a board guess; `--wait VID[:PID]`,
|
||||
`--product NAME`, `--serial SN` (one specific board, whatever path it comes back under) and
|
||||
`--serial-of PORT` (the serial number behind a path).
|
||||
- `serial_capture.py PORT SECONDS OUT [--baud] [--released] [--reset] [--append] [--ms]`: bounded timestamped
|
||||
capture (`--ms` adds milliseconds for timing work), ANSI stripped, `LOG_SECRET` text written as `<secret>`, reopens a vanished port, exits at the
|
||||
deadline. OUT is truncated unless `--append` is given, so counts over it cover one run.
|
||||
- `flash_rtl87xx_kit.py`: ltchiptool wrapper for the BW15 kit whose CH340 drives CEN (RTS) and the boot
|
||||
strap (DTR). `flash read` needs the family `realtek-ambz2`; `flash write` does not.
|
||||
- `flash_bk72xx.py`: ltchiptool wrapper for BK72xx boards whose RTS drives CEN. It misses the link now
|
||||
and then; retry up to three times.
|
||||
- `api_button.py HOST KEY list|press NAME [...]`: list a device's template buttons or press them over the API; the
|
||||
recipes drive their test configs with it.
|
||||
- `wifisave_hammer.sh KIND DUT_PORT DUT_YAML DUT_TREE CLIENT_PORT CLIENT_YAML CLIENT_TREE [SETTLE]`:
|
||||
the fallback AP plus captive portal hammer end to end (compile, flash, capture, counts) with the
|
||||
templates below. KIND is `esp`, `pico`, `bw15` or `bk`. It ends with `RESULT PASS` (exit 0),
|
||||
`RESULT FAIL` (exit 3: a crash, a reboot after the AP came up, or the device never joined the network),
|
||||
`RESULT INVALID`
|
||||
(exit 2: a precondition was missed, the stimulus was insufficient, or a capture did not last the run)
|
||||
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/`
|
||||
(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), `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), `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).
|
||||
|
||||
## Templates in `$SKILL/templates`
|
||||
|
||||
- `dut-fallback-ap.yaml` (package): a device that never finds its network, falls back to its AP and
|
||||
serves the captive portal. `example-dut.yaml` is the per-run file with the platform block.
|
||||
- `client-wifisave.yaml` (package): joins that AP, posts N bogus `/wifisave` requests, then the real
|
||||
credentials from `!secret`. `example-client.yaml` is the per-run file. `bogus_saves: "1"` gives a
|
||||
plain provisioning check.
|
||||
- Per-topic device configs, each described in `reference/recipes/<component>.md`: `online-image-dut.yaml`,
|
||||
`usb-cdc-acm-dongle-dut.yaml`, `nrf52-preferences-dut.yaml`, `rtsp-waveshare-s3-eth-dut.yaml`,
|
||||
`waveshare-s3-eth-camdiag.yaml`, `s31-cse7766-dut.yaml`, `nrf52-coredump-crash-dut.yaml`,
|
||||
`bk72xx-rtc-prefs-dut.yaml`, `bk72xx-crash-probe-dut.yaml`, `dut-ap-only-wipe-once-bk72xx.yaml`,
|
||||
`homeassistant-light-dut.yaml`, `deep-sleep-outgoing-dut.yaml`, `outgoing-wifi-drop-dut.yaml`,
|
||||
`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 `uart_sim/` (simulator header, common package and per-build parts).
|
||||
|
||||
## When something looks wrong
|
||||
|
||||
- A capture stopped early or a line is missing: check the timestamps before trusting it.
|
||||
- A script that pipes into `tee` never ends although its work is done: a background command written as
|
||||
`(cd dir && server & echo $!)` backgrounds the whole `cd && server` list, so a shell stays behind holding the
|
||||
pipe open and `$!` is that shell, not the server. Write `(cd dir && exec server > out 2>&1 < /dev/null) &`.
|
||||
- The client never joins the AP: another board may still run an AP with the same SSID, or the device
|
||||
booted with saved credentials because the name was reused. One AP device at a time on the bench.
|
||||
- Builds come out byte-identical between branches: the wrong tree was imported (rule 3). The reverse
|
||||
too: two binaries that differ only in the build timestamp and in `__LINE__` values of log calls below
|
||||
the changed code are the same build; map the offsets with `objdump -h` and `addr2line` first.
|
||||
- A boot the host cannot capture (a power cut, an OTA-only board): keep the boot report in a flash
|
||||
preference and repeat it in a periodic alive line, as `scripts/libretiny_prefs/ltprefs.hpp` does.
|
||||
- Multicast from the host never arrives on some access points: test it device to device. Broadcast
|
||||
is lossy under Wi-Fi power save, unicast is not. Throttle UDP floods to a fixed packet rate.
|
||||
- The merge base comes from a freshly fetched `origin/dev`; a stale local `dev` puts dependency bumps into the
|
||||
PR diff and builds the control from the wrong commit.
|
||||
- A `.local` name can stop resolving in the middle of a run; keep the address from the boot log and drive by it.
|
||||
- `wc -l` pads its count on macOS, so `tail -n +$n0` needs `$((n0+0))` or an arithmetic expansion.
|
||||
- `api:` reboots a board after 15 min without a client: `reboot_timeout: 0s` on `api:` and `mqtt:` for
|
||||
soak tests.
|
||||
|
||||
`reference/boards.md` has per-chip facts and crash decoding; `reference/recipes/` has the proven
|
||||
flows. Add new findings there.
|
||||
@@ -1,205 +0,0 @@
|
||||
# Board facts
|
||||
|
||||
Ports are not listed on purpose: they follow the USB hub port and change on every replug. Run
|
||||
`scripts/ports.py`.
|
||||
|
||||
## ESP8266 (D1 mini, NodeMCU, CH340 or CP2102)
|
||||
|
||||
- Opening the port usually resets the board through DTR, but not always; `serial_capture.py --reset`
|
||||
pulses RTS to capture from boot. 74880 baud shows the ROM boot messages (`rst cause`, `boot mode`).
|
||||
- UART0 can be looped back onto itself (`USC0(0) |= (1 << UCLBE)` in an `on_boot` lambda) so a UART
|
||||
component is testable without its device: frames written with `uart.write` arrive on RX. Log over the
|
||||
API with `logger: baud_rate: 0`, since the serial port carries the component's bytes.
|
||||
- `esphome logs` on some CH340s emits thousands of duplicated garbage lines right after the RTS reset;
|
||||
a plain pyserial capture at 115200 is reliable.
|
||||
- A failed esptool write can wedge the adapter (`termios` error 22, or an open that hangs) until replug.
|
||||
- The preference sector survives a reflash: a provisioned API key or saved Wi-Fi credentials stay
|
||||
active. `esptool erase_flash` gives a clean device.
|
||||
- `Panic core_esp8266_main.cpp:191 __yield` with `ctx: sys` means a yield from lwIP context (a web
|
||||
handler, an lwIP callback). Decode stacks with
|
||||
`xtensa-lx106-elf-addr2line -e <build>/.pioenvs/<name>/firmware.elf -f -C -i <addr...>` from the
|
||||
toolchain under `~/.platformio/packages/toolchain-xtensa/bin/` (PlatformIO builds) or the ESPHome
|
||||
cache directory (native toolchain builds).
|
||||
- Constant data lives in RAM unless marked `PROGMEM`; with 80 KB of RAM a few hundred bytes are worth a
|
||||
row in the PR.
|
||||
- AsyncMqttClient drops inbound topics over 128 characters; topics of 255 or more wrap a counter and
|
||||
stall the link until the broker drops TCP.
|
||||
|
||||
## ESP32 classic devkit
|
||||
|
||||
- Takes ESP-IDF and Arduino. Default Wi-Fi light sleep delays API driven actions by up to 6 s; judge
|
||||
timings from device logs, not from the host. `power_save_mode: none` for OTA overlap tests (an IDF web
|
||||
upload of 739 KB took 107 s with power save and 45 s without).
|
||||
- Receives only a few percent of IPv6 multicast on some access points with power save on; a raw lwIP
|
||||
socket loses the same, so that is the AP or driver, not a PR.
|
||||
- Decode with `xtensa-esp32-elf-addr2line` from the IDF tools directory against
|
||||
`<build>/.pioenvs/<name>/firmware.elf` (PlatformIO) or `<build>/build/<name>.elf` (IDF native).
|
||||
- Clean reboot between runs with the capture stopped: `esptool --after hard_reset chip_id`.
|
||||
- Trigger a forced crash only after the app is marked valid (45 s after boot is plenty), never on an
|
||||
image still pending OTA rollback.
|
||||
- Signed OTA testing: build with `esp32.framework.advanced.signed_ota_verification.verification_keys`
|
||||
under a different name, sign with `python -m espsecure sign_data --version 2 --keyfile
|
||||
tests/components/esp32/dummy_signing_key.pem`, upload with `esphome upload --file`. The verifier
|
||||
refuses unsigned images afterwards, so restore with a signed plain build.
|
||||
|
||||
## ESP32-S3, C3, C6, H2 with native USB
|
||||
|
||||
- `/dev/cu.usbmodem*`, esptool works, `logger: hardware_uart: USB_SERIAL_JTAG`.
|
||||
- The USB console can die at the moment the app takes over the console during a reboot (log stops after
|
||||
`Disabling RNG early entropy source`, then 0 bytes, esptool reports `No serial data received`). Only a
|
||||
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)
|
||||
|
||||
- The CDC port re-enumerates after every reboot and after `esphome upload` (1200 baud touch). Re-detect
|
||||
with `ports.py --wait 2e8a` before capturing; `serial_capture.py` reopens on its own if the port
|
||||
vanishes mid-capture.
|
||||
- First flash ever: BOOTSEL, then `esphome upload --device /Volumes/RPI-RP2` (or `RP2350`).
|
||||
- arduino-pico creates the lwIP netif in `WiFi.begin()`, so any IGMP join during component setup fails;
|
||||
joins must wait for `network::is_connected()`.
|
||||
- Parallel Pico builds race on package extraction after a PlatformIO package wipe; one at a time.
|
||||
- An RTS pulse from pyserial does not reset the board; reboot with `App.safe_reboot()` or the touch.
|
||||
|
||||
## BW15 kit (RTL8720CF, LibreTiny rtl87xx)
|
||||
|
||||
- The kit's CH340 wires RTS to CEN and DTR to PA00 (boot strap). A plain pyserial open asserts both and
|
||||
holds the chip in reset, which is why `esphome upload`, plain `ltchiptool` and `esphome logs` all fail
|
||||
("Timeout while linking", or silence). `scripts/flash_rtl87xx_kit.py` sets DTR high and RTS released
|
||||
on every open, pulses RTS once so the ROM answers `ping`, and after the command drops DTR and pulses
|
||||
RTS to boot the app. Run it with the PlatformIO LibreTiny penv Python.
|
||||
- `flash write -d <port> <uf2>` takes no family argument; `flash read -d <port> -s 0 -l <len>
|
||||
realtek-ambz2 <out>` does.
|
||||
- Capture with `serial_capture.py --released`. The ESPHome log is on the flashing UART already.
|
||||
- The macOS CH340 driver only pushes DTR/RTS to the wire once a session has driven them, so the first
|
||||
plain open after a replug streams logs and the second is silent; always open with the lines released.
|
||||
- Driver quirks seen on `dev`: `WiFi.begin` can refuse the real network on the first try after bogus
|
||||
credentials (it connects after two cooldowns); right after connecting while the AP is still up the
|
||||
driver can bus-fault in `rtw_is_adapter_up` (`R0 = 0xdeadbeef`) and reboot; the AP restarts on every
|
||||
STA retry, so stations cannot stay joined; `WiFi.begin` fails synchronously for an absent network and
|
||||
lands in a cooldown at once; connecting blocks the loop 2.5 to 4.1 s.
|
||||
- Decode faults with `arm-none-eabi-addr2line -e <build>/.pioenvs/<name>/raw_firmware.elf -f -C -i <PC>`
|
||||
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)
|
||||
|
||||
- Stock ltchiptool closes and reopens the port after its reset, and pyserial raises both lines on open,
|
||||
holding CEN low through the BootROM window. `scripts/flash_bk72xx.py` opens with both released and
|
||||
pulses the reset right before the link checks. A write takes about 75 s. Only a CEN or power reset
|
||||
reaches the downloader; no software reboot does.
|
||||
- ESPHome logs on UART2 by default; `logger: hardware_uart: UART1` puts them on the flashing adapter.
|
||||
- Opening the port may reset the chip (bootloader banner on open) or may not, depending on the adapter and
|
||||
what pyserial does with DTR and RTS; `serial_capture.py --reset` pulses RTS on CEN and always does, and
|
||||
`lt_get_reboot_reason()` reports that as Power-On. Check for the banner at the start of a capture before
|
||||
assuming either.
|
||||
- `flash_bk72xx.py` misses the link now and then (`Timed out attempting to link with chip`); retry up to 3
|
||||
times before suspecting the board.
|
||||
- Crashes: `__builtin_trap()` and a call into unmapped memory both end as an undefined-instruction trap
|
||||
(`bk_misc_get_start_type()` 6, `lt_get_reboot_reason()` Crash); reads, unaligned loads and stores to
|
||||
unmapped addresses never fault on the ARM968. Without Wi-Fi the SDK trap handler spins with interrupts off
|
||||
for 10 s and the hardware watchdog resets the chip. With Wi-Fi connected a dev build hangs forever after a
|
||||
crash, and never resets from a plain `portDISABLE_INTERRUPTS(); while (1) {}` either: the boot-time
|
||||
watchdog is dead once Wi-Fi is up, for any lockup. The crash handler fix (#21012) re-arms the watchdog
|
||||
from its wrapper, after which the reboot comes within a second (BK7238 and BK7231N).
|
||||
- The SDK prints nothing on UART1 under `sdk_silent: all`; the bootloader then prints the banked
|
||||
`cpsr/spsr/r13/r14` of SVC, IRQ, FIQ and SYS plus `ST:` (the retention register) before `go os_addr`.
|
||||
A CEN or power reset wipes ITCM (reads `0xaaaaaaaa`), so only a watchdog reset keeps a record there. What
|
||||
survives that reboot on the BK7238: ITCM (`0x3F0000..0x3F4000`) and the top 96 KB of SRAM
|
||||
(`0x428000..0x440000`, the heap); the bootloader zeroes SRAM up to about `0x420000` and rewrites
|
||||
`0x400024..0x4000FF` with its own register dump every boot, so neither a `.noinit` after `.bss` nor the
|
||||
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.
|
||||
- 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.
|
||||
|
||||
## BW16 kit (RTL8720DN, AmebaD)
|
||||
|
||||
- The kit's own USB-C (CH340) is on LOG_UART and flashes fine. Its two-transistor circuit resets while
|
||||
RTS alone is asserted and straps BURN while DTR alone is; both asserted does nothing. ROM entry is
|
||||
esptool's classic sequence (`dtr:false,rts:true` 100 ms, `dtr:true,rts:false` 400 ms, both false); the
|
||||
first pulse after a replug can be lost, retry up to three times.
|
||||
- Any reopen resets the chip, 460800 is flaky, 115200 is solid: one open per session, in-place baud
|
||||
changes only. The ROM and the loader NAK continuously while idle, so ACK scans must drain first.
|
||||
- The AmebaD core has no mDNS responder (`mdns: disabled: true`).
|
||||
|
||||
## LN882H
|
||||
|
||||
- ltchiptool forces 1 Mbaud for writes; adapters that cannot hold it fail with "Timeout while linking"
|
||||
or die mid-write. Patch `LN882H_YM_BAUDRATE` in the penv's `ltchiptool/soc/ln882h/util/ln882htool.py`
|
||||
to 115200 (lost on reprovision). Weak 3.3 V from the adapter: feed the module's 5 V pad instead. Short
|
||||
BOOT to GND while the tool connects. OTA afterwards.
|
||||
- `USE_WIFI_AP_EXCLUSIVE` (one radio mode at a time) exists only on LN882x; compile-check changes there.
|
||||
|
||||
## nRF52840
|
||||
|
||||
- Nordic PCA10059 dongle: the factory Open DFU bootloader enumerates as `1915:521F` on its own port
|
||||
name; the app as `2FE3:0100` with two CDC ports, ESPHome log on the second. Only Nordic
|
||||
`nrfutil nrf5sdk-tools` works (`pkg generate --hw-version 52 --sd-req 0x00 --application-version 1
|
||||
--application zephyr.hex app.zip`, then `dfu usb-serial -pkg app.zip -p <port>`); ESPHome downloads
|
||||
it on the first build. GPREGRET does not enter the bootloader; a pin reset through P0.19 does, which
|
||||
`dfu: true` wires up on this board. A pulsing red LED means bootloader; the side RESET button
|
||||
re-enters it.
|
||||
- Makerdiary MDK USB dongle: UF2 bootloader without SoftDevice, app at 0x1000, `UF2BOOT` volume,
|
||||
adafruit-nrfutil, GPREGRET 0x57 works. RGB LED active low (red P0.23, green P0.22, blue P0.24),
|
||||
button P0.18.
|
||||
- Adafruit ItsyBitsy nRF52840 Express (UF2 bootloader with S140, bootloader port `239a:0051` plus an
|
||||
`ITSY840BOOT` volume): the board DTS already has `cdc_acm_uart0`, so the logger port is the first CDC
|
||||
port and a `usb_cdc_acm` interface 1 the second. A `dfu: true` build enters the bootloader on the
|
||||
1200 bps touch (an app without it needs a double tap on RESET); `adafruit-nrfutil` over the bootloader
|
||||
serial port can fail, copying `.pioenvs/<name>/zephyr/zephyr.uf2` to the volume works (the copy reports
|
||||
an I/O error as the board reboots, which is normal). Reboot a running `dfu: true` app with a 2001 bps touch.
|
||||
- The PCA10059 board DTS already defines a `cdc_acm_uart` node, so every ESPHome CDC port is one USB port
|
||||
later than its number (log on `cdc_acm_uart0` is the second port). A third CDC instance needs
|
||||
`CONFIG_USB_MAX_NUM_TRANSFERS` above 4 or it never moves data (see `recipes/usb_cdc_acm.md`).
|
||||
- USB CDC boot output: the Zephyr legacy stack's `cdc_acm` TX ring is 1 KB and `uart_poll_out` drops when it
|
||||
is full, so anything printed in one burst beyond about 1 KB (a coredump, a long table) is lost even with
|
||||
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.
|
||||
|
||||
## Waveshare ESP32-S3-ETH with the OV5640 camera module
|
||||
|
||||
- Native USB console (`303a:1001`), ESP32-S3R8, 16 MB flash, 8 MB octal PSRAM, W5500 on SPI (MOSI 11,
|
||||
MISO 12, SCLK 13, CS 14, INT 10, RST 9), TF card on 4..7, WS2812 on 21.
|
||||
- Camera header (vendor schematic): XCLK 3, SIOD 48, SIOC 47, VSYNC 1, HREF 2, PCLK 39, D0..D7 = 41, 45,
|
||||
46, 42, 40, 38, 15, 18. PWDN is tied to GND and RESET is an RC to 3.3 V on the board, so no reset or
|
||||
power-down GPIO exists.
|
||||
- GPIO8 switches the camera 3.3 V rail through a P-channel MOSFET: LOW = camera powered, gate pulled up so
|
||||
the camera is off by default. `power_down_pin: GPIO8` only pulls it low 10 ms before the probe, which is
|
||||
not enough; use `switch: gpio GPIO8 restore_mode: ALWAYS_OFF setup_priority: 800` plus `on_boot:
|
||||
priority: 700` with `delay(1200)` and `esp32_camera: setup_priority: 200`
|
||||
(`templates/rtsp-waveshare-s3-eth-dut.yaml`). `esphome config` rejects a config that uses GPIO8 for both the switch
|
||||
and `power_down_pin` (pin reuse), so it is one or the other.
|
||||
- The sensor at SCCB 0x3C answers only with XCLK running, so the ESPHome i2c scan at boot (before XCLK)
|
||||
reporting no devices on 48/47 is expected. If the SCCB ID register (0x3100 = 0x78) reads fine but every
|
||||
0x30xx register reads 0x00 (`Detected camera not supported`, 0x106), reseat the ribbon before blaming
|
||||
software; `templates/waveshare-s3-eth-camdiag.yaml` runs that probe with LEDC XCLK and raw SCCB reads.
|
||||
|
||||
## ESP Thread Border Router board v1.2 (S3 host + H2 RCP)
|
||||
|
||||
- S3 host on USB JTAG serial, H2 RCP on its own USB. Spinel UART1 from the host: `rx_pin: GPIO17`,
|
||||
`tx_pin: GPIO18`, RCP reset `GPIO7` active low, 460800. The config needs `network: enable_ipv6: true`.
|
||||
- The shipped H2 firmware fails `CheckRadioCapabilities` with IDF 5.5; build `examples/openthread/ot_rcp`
|
||||
for esp32h2 with ESPHome's own IDF (`IDF_PATH` at the cached framework, its penv and tools,
|
||||
`IDF_PYTHON_CHECK_CONSTRAINTS=no`) and flash with esptool at 0x0, 0x8000 and 0x10000.
|
||||
- A crash-looping S3 pulses the H2 reset every boot, so the H2 cannot be flashed and the S3 will not
|
||||
enter its bootloader over USB. Hold S3 BOOT, tap S3 RST, flash the H2, release, then replug both.
|
||||
- `dns-sd -L <name> _meshcop._udp local.` shows the `omr` prefix; it disappears when routing is dead.
|
||||
Keep one capture per chip; never reset the H2 over USB mid-test unless that is the test (the host
|
||||
logs `Unexpected RCP reset: RESET_OTHER` and recovers).
|
||||
@@ -1,39 +0,0 @@
|
||||
# Proven test flows
|
||||
|
||||
Each flow names the pull requests it was used on, so their result tables show what to post.
|
||||
|
||||
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
|
||||
- [`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
|
||||
- [`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
|
||||
- [`nrf52.md`](nrf52.md): dongle board support
|
||||
- [`online_image.md`](online_image.md): stalled and malformed downloads, PNG, JPEG, BMP and QOI decode time per loop pass with large images and small buffers
|
||||
- [`openthread.md`](openthread.md): border router on the S3 host plus H2 RCP
|
||||
- [`ota.md`](ota.md): overlap and lock, timeouts, deflate
|
||||
- [`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
|
||||
- [`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
|
||||
- [`globals.md`](globals.md): restoring globals with storage rtc and flash across every reset kind
|
||||
- [`homeassistant.md`](homeassistant.md): light platform mirrored from a local Home Assistant, held reports versus later calls
|
||||
- [`usb_audio.md`](usb_audio.md): USB audio speaker and microphone, the usb_host FIFO split, and Music Assistant playback through sendspin
|
||||
- [`dfrobot_sen0395.md`](dfrobot_sen0395.md): SEN0395 mmWave command flow, module quirks and overlong lines through its error reply
|
||||
- [`speaker.md`](speaker.md): media player pipeline tasks on the Connect AUX-2 with the `speaker` platform player
|
||||
- [`web_server.md`](web_server.md): state SSE stress and the HTTPD task stack on web_server_idf, entity icon and device class readback
|
||||
- [`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
|
||||
@@ -1,58 +0,0 @@
|
||||
# api
|
||||
|
||||
## Noise handshake and OTA encryption on the ESP8266 (#19062, #19233)
|
||||
|
||||
Host side timing is useless on a weak link; use an on-device bench with the minimum of five runs over
|
||||
two boots. Provision a key with `noise_encryption_set_key` through aioesphomeapi and upload with
|
||||
`espota2.run_ota(host, 8266, None, bin, noise_psk=key)` when the key is not in the yaml.
|
||||
|
||||
## Outgoing connection wake timing on a deep sleep build (#21077)
|
||||
|
||||
`templates/deep-sleep-outgoing-dut.yaml`: classic ESP32 ESP-IDF, `wifi: fast_connect`, `api: encryption` with a bare
|
||||
`outgoing_connection:`, `deep_sleep` 15 s run and 15 s sleep, a `homeassistant` text sensor, and `millis()` logged
|
||||
from `wifi: on_connect`, `api: on_client_connected` and the sensor's first `on_value`. Home Assistant's dial-in
|
||||
listener is on 6054; reuse a device name it already has. Flash by USB, `serial_capture.py PORT 360 OUT --reset` for
|
||||
12 cycles, then `scripts/api_outgoing/cycles.py OUT LABEL` prints per cycle the wifi, client and state millis with
|
||||
the client-wifi and state-client gaps. Wi-Fi takes 4 to 8 s after a wake, so compare the client-wifi gap, and run
|
||||
the PR twice around one base run because the spread is a few hundred ms.
|
||||
Results: https://github.com/esphome/esphome/pull/21077#issuecomment-6254098014
|
||||
|
||||
## Outgoing connection on a mains build after a Wi-Fi drop (#21085)
|
||||
|
||||
`templates/outgoing-wifi-drop-dut.yaml`: classic ESP32, `outgoing_connection: delay: 2s`, a "Wifi cycle" button doing
|
||||
`wifi.disable`, 4 s, `wifi.enable`, a `debug` loop-time sensor, millis from the wifi and api triggers. Flash by USB,
|
||||
`serial_capture.py PORT SECONDS OUT --ms`, press the button N times 40 s apart with `api_button.py DEV_IP KEY press
|
||||
"Wifi cycle"`, then `wificycles.py CAPTURE LABEL` prints per drop the Wi-Fi-to-dial gap, dials and dials closed, who
|
||||
connected first, and the loop-time maxima. For the loop cost of polling, repeat with an unreachable
|
||||
`host: 192.0.2.1`. Home Assistant refuses a dial-in while its own session is READY (`Refusing dial-in adoption`),
|
||||
so after a drop every dial is closed and HA's incoming reconnect wins 11 to 33 s later; the measurable effect is the
|
||||
first dial landing in the loop the network flag flips.
|
||||
Results: https://github.com/esphome/esphome/pull/21085#issuecomment-6254742791
|
||||
|
||||
## User defined action listing and execution without a client library (#18882)
|
||||
|
||||
`scripts/api/rawactions.py HOST list` speaks the plaintext native API over a raw socket and decodes every
|
||||
`ListEntitiesServicesResponse` by field number (argument fields 1 name, 2 type, 3 description, 4 example, 5 optional,
|
||||
6 default_value), so new wire fields show up without waiting for the client library. `rawactions.py HOST exec ACTION
|
||||
k=v ...` sends `ExecuteServiceRequest` with `sint32` ints (field 5, not the legacy int32 field 2), fixed32 floats,
|
||||
length delimited strings and `int[]` as repeated sint32 (field 7); `ALLOW_MISSING=1` leaves arguments out on purpose
|
||||
(the device then drops the call). `templates/api-actions-dut.yaml` (D1 mini, three actions, optional variables with
|
||||
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,21 +0,0 @@
|
||||
# captive_portal
|
||||
|
||||
## Captive portal `/wifisave` hammer (#20802, #20784)
|
||||
|
||||
Reproduces a `/wifisave` arriving during the STA cooldown, and proves a fix on every board.
|
||||
Device under test: `templates/example-dut.yaml` (bogus network, `ap:` with `ap_timeout: 15s`,
|
||||
`captive_portal:`). Client: `templates/example-client.yaml` on an ESP32 or a D1 mini; it joins the
|
||||
device's AP, posts 15 bogus saves 3 s apart, then the real credentials. With the portal up the cooldown
|
||||
is 30 s, so nearly every save lands inside one. Driver: `scripts/wifisave_hammer.sh`. Settle 40 s on
|
||||
ESP boards, 90 s on the BW15 (its first attempt on the real network fails, see boards.md).
|
||||
|
||||
Counts that matter: `Requested WiFi Settings Change` (saves received), `Exiting cooldown early`, crash
|
||||
markers, boots (`Log initialized`), and the client's `bogus save status 200` and `real save status 200`.
|
||||
A healthy run: every save answered 200, one cooldown exit per save (two on the BW15, whose retry enters
|
||||
the adapter restart), no panic, and the real credentials connect the device within about 10 s.
|
||||
|
||||
Fault injection for AP start failures: wrap `this->ap_setup_ = this->wifi_start_ap_(this->ap_)` in
|
||||
`setup_ap_config_()` with an `HWTEST_AP_FAIL_COUNT` build flag
|
||||
(`esphome: platformio_options: build_flags: -DHWTEST_AP_FAIL_COUNT=2`), raise the portal's "Captive
|
||||
portal started" from LOGV to LOGI, and after provisioning curl the device's STA address: connection
|
||||
refused proves the portal's server is gone.
|
||||
@@ -1,11 +0,0 @@
|
||||
# cse7766
|
||||
|
||||
## cse7766 on a Sonoff S31 (#20948)
|
||||
|
||||
`templates/s31-cse7766-dut.yaml`: `logger: baud_rate: 0` because the CSE7766 owns the UART, VERBOSE logger
|
||||
with everything but cse7766 quieted, 2 s throttles, and a `globals` frame counter fed by the voltage sensor's
|
||||
`on_raw_value` and logged every 10 s (about 96 frames per 10 s). OTA only, every reflash reboots the relay.
|
||||
`scripts/cse7766/run_obs.sh IP SECONDS LABEL [OUTDIR] [NAME_FILTER]` subscribes to states and logs over the
|
||||
API with a concurrent ping and prints the frame counter, API gaps and warnings. API state gaps of 10 to 20 s
|
||||
can appear on a weak Wi-Fi path while the device counter stays flat, so judge a UART parser by the
|
||||
device-side counter, not by the API cadence. With nothing plugged in, current and power read 0.
|
||||
@@ -1,21 +0,0 @@
|
||||
# dfrobot_sen0395
|
||||
|
||||
## DFRobot SEN0395 mmWave on an ESP32 DevKit V1 (#20906, #20979)
|
||||
|
||||
Wiring: V to VIN (5 V, the module wants 3.6 to 5 V), G to GND, sensor TX to GPIO16 (RX2), sensor RX to GPIO17
|
||||
(TX2), IO2 to GPIO18 (presence output, a gpio binary sensor), I1 unconnected. `templates/dfrobot-sen0395-dut.yaml`
|
||||
has the hub, both detection binary sensors, the four switches, settings buttons and junk-line buttons.
|
||||
`scripts/dfrobot_sen0395/ctl.py HOST KEY press:NAME sw:NAME=on|off wait:S` drives it and prints binary sensor and
|
||||
switch updates; `cases.sh DEV_IP KEY CAPTURE LABEL` runs the whole flow against a running serial capture. Flash by
|
||||
USB, `serial_capture.py PORT 540 CAPTURE --reset`, then the cases; compare the `Sending command` and `Message:` lines
|
||||
and the counts of `Done`, `Error`, prompts and frames between builds. The module echoes every command, so the echoed
|
||||
lines are the bytes the component sent and can be compared between builds as a set.
|
||||
|
||||
Module facts: it answers `Done` or `Error` and then the `leapMMW:/>` prompt without a line end; a junk line gets
|
||||
`<line> is not recognized as a CLI command` (36 chars longer than the line, so 220 and 240 byte junk gives 256 and
|
||||
276 char replies); input lines of 256 bytes or more make the module assert (`..\User_code\main.c line:232`) and
|
||||
restart, after which the sensor is stopped; a factory reset restarts the module about 7 s later; `sensorStop` on a
|
||||
stopped sensor answers `sensor stopped already` then `Error`; a settings press takes 5 to 6 s (stop, change, save,
|
||||
start). Free heap on the ESP32 is Wi-Fi noise (192 to 198 kB) and says nothing about the component.
|
||||
Results: https://github.com/esphome/esphome/pull/20979#issuecomment-6279129146 and
|
||||
https://github.com/esphome/esphome/pull/20906#issuecomment-6279129604
|
||||
@@ -1,7 +0,0 @@
|
||||
# espnow
|
||||
|
||||
## ESP-NOW on the ESP8266 (#14407)
|
||||
|
||||
The NONOS SDK only delivers broadcast ESP-NOW frames while the station is associated or a soft-AP is
|
||||
up; a hidden, open, client-less soft-AP (60 s beacon, DHCP stopped) makes broadcasts arrive. In AP-only
|
||||
mode the device transmits from the soft-AP MAC.
|
||||
@@ -1,15 +0,0 @@
|
||||
# globals
|
||||
|
||||
## Restoring globals with storage: rtc and flash (#13954)
|
||||
|
||||
`templates/globals-storage-dut.yaml` is the shared package: five restoring globals (rtc int, flash int, default int,
|
||||
rtc `std::string`, rtc `uint8_t[2]`), bumped and logged with the reset reason on every boot, saved and synced after
|
||||
2 s, odd boots `App.safe_reboot()`. Platform files add the board (`packages: dut: !include globals-storage-dut.yaml`), the `debug` reset-reason text sensor and, on the
|
||||
ESP32, `deep_sleep: run_duration: 12s, sleep_duration: 8s` (even boots sleep). No network needed: flash by USB,
|
||||
`serial_capture.py PORT 110 OUT --reset` gives the reset pulse plus a run of soft restarts and sleeps; the ESP32's
|
||||
EN pulse is a `POWERON_RESET` that empties RTC memory, the D1 mini's RST pulse (`rst cause:2`) keeps it, so the
|
||||
ESP8266 needs a real power cut by hand; arm long `--released` captures on both ports first (the capture
|
||||
reopens the port when it comes back, the very first boot lines are still lost, read the next boot's restored
|
||||
values). Unchanged-build check: the config with every `storage:` removed, built on the PR and on the dev merge
|
||||
commit under the PR's own commits (not the merge base, which is older dev), `cmp -l` plus an `nm -S` symbol diff;
|
||||
only the template names differ. Results: https://github.com/esphome/esphome/pull/13954#issuecomment-6254794712
|
||||
@@ -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,9 +0,0 @@
|
||||
# hdmi_cec
|
||||
|
||||
## HDMI-CEC two-board wire (#9189)
|
||||
|
||||
Two boards on one wire: promiscuous mode, a 0x8F request answered with 0x90 0x00, a `destination:`
|
||||
filter on the reply handler, template buttons for each target plus lambdas calling
|
||||
`send(source, dest, span)` as another initiator. Healthy numbers: device-side turnaround 15 to 22 ms,
|
||||
round trip 144 to 156 ms. Press buttons over the API; judge timings from device logs (ESP32 light sleep
|
||||
lags the press).
|
||||
@@ -1,47 +0,0 @@
|
||||
# homeassistant
|
||||
|
||||
## homeassistant light platform against a local Home Assistant (#11354)
|
||||
|
||||
A local Home Assistant dev install (`hass -c config`, https://127.0.0.1:8123 with a self-signed cert); its ESPHome
|
||||
entries and entity ids are in `config/.storage/`. Two ESPHome RGBCW bulbs with a plaintext API are the lights, so an
|
||||
"HA side" change is made directly on a bulb with `scripts/homeassistant_light/bulb.py BULB_IP - on|off|state|restart`.
|
||||
Add the test devices to HA by hand with the shared `api_key` and "Allow the device to perform Home Assistant actions".
|
||||
|
||||
`templates/homeassistant-light-dut.yaml` is a package: two mirrors, buttons for each change, a "Log state" button, a
|
||||
30 s alive line, an `on_boot` `light.turn_on` for the change-before-first-write path, and VERBOSE logging with the
|
||||
noisy tags at DEBUG (a tag cannot exceed the global level). A platform file sets the board and includes it:
|
||||
|
||||
```yaml
|
||||
esphome:
|
||||
name: ha-light-dut
|
||||
esp32:
|
||||
board: esp32dev
|
||||
framework:
|
||||
type: esp-idf
|
||||
packages:
|
||||
dut: !include homeassistant-light-dut.yaml
|
||||
```
|
||||
|
||||
Flash by USB, start a bounded `esphome logs` capture per device, then press buttons with
|
||||
`scripts/api_button.py DEV_IP KEY press "Button"` and read the bulb with `bulb.py`. Cases: each
|
||||
button against the bulb and the device log; a direct bulb change that both mirrors follow; restart the bulb, send a
|
||||
change, expect the 5 s `did not report the change back` and the fallback (with an off and with an on last report);
|
||||
OTA reboot with a serial capture running to see the boot-time change (the API log client reconnects too late).
|
||||
|
||||
Lessons: the light core clamps mireds to the range HA reported; a flash sends nothing; a change sent while HA is
|
||||
connected but not yet subscribed is dropped by the api server (`client has not subscribed to actions (yet)`); after a
|
||||
fallback to an off report the mirror keeps the unsent brightness; a mirror that never saw its light on since boot has
|
||||
no levels to restore. Results: https://github.com/esphome/esphome/pull/11354#issuecomment-6253630336 and
|
||||
https://github.com/esphome/esphome/pull/11354#issuecomment-6254161409
|
||||
|
||||
## Held report versus a later call (#21144)
|
||||
|
||||
A report that arrives during a transition is held and applied when the transition ends, unless a call came after
|
||||
it. `scripts/homeassistant_light/heldcase.py DEV_IP KEY BULB_IP same|many [BULB_KEY]` (a key of `-` is plaintext) keeps one API connection to the mirror
|
||||
device and one to the bulb so the steps land inside a 3 s fade: press "A 50 fade 3s", 0.7 s later set the bulb to
|
||||
90% directly (the report is held), 1.4 s in press the same fade again (or "A many calls", 16 calls in one loop
|
||||
pass). Pass: the mirror and the bulb end at the second call's target. Only `same` reproduces the bug: a build
|
||||
without the fix logs `Applying the report that arrived during the transition` and the bulb stays at 90%. `many`
|
||||
ends at 100% on both builds because the last call's target differs from the held report, so it is a regression
|
||||
check only, not a reproduction. Separate button presses are too slow (about 1.5 s each) to land inside the fade.
|
||||
The mirrors are not API entities, so read their state from the "Log state" button's line. Results: https://github.com/esphome/esphome/pull/21144#issuecomment-6278257695
|
||||
@@ -1,36 +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`) 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.
|
||||
@@ -1,13 +0,0 @@
|
||||
# ld2412
|
||||
|
||||
## Output pin level and the basic configuration command (#21353)
|
||||
|
||||
`templates/ld2412-select-only-dut.yaml` (ESP32-S3, the module on GPIO43 and GPIO44 at 115200, only the output pin
|
||||
level select, the module's OUT pin on GPIO38 as a binary sensor plus the presence sensor) with `uart: debug:
|
||||
direction: BOTH`. Drive the select with `scripts/ld2450/lddrive.py HOST KEY LOGFILE sel:NAME=OPTION` and read the TX
|
||||
dump for command `02` carrying the level byte, then the OUT pin binary sensor against presence: with level high the
|
||||
pin follows presence, with level low it is inverted. A module that never answers the boot query (no `<<<` lines)
|
||||
only shows the held back path: `Command 02 held back until the module reports its settings`, a query `12`, and after
|
||||
2 s `Command 02 not sent, the module did not report its settings` with the select republished to the last known
|
||||
level. With the full set of numbers configured a select change also needs every number to have a state, so wait
|
||||
for the boot query answer before judging.
|
||||
@@ -1,42 +0,0 @@
|
||||
# ld2450
|
||||
|
||||
## LD2450 polygon zones (#20154)
|
||||
|
||||
To make a target "leave" without anyone moving, set the radar's Zone-1 numbers over the target and
|
||||
switch the zone type to `Filter` (the count drops to 0 within 0.5 s); set it back to `Disabled` after.
|
||||
Writing those numbers blocks the ld2450 loop about 50 ms.
|
||||
|
||||
## Zone numbers round trip (#21146)
|
||||
|
||||
`scripts/ld2450/zonedrive.py HOST KEY(- for plaintext) set:NAME=VALUE sel:NAME=OPTION wait:S list` sets numbers and
|
||||
selects over the API and prints every LD2450 state update. After each set the hub sends the set zone command, queries
|
||||
the radar and republishes all twelve coordinates from the answer, so set each coordinate of each zone to a distinct
|
||||
value and check the readbacks; no target is needed. Readbacks can arrive late over Wi-Fi, so match them by content.
|
||||
Results: https://github.com/esphome/esphome/pull/21146#issuecomment-6278026922
|
||||
|
||||
## ESP8266 loopback harness, no radar needed (#21349)
|
||||
|
||||
`templates/ld2450-loopback.yaml` (package; substitutions `name` and `baud`) runs the hub on UART0 (GPIO1 and GPIO3)
|
||||
with `logger: baud_rate: 0` and sets the UART0 loopback bit in `on_boot` (`USC0(0) |= (1 << UCLBE)`), so everything
|
||||
the hub or a `uart.write` action sends comes back on RX. Template buttons inject periodic frames (all four direction
|
||||
strings, targets 2 and 3), query zone acks (zone type 0, 1 and 2 for the select readback) and call the name based
|
||||
setters with a valid and a bogus name. `uart: debug: direction: TX` delimited on the command footer dumps every
|
||||
command the hub sends. Drive it with `scripts/ld2450/lddrive.py HOST KEY LOGFILE press:NAME sel:NAME=OPTION wait:S`
|
||||
(logs over the API at VERBOSE, 2 s between steps because the API log stream drops lines while `send_command_`
|
||||
blocks), then `txsum.py LOGFILE` lists the TX frames per step; diff the summaries of the two builds. The hub reads its
|
||||
own commands back and logs `Invalid status` for each, which is harmless. The boot readback of the baud rate select
|
||||
comes from the UART setting, so a second build at `baud: "9600"` checks the flash table lookup.
|
||||
Results: https://github.com/esphome/esphome/pull/21349#issuecomment-6332320026
|
||||
|
||||
## Frame splitter collisions (#21357)
|
||||
|
||||
The loopback template also carries the zone 1 numbers and seven collision buttons: a periodic frame with the
|
||||
command footer inside target 1, zone acks with `55 CC` and with `04 03 02 01` inside the coordinates, a periodic
|
||||
frame cut after 12 bytes followed by a zone ack, a frame missing its last byte followed by a complete one, a bogus
|
||||
255 byte length then a frame, and garbage then a frame. Judge by the state updates plus the `Handling Periodic` and
|
||||
`Handling Ack` lines. Through a real radar the set zone ack is sometimes corrupted by the radar itself (its tail
|
||||
replaced by the periodic frame it was sending, for example `04 03 03 03 00 ... 55 CC`), so count readbacks over at
|
||||
least 24 selects per build and read the raw bytes with `uart: debug: direction: RX` (`!extend` the package's uart
|
||||
id) before blaming the parser; the API log stream drops lines under that dump volume, so some misses stay
|
||||
unclassified.
|
||||
Results: https://github.com/esphome/esphome/pull/21357#issuecomment-6333244886
|
||||
@@ -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,58 +0,0 @@
|
||||
# libretiny
|
||||
|
||||
## LibreTiny rtc preference emulation (#21007)
|
||||
|
||||
The PR keeps `storage: rtc` preferences in FlashDB and deletes them on the first load or save after a boot
|
||||
whose `lt_get_reboot_reason()` is not software, watchdog, crash or sleep. Only the families listed in
|
||||
`_libretiny_rtc_supported()` accept the config keys; on others force the backend in with
|
||||
`platformio_options: build_flags: ["-DUSE_LIBRETINY_RTC_PREFERENCES"]` after confirming the rejection.
|
||||
|
||||
- Harness: `scripts/libretiny_prefs/ltprefs.hpp` plus `templates/bk72xx-rtc-prefs-dut.yaml`. `ltprefs_boot()`
|
||||
loads one rtc and one flash preference, a second pair that shares one key as rtc and as flash, and a third
|
||||
rtc entry (so a hard reset drops three entries in one pass), logs the reason and both results, saves `100 + step`, syncs; after
|
||||
a templated delay `ltprefs_exit()` bumps the flash-backed step and runs the step's action (`lt_reboot()`,
|
||||
`__builtin_trap()`, `lt_reboot_wdt()` or idle). The last 8 boot reports are kept in a flash preference and
|
||||
repeated in the 10 s alive line, so a boot missed by the capture (a power cut, an OTA-only board) is still
|
||||
readable. Bump `run:` for fresh keys.
|
||||
- A store to an unmapped address does not fault on the ARM968, the board carries on: use `__builtin_trap()`
|
||||
for the crash row. The SDK crash handler reboots about 10 s later. Works on BK7238 and BK7231N.
|
||||
- Hard resets: `serial_capture.py ... --reset` pulses RTS on CEN (reported as Power-On). A real power cut
|
||||
needs a hand or a smart plug; the history in the alive line covers the boot the host cannot see. On the
|
||||
Beken SDK a chip-enable reset and a power cut both report Power-On, there is no separate reset-pin source.
|
||||
- Step 0 and step 8 wait 30 s before acting so the host can open the port (and pulse a reset) after a flash
|
||||
without losing the first boot; the flash tool's own reset starts the sequence immediately otherwise.
|
||||
- OTA-only board: keep the device's wifi, api and ota blocks verbatim, keep safe_mode, read logs with
|
||||
`esphome logs <yaml> --device <name>.local` (the API attaches late, hence the history), and restore the
|
||||
device's own config afterwards.
|
||||
- Plain-build comparison: `raw_firmware.bin` differs by the timestamp and by `__LINE__` in log calls of
|
||||
functions below the added code; map offsets through `objdump -h` load addresses and `addr2line` before
|
||||
calling a byte difference a code change.
|
||||
|
||||
## BK72xx crash report on the next boot (#21012)
|
||||
|
||||
Harness: `scripts/libretiny_crash/bkprobe.hpp` plus `templates/bk72xx-crash-probe-dut.yaml`. A flash
|
||||
preference holds the step; `on_boot` (priority -100) logs the reset reason, the SDK start type, two canaries
|
||||
and hex dumps of the low SRAM, a set of marker words and the record area after `.bss`, waits 30 s on step 0
|
||||
(so a capture can be opened after the flash) or 5 s, saves `step + 1`, syncs, then acts: 0 `__builtin_trap()`,
|
||||
1 call into unmapped memory, 2 unmapped and unaligned reads and a store (no fault on the ARM968), 3
|
||||
`lt_reboot()`. A `globals: restore_value` step counter does not work here: it is only saved from the global's
|
||||
loop, which a crash 50 ms later never reaches; save an `ESPPreferenceObject` and `global_preferences->sync()`
|
||||
first. Bump `run:` for fresh keys. Keep the `wifi:` block: the bug the fix addresses only shows with Wi-Fi up.
|
||||
|
||||
Flow: `flash_bk72xx.py` (retry up to three times), one `serial_capture.py ... --reset` capture of 150 to 230 s,
|
||||
then `grep -a "libretiny.crash\|probe"`. Decode with
|
||||
`arm-none-eabi-addr2line -pfiaC -e .pioenvs/<name>/raw_firmware.elf <addr...>` (the ELF is `raw_firmware.elf`
|
||||
on LibreTiny), or run `scripts/libretiny_crash/decode_capture.py <yaml> <capture>` from the config directory
|
||||
to feed the capture through the CLI's `LogLineProcessor`.
|
||||
|
||||
Expected: `*** CRASH DETECTED ON PREVIOUS BOOT ***`, `Reason: Undefined instruction`, PC on the `udf`,
|
||||
LR = PC + 1, BT0..BT7 walking the lambda, `StatelessLambdaAction`, `Action::play_complex`, `DelayAction`,
|
||||
`Scheduler::call`, `Application::loop`. The wild call reports where the core ended up (it executes zeros as
|
||||
Thumb NOPs until it wraps into real code), not the called address. Without the fix a dev build with Wi-Fi
|
||||
connected never comes back from the crash; see the BK72xx section in `boards.md`.
|
||||
|
||||
OTA-only board: copy the device's own config, add the probe include and the step machine (step 0 crashes
|
||||
45 s after boot, later steps idle), keep its wifi, api, ota and safe_mode blocks and use the secrets file
|
||||
next to that config. A LibreTiny OTA is a 1.5 MB UF2 and takes minutes on a slow link, so do not wrap the
|
||||
upload in a short timeout. Read the replayed report with `esphome logs ... --device <name>.local` (an API
|
||||
client gets it on subscribe) or on the board's serial log port if it has one.
|
||||
@@ -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
|
||||
@@ -1,65 +0,0 @@
|
||||
# mqtt
|
||||
|
||||
## MQTT (#20433, #17935, #20762, #20767, #20768)
|
||||
|
||||
A local mosquitto with `allow_anonymous true`, `log_type all` and `log_dest file`: the broker log gives
|
||||
each subscription's QoS, the device address (`New client connected from <ip> as <name>-<mac>`) and exact
|
||||
subscribe counts. Kill and restart mosquitto to exercise `on_disconnect` (reason 0) and resubscription.
|
||||
Keep `reboot_timeout: 0s` on `api:` and `mqtt:`. The ESP-IDF outbox swings free heap about 2 kB right
|
||||
after bulk subscribe and unsubscribe; read the heap seconds later over several rounds before calling a
|
||||
leak. Spawned subscriptions need about 2.5 s to reach the broker before the next publish.
|
||||
`esphome logs --device MQTT` only uses the MQTT transport when the config has no `api:`. Driver pattern: a
|
||||
paho script publishes and polls the serial capture file.
|
||||
|
||||
## WebSocket transports on ESP-IDF (#16056)
|
||||
|
||||
One build per transport from `templates/mqtt-transport-dut.yaml`, with `scripts/mqtt/mosquitto-ws.conf` as the
|
||||
local broker (mosquitto 2.x from brew has `websockets` support; `log_type all` prints `New connection from <ip>:<port>
|
||||
on port <listener>`, which proves which listener each client used) and `scripts/mqtt/make_test_ca.sh BROKER_IP` for
|
||||
the TLS listener's certificate, both run in the scratch directory so keys, logs and outputs stay out of the checkout. `scripts/mqtt/cases.sh NAME KEY BROKER_HOST SUB_PORT CAPTURE [DEV_HOST] [restart]` subscribes
|
||||
to `NAME/#`, sends a switch command and an `on_message` topic, presses the 3000 byte publish button over the API,
|
||||
restarts the local broker when the last argument is `restart` (the PID in `mosquitto.pid`, written when the broker
|
||||
was started with `mosquitto -c mosquitto-ws.conf & echo $! > mosquitto.pid` in the working directory next to the
|
||||
certificates), checks every listener in the broker config answers again, and prints the broker's message counts with the device log. `mosquitto_sub` cannot speak
|
||||
WebSocket, so it subscribes on the plain listener of the same broker. Cases: `tcp` on 1883, `ws` on 9001, `wss` on
|
||||
9002 with `certificate_authority` (the certificate names an address, so `skip_cert_cn_check: true`), `wss` to
|
||||
test.mosquitto.org on 8081 with no CA for the certificate bundle, and two negatives that must never connect: a
|
||||
different CA (`mbedtls_ssl_handshake returned -0x2700`) and the self-signed server through the bundle
|
||||
(`esp-x509-crt-bundle: Failed to verify certificate`, `-0x3000`). `CONFIG_MQTT_TRANSPORT_WEBSOCKET` is on by
|
||||
default in the generated sdkconfig. The TLS session costs about 29 kB of internal heap while connected; the public
|
||||
broker carries other devices' `esphome/discover` traffic, which is noise. Results:
|
||||
https://github.com/esphome/esphome/pull/16056#issuecomment-6301034019
|
||||
|
||||
## TLS trust sources on ESP-IDF (#14318)
|
||||
|
||||
One build per trust source from `templates/mqtt-tls-dut.yaml`: broker only (port must resolve to 1883),
|
||||
`certificate_authority` with no port (must resolve to 8883), `verify_ssl: false` with no CA, the CA plus
|
||||
`client_certificate` and `client_certificate_key` on the 8884 listener that requires one, `transport: wss` with the CA,
|
||||
`tls: true` to test.mosquitto.org on 8886 for the certificate bundle, and `tls: true` to the local self-signed broker as
|
||||
the negative. `scripts/mqtt/mosquitto-ws.conf` now has the 8883 and 8884 listeners and `scripts/mqtt/make_test_ca.sh`
|
||||
also writes `client.crt`/`client.key`. Before flashing, check each build's `src/esphome/core/defines.h` for
|
||||
`USE_MQTT_TLS`, `USE_MQTT_CERT_BUNDLE` and `USE_MQTT_TLS_INSECURE` and its `sdkconfig.<name>` for
|
||||
`CONFIG_MBEDTLS_CERTIFICATE_BUNDLE` and `CONFIG_ESP_TLS_INSECURE`: only the bundle builds may carry the bundle and only
|
||||
the unverified build the insecure flags. `scripts/mqtt/flash_and_drive.sh TREE YAML PORT KEY BROKER_HOST
|
||||
local|public|neg` runs one build end to end (flash, bounded capture, `cases.sh` with a restart for the local broker,
|
||||
counts and the broker's per-listener connection lines) and prints the config dump's `TLS:` line (`CA certificate`,
|
||||
`certificate bundle` or `no verification`). The CLI side (`esphome/mqtt.py`) is covered without a board by
|
||||
`scripts/mqtt/cli_tls_check.sh TREE [neg] YAML...`, which runs `esphome clean-mqtt` under a timeout: status 124
|
||||
after `Connected to MQTT broker!` is a pass, and with `neg` each config must instead fail with
|
||||
`CERTIFICATE_VERIFY_FAILED` and never connect. Python's default SSL
|
||||
context rejects a CA that lacks a `keyUsage` extension (`CA cert does not include key usage extension`) while mbedTLS
|
||||
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` 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.
|
||||
@@ -1,6 +0,0 @@
|
||||
# nrf52
|
||||
|
||||
## nRF52840 dongle boards (#19009, #20814)
|
||||
|
||||
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.
|
||||
@@ -1,64 +0,0 @@
|
||||
# online_image
|
||||
|
||||
## online_image stalled downloads (#20594)
|
||||
|
||||
One classic ESP32, both frameworks (the ESP32 Arduino build also uses `http_request_idf.cpp`). The host
|
||||
serves the images: `scripts/online_image/make_images.py <www>` writes 16x16 BMP/PNG/JPEG/QOI plus an 8 bit
|
||||
palette BMP with a 1078 byte header; `scripts/online_image/oi_server.py <www> 8765 <log>` answers one
|
||||
misbehaviour per path name (`ok`, `truncated`, `large_header`, `empty`, `stall` holds the socket 40 s,
|
||||
`closed_early`, `slow` pauses 2.5 s, `chunked`, `chunked_cut`, `noclen`, `huge` claims 20 MB) with an ETag
|
||||
and a 304 on If-None-Match. `templates/online-image-dut.yaml` has two AUTO-format images (default and
|
||||
256 byte buffer), API actions `fetch`/`fetch_small` (set_url with `update: false`, then component.update)
|
||||
and `refetch`/`refetch_small` (component.update only, keeps the cache headers), and a restart button.
|
||||
`scripts/online_image/drive.py <device ip> <api key> <capture> http://<host ip>:8765 pr|base` runs the
|
||||
case list over aioesphomeapi and judges each from the serial capture. ESP-IDF facts: a stalled server
|
||||
ends with `Error downloading image: -28679` (EAGAIN) after the transport timeout, an early close with
|
||||
`-1`, both before and after the PR; a body without Content-Length and without chunking reads as complete
|
||||
(Size: 0) and finishes. A build without the fix hangs on the truncated, oversized header, empty, chunked PNG
|
||||
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.
|
||||
@@ -1,5 +0,0 @@
|
||||
# openthread
|
||||
|
||||
## Thread border router (#18104)
|
||||
|
||||
See boards.md for the ESP Thread BR board. Check that the H2 answers Spinel before blaming a PR.
|
||||
@@ -1,8 +0,0 @@
|
||||
# ota
|
||||
|
||||
## OTA overlap and lock (#20588), OTA timeouts (#19041), deflate (#19037)
|
||||
|
||||
All overlap orders (a web upload during a native OTA and the reverse) must be refused; the lock release
|
||||
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.
|
||||
@@ -1,18 +0,0 @@
|
||||
# rtsp_server
|
||||
|
||||
## RTSP camera streaming on the Waveshare ESP32-S3-ETH (#17990)
|
||||
|
||||
`templates/rtsp-waveshare-s3-eth-dut.yaml` (OV5640 pins, GPIO8 camera power switch with the 1.2 s boot delay,
|
||||
`rtsp_server`, logger VERBOSE for `rtsp_server`); swap the `wifi:` block for the W5500 `ethernet:` block when
|
||||
the cable is in, and add `network: enable_high_performance: true` for the big TCP buffers. Flash over native
|
||||
USB, capture the log with `serial_capture.py`, take the IP from the last `IP Address` line that is not
|
||||
0.0.0.0 (or `dns-sd -Q <name>.local`). `scripts/rtsp_server/rtsp_client.py IP [cases]` covers play, udp,
|
||||
pipeline, badreq, replay, getparam, teardown, third, stall, timeout; `rawrate2.py IP quiet|chatty|rtcp|bigbuf`
|
||||
measures the raw receive rate; `measure.sh IP LABEL LOGFILE [OUTDIR]` runs the fixed set (ping, ffmpeg 12 s
|
||||
twice, two ffmpeg clients, raw reader) and appends to `results.txt`; `cam_api.py IP` pulls one image over the
|
||||
API; `ffmpeg -rtsp_transport tcp -i rtsp://IP:554/ -frames:v 30 -f image2 f%03d.jpg` plus Pillow checks
|
||||
decoding. The 5760 byte default TCP send buffer makes the stream stall over Wi-Fi (about 1 fps, dozens of
|
||||
stall drops per run); `enable_high_performance` gives several fps on Wi-Fi and removes the stalls on Ethernet.
|
||||
Frame counts vary a lot between runs (auto exposure changes the JPEG size), so always measure twice. Home
|
||||
Assistant's stream pipeline does not accept MJPEG over RTSP; its ffmpeg camera opens one RTSP session per
|
||||
snapshot, so `max_connections` needs headroom, and go2rtc transcoding to H.264 is the way to a live view.
|
||||
@@ -1,8 +0,0 @@
|
||||
# scheduler
|
||||
|
||||
## Scheduler and loop wake A/B (#20356)
|
||||
|
||||
An external component whose template button arms an SDK `os_timer` (50 ms, one shot) on the ESP8266;
|
||||
the callback runs in SYS context, records `millis()` and calls `set_timeout` or `defer`; the timeout
|
||||
logs the elapsed time and loop count delta. Drive with an aioesphomeapi script (`subscribe_logs` plus
|
||||
`button_command`). Build the same yaml twice with different names, one per tree.
|
||||
@@ -1,19 +0,0 @@
|
||||
# speaker
|
||||
|
||||
## Media player pipeline tasks (#21203)
|
||||
|
||||
The `speaker` media player platform (`speaker/media_player/`) creates `ann_read`, `ann_decode`, `med_read` and
|
||||
`med_decode` FreeRTOS tasks on every play and deletes them after a stop. The AUX-2 and sendspin packages use the
|
||||
`speaker_source` player instead, which has its own pipeline and never runs that code, so a test of
|
||||
`speaker/media_player/*` has to swap the player: `templates/aux-2-preprod-speaker-player-dut.yaml` removes the
|
||||
package's `external_media_player` with `id: !remove` and adds a `speaker` platform player on the package's resampler
|
||||
speakers, plus a "Task names" button whose lambda calls `xTaskGetHandle()` on the four names and logs internal free
|
||||
heap. Serve FLAC files from the host (`ffmpeg -f lavfi -i "sine=frequency=440:duration=90" -ac 2 -ar 48000 -c:a flac
|
||||
media90.flac`, a 3 s mono one for announcements, `python3 -m http.server 8765 --directory www`); `audio_http`
|
||||
refuses WAV and MP3. `scripts/speaker_media_player/cases.sh HOST KEY MEDIA_URL ANN_URL CAPTURE LABEL` runs three
|
||||
cycles through `drive.py` (`play:URL | ann:URL | stop | press:NAME | wait:S` on one API connection) with the probe
|
||||
pressed idle, during media, during the announcement, after it and after the stop. Pass: idle none, media `med_*`
|
||||
only, announcement all four, after stop none, every cycle. API commands land a second or two late over Wi-Fi, so read
|
||||
the probe against the `State changed to` lines rather than the driver's timestamps. Internal free heap after a stop
|
||||
moved by 2.5 kB between two boots of the same build, so a heap delta needs more than one boot per build. Results:
|
||||
https://github.com/esphome/esphome/pull/21203#issuecomment-6299581943
|
||||
@@ -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...` (flash,
|
||||
capture, drive; `PORT` and `SC` in the environment).
|
||||
@@ -1,26 +0,0 @@
|
||||
# udp
|
||||
|
||||
## UDP, multicast, sockets (#20556 to #20559, #20585, #20590)
|
||||
|
||||
A listener on port 9 needs no privileges on macOS. Test multicast device to device; host to device
|
||||
multicast never arrives on some access points, and `239.255.x.x` groups are unreliable even to a stock
|
||||
listener. Broadcast to boards is lossy under power save, unicast is not. Flood at a fixed packet rate
|
||||
(the host hits `ENOBUFS` unthrottled); 1500 packets per second survived on every board. A forced Wi-Fi
|
||||
reconnect on the Pico keeps IGMP membership. Set a long loop interval from `wifi.on_connect`
|
||||
(`App.set_loop_interval(20000)`), not `on_boot`, or Wi-Fi connect crawls. The `logger.log` action
|
||||
rejects `%.*s`; use a lambda.
|
||||
|
||||
## udp.write payload shapes (#21263, ApplyBytes)
|
||||
|
||||
`templates/udp-write-dut.yaml` puts every payload shape behind a template button (constant 4 bytes twice, 3, 9, 0,
|
||||
128, 129 and 600 bytes, a 300 byte lambda, a simple value, a string) plus an `on_receive` that replies with the
|
||||
received bytes reversed. `scripts/udp/write_cases.sh DEVICE_IP KEY` records the device's datagrams with
|
||||
`udp_listen.py` on the test host, presses the buttons two seconds apart, sends one unicast datagram for the echo and
|
||||
compares everything byte for byte with `check.py`; a missing datagram shifts every later one, so read the first
|
||||
mismatch. Before flashing, check the generated `main.cpp`: on ESP8266 a constant payload is copied out of its
|
||||
`PROGMEM` table into `uint8_t esphome__bytes[N]` up to the stack limit and into `std::make_unique<uint8_t[]>` beyond,
|
||||
identical payloads share one table, a lambda is sent from its vector. An empty constant payload is generated as
|
||||
`send_packet(nullptr, 0)`, and the raw lwIP UDP `sendto` used on ESP8266 rejected a null buffer with `EINVAL`
|
||||
(`sendto() error 22` in the log, no datagram) until it accepted `nullptr` with a zero length; the old
|
||||
`TemplatableBytes::visit` had passed a zero length stack buffer instead. Compare sizes against the stacked PR's own
|
||||
head when the PR is stacked, not against dev. Results: https://github.com/esphome/esphome/pull/21263
|
||||
@@ -1,52 +0,0 @@
|
||||
# usb_audio
|
||||
|
||||
## USB audio on the Waveshare ESP32-S3-ETH (#21081, #11728)
|
||||
|
||||
`templates/usb-audio-waveshare-s3-eth-dut.yaml`: ESP-IDF, PoE, logs over the API on Ethernet (the native USB port is
|
||||
the host port, so there is no console), `usb_audio` hub, a 48 kHz 16-bit microphone, a 48 kHz 24-bit speaker (many
|
||||
speakerphones offer only 24-bit; a wrong format logs the device's alternates), buttons for capture start and stop,
|
||||
a non-blocking beep fed from an 8 ms interval with `play(buf, len, 0)` (a blocking `play()` on the main loop trips
|
||||
the task watchdog), and a status interval with mic bytes, speaker state and heap. Drive the buttons with
|
||||
`scripts/api_button.py IP KEY press "Beep"`. Expect 192 kB/s microphone bytes and the FIFO split
|
||||
RX 80 / NPTX 16 / PTX 104 in the build's `defines.h`; with the balanced split the 294-byte OUT pipe is refused
|
||||
(`EP MPS (294) exceeds supported limit (128)`). A device whose OUT endpoint is larger than 600 bytes cannot be
|
||||
claimed on an S3 at all.
|
||||
|
||||
## Music Assistant through sendspin
|
||||
|
||||
`templates/usb-audio-sendspin-s3-eth-dut.yaml` overlays the template above with the Apollo CAST-1 wiring: resampler
|
||||
speakers into a mixer whose inputs never time out, `speaker_source` media player with the sendspin source, and
|
||||
`sendspin: unpaired_access: true`. A `media_player: platform: speaker` is not a media-source consumer and gives
|
||||
"Player over its buffer", no audio. Music Assistant finds the device by mDNS within 15 s of boot.
|
||||
|
||||
Read the result from the device, not only by ear: sendspin's sync task logs `Lost sync (N us off)` (DEBUG, tag
|
||||
`SsSync`) for every correction over 5 ms, a positive N inserts that much silence, and each one is an audible click.
|
||||
For the chunk lead histogram, edit the managed library in the build directory,
|
||||
`.esphome/build/<name>/managed_components/sendspin__sendspin-cpp/src/sync_task.cpp` (an `SS_LOGD` before the
|
||||
late-chunk skip in `decode_chunk()` printing the chunk's lead against `new_audio_client_playtime`), update only that
|
||||
file's `size` and sha256 `hash` in the component's `CHECKSUMS.json`, and compile again; deleting `.component_hash` or
|
||||
recomputing it makes the manager refuse or refetch. Check the edit is in the image with `strings firmware.ota.bin`.
|
||||
A lead below -5 ms makes the library skip the whole chunk; an I2S speaker keeps it within 0.1 ms of zero, which is
|
||||
the figure a USB speaker has to match.
|
||||
|
||||
Gotchas: wait two minutes after a reboot before the measured stream (safe mode's boot counter write stalls the cores
|
||||
for about 140 ms once, 60 to 75 s after boot); with the serial console on, a DEBUG log line per report saturates
|
||||
UART0 and trips the task watchdog, so use `logger: baud_rate: 0` and the API log; two overlapping `esphome logs`
|
||||
captures double every count; and every audio test must include a pause and resume cycle, since a stream end that
|
||||
leaves less than one transfer parked in the driver was what hung the speaker after #11728 merged.
|
||||
|
||||
## Controls
|
||||
|
||||
Apollo CAST PRO-1 (`templates/cast-pro-1-sendspin-control.yaml`): `Core.yaml` next to it is
|
||||
`Integrations/ESPHome/Core.yaml` from ApolloAutomation/CAST_PRO-1, which also defines the `version` substitution.
|
||||
Keep its framework log level at ERROR (DEBUG floods driver output and trips the watchdog); the package reboots itself
|
||||
into Ethernet-only once it sees a link and appends the MAC suffix to the name. `wifi: enable_on_boot: false` keeps
|
||||
sendspin off Wi-Fi.
|
||||
|
||||
Nabu Casa Connect AUX-2 (a pre-production unit): build from `packages/aux-2-pre-prod.yaml` at NabuCasa/aux-2 commit
|
||||
283f2e64 (dropped in bde41e01), not the public `aux-2.yaml`, whose W5500, codec and I2S pins differ (the public one
|
||||
reads W5500 chip ID 0x00 and fails the codec's I2C writes). Point its local `external_components` source at
|
||||
`github://NabuCasa/aux-2@main`. Templates `aux-2-preprod-stock-dut.yaml` (I2S codec) and
|
||||
`aux-2-preprod-usb-audio-dut.yaml` (the USB speaker as the mixer output via `!extend mixing_speaker`). The console is
|
||||
the CH343 (1a86:55d3); first flash over it, OTA after. Forcing the Wi-Fi flag off with `restore_value: no` boot-loops
|
||||
when Ethernet fails, so let the package switch itself.
|
||||
@@ -1,20 +0,0 @@
|
||||
# usb_cdc_acm
|
||||
|
||||
## usb_cdc_acm on the nRF52840 dongle (#11634)
|
||||
|
||||
`templates/usb-cdc-acm-dongle-dut.yaml`: logger on USB_CDC port 0, `usb_cdc_acm` interface 0 disabled,
|
||||
interface 1 echoing from a 20 ms lambda, 0x01-prefixed commands for burst, stream, flush, peek, line coding
|
||||
and counters. Build and flash with `dfu: true` through the app port; the dongle then shows three CDC ports:
|
||||
the board DTS node `cdc_acm_uart` (unused), `cdc_acm_uart0` (log) and `cdc_acm_uart1` (data), in that order.
|
||||
Capture the log port with `serial_capture.py`, drive the data port with `scripts/usb_cdc_acm/drive.py
|
||||
DATA_PORT` (11 cases, prints PASS/FAIL and a summary) and grep the log for `Opened`, `Closed`, `buffer full`,
|
||||
`flush result`, `line coding`. Boot lines are held in the driver's 1 KB ring until the host opens the port, so
|
||||
a capture started later still shows the first 1 KB of the boot and then a truncated line.
|
||||
|
||||
With three CDC instances the Zephyr legacy stack's `CONFIG_USB_MAX_NUM_TRANSFERS=4` starves the last instance
|
||||
(each instance holds an OUT read and an IN ZLP), so interface 1 shows DTR changes but moves no data.
|
||||
`scripts/usb_cdc_acm/cdc_probe.hpp` (include it, call `cdc_probe()` from an interval) reads the Zephyr driver
|
||||
directly to tell a dead endpoint from a component bug. Raising the transfer pool to 8, or disabling the
|
||||
board's `cdc_acm_uart` node, fixes it. Design limit of the driver: `fifo_fill` holds `tx_ready` until the
|
||||
write callback and `write_array` drops when the ring is full, so a 64 KiB full-duplex echo loses one 64 byte
|
||||
tail on every buffer size.
|
||||
@@ -1,60 +0,0 @@
|
||||
# web_server
|
||||
|
||||
## State SSE on web_server_idf (#21109) and the HTTPD task stack (#21038)
|
||||
|
||||
`templates/web-server-sse-dut.yaml` (ESP32 classic, ESP-IDF, `web_server` version 3) publishes eight sensors every
|
||||
200 ms (small state events on the 1024 byte stack buffer) and three text sensors whose JSON carries the string twice
|
||||
(`value` and `state`): 600 chars for about 1.3 kB (the 2048 byte tail), 1800 chars for about 3.7 kB (tail grown to
|
||||
4096) and 2800 chars for about 5.7 kB, over the 5120 byte JSON room, which must log `State event does not fit`
|
||||
and never put a truncated frame on the wire. An `interval` lambda logs `uxTaskGetStackHighWaterMark()` of the loop
|
||||
task (`nullptr`) and of the HTTPD task (`xTaskGetHandle("httpd")`) every 5 s; the ESPHome loop task is `loopTask`
|
||||
on ESP32. Keep `power_save_mode: none`, and drive the device by address: mDNS names dropped out mid-run once.
|
||||
|
||||
`scripts/web_server/sse.py HOST SECONDS [--clients N] [--stall] [--churn CYCLES]` opens raw TCP connections to
|
||||
`/events`, decodes the chunked body and parses every `state` event as JSON; `--stall` adds a connection with a 2 kB
|
||||
receive buffer that never reads (the device must log `Closing stuck EventSource connection` after the 20 s stall
|
||||
timeout), `--churn` opens and resets a connection CYCLES times. `sse_cases.sh HOST KEY LABEL CAPTURE` runs the
|
||||
set: 1 client 60 s, 4 clients 60 s, a reader plus a stalled client 45 s, a reader plus 10 abrupt closes, then two
|
||||
clients with the "Burst" button (50 sensor and 50 text publishes in one loop pass). Pass: 0 invalid JSON on every
|
||||
client, the oversize sensor dropped with its warning on every publish, the stalled session closed after about
|
||||
20 s, no reset. The loop task watermark is a minimum since boot, so compare the value after the first client, after
|
||||
four clients and after the burst between the builds (the SSE split in #21109 left 1280 B more on the ESP32 classic).
|
||||
|
||||
For the HTTPD task, `web_server: auth: type: digest` (the default `auth` is Basic) and
|
||||
`scripts/web_server/httpd_cases.sh HOST USER PASS LABEL CAPTURE`: `httpmix.sh` sends a `curl --anyauth` request
|
||||
mix per round (page, `/sensor/<Name>`, `/text_sensor/<Name>`, `/switch/<Name>`, a `POST` with `Content-Length: 0`
|
||||
to `/switch/<Name>/toggle`, an unknown path, which the IDF server closes without a response, an unauthenticated
|
||||
request answered 401, and a 2 s `/events` stream), 20 rounds alone and 12 rounds next to two `ssecurl.sh` SSE
|
||||
clients. Entity URLs use the entity name, URL encoded, not an object id. The HTTPD watermark follows the deepest
|
||||
request of the boot; compare after the mix and after the SSE round, with two boots when the numbers are close.
|
||||
Results: https://github.com/esphome/esphome/pull/21109#issuecomment-6300582328 and
|
||||
https://github.com/esphome/esphome/pull/21038#issuecomment-6301310182
|
||||
|
||||
## Entity icon and device class readback (#21111)
|
||||
|
||||
Covers every path that reads an entity's icon or device class: the native API listing, MQTT discovery, the web_server
|
||||
`/events` listing and REST endpoints, and `dump_config`. `templates/entity-icon-dut.yaml` (ESP8266 board with wifi,
|
||||
encrypted api, ota, web_server and mqtt against a local broker) carries a sensor with a 63 character icon, one with no
|
||||
icon or device class, an internal sensor, and binary_sensor, switch, button, text_sensor, number, select, event, cover
|
||||
and text entities with icons and device classes. The per-run file supplies `name` and `broker_ip` through
|
||||
substitutions. Flash the PR and base builds under different names, then from the scratch directory:
|
||||
|
||||
```sh
|
||||
scripts/entity_icons/readback.sh DEVICE_IP KEY NAME BROKER_HOST cap-NAME.txt # once per build
|
||||
scripts/entity_icons/compare.sh ic-base ic-pr # api, web, mqttn, dump all identical
|
||||
```
|
||||
|
||||
`readback.sh` takes about 25 s once the device is on the network: 12 s of `mosquitto_sub` on `homeassistant/#` and
|
||||
`NAME/#`, the API listing (`api_list.py`, one JSON line per entity with icon, device class, unit, options and event
|
||||
types) and `web_dump.py` (6 s on `/events`, keeping only the listing rows that carry `domain`, then a GET of each
|
||||
listed id with `?detail=all` and one retry, because the ESP8266 async server occasionally leaves a request unanswered
|
||||
within 5 s). The web ids are `domain/Name`, not object ids, and `/event/<name>` has no GET handler (404 on every
|
||||
build). `mqtt_norm.py` drops the `dev` block (compile time) and the `NAME/debug` topic (heap probe), so a clean run
|
||||
differs in nothing. `dump_config` prints icons and device classes only for some domains; button, event and
|
||||
binary_sensor icons never appear there.
|
||||
|
||||
Found with this flow on 2026-10-21: since #19577 every ESP8266 `web_server` build that lists a cover, climate, lock,
|
||||
valve, update, alarm_control_panel or water_heater entity reboots with `Exception (3) LoadStoreErr` in
|
||||
`json::linked(const char *)` (the ROM `strlen` on a flash address), fixed by #21316. The cover in the template keeps
|
||||
that path covered; before #21316 is merged, apply its one line change to both trees or the web_server comparison
|
||||
cannot run.
|
||||
@@ -1,39 +0,0 @@
|
||||
# wifi
|
||||
|
||||
## `reboot_timeout` with a fallback AP (#9958)
|
||||
|
||||
Only one board runs the AP at a time, or stations join the wrong one. AP probe: bogus network,
|
||||
`ap: {ssid, password, ap_timeout: 5s}`, `reboot_timeout: 60s`, `logger: level: VERBOSE` (ESP32 and
|
||||
ESP8266 log `AP client connected MAC=` at verbose), `on_boot: logger.log: BOOT`. Station probes:
|
||||
`reboot_timeout: 0s`, `interval: 150s` running `wifi.disable`, `delay: 20s`, `wifi.enable` (60 s cycles
|
||||
are too short to cover the due moment). Pass pattern: "Can't connect; rebooting" exactly 60 s after boot
|
||||
with no station joined, no reboot for minutes while one is, then a reboot within a second of the last
|
||||
disconnect. The BW15 restarts its AP on every STA retry and cannot be tested this way.
|
||||
|
||||
## DHCP lease cache (#17767)
|
||||
|
||||
Cycle 20 s awake, `deep_sleep.enter 30s`, wake, 20 s, `App.safe_reboot()`, logging `millis()` at the
|
||||
`wifi.connected` condition. An RTS hardware reset must fall back to DHCP; a software reboot and a deep
|
||||
sleep wake must apply the cache. `esphome run --no-logs` silently skipped the upload on one board; use
|
||||
`upload` then `logs`.
|
||||
|
||||
## Wi-Fi Easy Connect (DPP) enrollee (#17934)
|
||||
|
||||
Only an Android phone configures: Settings, network details, Add device, Share Wi-Fi (the Wi-Fi list's
|
||||
QR scanner makes the phone an enrollee). Render the URI with the `qrcode` module and open the PNG.
|
||||
`esp32: framework: log_level: DEBUG` plus `sdkconfig_options: CONFIG_WPA_DEBUG_PRINT: y` prints the
|
||||
supplicant state machine.
|
||||
|
||||
## WISP bridge with an ethernet upstream (#7147)
|
||||
|
||||
`templates/wisp-ethernet-dut.yaml` (ESP32-S3 with a W5500, `wifi: ap:` with `ap_mode: WISP` and no station) and
|
||||
`templates/wisp-client.yaml` (D1 mini joining the bridge, `http_request` to a web server on the wired LAN and to
|
||||
`http://example.com/` every 15 s, `time: sntp`). Secrets: `wisp_psk` and `lan_http` (serve a text file on the host
|
||||
with `python -m http.server 8787 --bind 0.0.0.0` from a scratch directory). Judge by the client's `GET status 200`
|
||||
lines, the web server log showing the device's ethernet address as the source (NAT), the client's DHCP info (DNS1 is
|
||||
the LAN resolver) and `SNTP synced`. The device logs `Starting AP` and `DHCP DNS server: <resolver>` on its USB
|
||||
console; flashing over the air reboots it for repeat boots. Before the AP address and DHCP server moved ahead of the
|
||||
AP start (the fix in that PR), the first AP start failed on every boot with `esp_netif_dhcps_option failed: 20484`
|
||||
(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.
|
||||
@@ -1,10 +0,0 @@
|
||||
# zephyr
|
||||
|
||||
## Zephyr preferences on the nRF52840 dongle (#20810)
|
||||
|
||||
`templates/nrf52-preferences-dut.yaml`: logger on USB_CDC at VERBOSE, `flash_write_interval: 5s`, one
|
||||
`globals` with `restore_value` incremented every 15 s. Give each build its own global id so each first boot
|
||||
sees a never-saved key (settings survive a reflash). Flow per build: flash through the log port, 40 s capture
|
||||
of the first boot, then start a second capture and reboot with a 2001 baud touch on the dongle's other CDC
|
||||
port (the dfu rate callback is global, and the capture holds the log port); `serial_capture.py` reopens the
|
||||
log port after the USB re-enumeration and gets the buffered boot lines (`load setting`, `Loaded N settings`).
|
||||
@@ -1,17 +0,0 @@
|
||||
# zephyr_coredump
|
||||
|
||||
## zephyr_coredump crash and decode on nRF52 boards (#13122)
|
||||
|
||||
`templates/nrf52-coredump-crash-dut.yaml` (dongle; change `board:` to `adafruit_itsybitsy_nrf52840` for the
|
||||
ItsyBitsy): `zephyr_coredump:`, `dfu: true`, a `restore_value` global keyed by the `run` substitution
|
||||
(settings survive a reflash, so bump `run` for every new crash), and an `on_boot` sequence that sets the
|
||||
flag, yields 3 s so the globals loop saves it (a blocking lambda never gets there and the board crash-loops),
|
||||
syncs preferences, then writes to 0xDEADBEEF. Flash, keep every port closed for 80 s, then
|
||||
`scripts/zephyr_coredump/flow.sh LABEL PORT ELF [OUTDIR]` does the three opens (3 s cut, 100 s full print,
|
||||
20 s reopen) and calls `decode.sh`, which keeps the first complete `#CD:BEGIN#..END#` block, runs Zephyr's
|
||||
`coredump_serial_log_parser.py` and `coredump_gdbserver.py` from the sdk-nrf ESPHome installed and prints
|
||||
`bt` and `info threads` with its `arm-zephyr-eabi-gdb`. The ELF is `.pioenvs/<name>/zephyr/zephyr/zephyr.elf`.
|
||||
Expect about 9 KB dumps, 140 to 150 `#CD:` lines, a 673 ms loop warning for the erase, and `Has stored
|
||||
dump: 0` on the reopen. Check `compiled on` in every capture: another session flashing the same board
|
||||
mid-test looks exactly like a failed test otherwise. Boards without a network cannot exercise the API and
|
||||
MQTT delivery paths of the component; say so in the results.
|
||||
@@ -1,23 +0,0 @@
|
||||
# zwave_proxy
|
||||
|
||||
## zwave_proxy frame checksums on a live proxy (#20922)
|
||||
|
||||
A Z-Wave proxy (ESP32-S3 with the module on `usb_uart`) is a live device: flash it over OTA and read logs
|
||||
over the API, there is no serial console because the native USB is the host port for the module, so the
|
||||
boot-time `GET_NETWORK_IDS` exchange is never captured. Home Assistant's Z-Wave JS holds the single API
|
||||
subscription (it polls `0x3B` every 30 s and resubscribes after every reboot), so do not subscribe from a
|
||||
script, and keep the device `name:` so it stays on Z-Wave JS; give each build its own scratch directory
|
||||
instead.
|
||||
|
||||
1. `logger: level: VERY_VERBOSE` with `logs: zwave_proxy: VERY_VERBOSE` and DEBUG for the rest: the
|
||||
`Sending:`, `Received frame:` and `CHECKSUM Received ... Calculated` lines are `ESP_LOGVV`, which needs
|
||||
the compile-time level.
|
||||
2. `md5` the two `firmware.ota.bin` files to be sure the A and B builds differ, then `esphome upload
|
||||
--device <name>.local` and a `timeout 330 esphome logs --device <name>.local` capture started right after
|
||||
the OTA to catch the resubscribe traffic.
|
||||
3. `scripts/zwave_proxy/verify_checksums.py <captures>` recomputes the XOR (init 0xFF, LENGTH..payload) over
|
||||
every logged frame and counts bad checksums and ACK/NAK sent and received; `scripts/zwave_proxy/devinfo.py
|
||||
<name>.local` prints the firmware version, compile time and the Home ID from the API (a Home ID proves the
|
||||
device-built `GET_NETWORK_IDS` frame was accepted at boot).
|
||||
4. Pre-existing: one `zwave_proxy took a long time for an operation` warning on the first frame after the
|
||||
log client connects, caused by VERY_VERBOSE logging; it appears on dev too.
|
||||
@@ -1,211 +0,0 @@
|
||||
"""Plaintext native API client that lists user actions with their raw argument fields and executes one.
|
||||
|
||||
usage: rawactions.py HOST list
|
||||
rawactions.py HOST exec ACTION key=value [...] (every argument must be given; types from the listing)
|
||||
Fields of ListEntitiesServicesArgument: 1 name, 2 type, 3 description, 4 example, 5 optional, 6 default_value.
|
||||
"""
|
||||
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
|
||||
HOST = sys.argv[1]
|
||||
CMD = sys.argv[2]
|
||||
ARGS = sys.argv[3:]
|
||||
TYPE_NAMES = {
|
||||
0: "bool",
|
||||
1: "int",
|
||||
2: "float",
|
||||
3: "string",
|
||||
4: "bool[]",
|
||||
5: "int[]",
|
||||
6: "float[]",
|
||||
7: "string[]",
|
||||
}
|
||||
|
||||
|
||||
def varint(v: int) -> bytes:
|
||||
out = bytearray()
|
||||
while True:
|
||||
b = v & 0x7F
|
||||
v >>= 7
|
||||
if v:
|
||||
out.append(b | 0x80)
|
||||
else:
|
||||
out.append(b)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def svarint(v: int) -> bytes:
|
||||
return varint((v << 1) ^ (v >> 63))
|
||||
|
||||
|
||||
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) -> list[tuple[int, int, object]]:
|
||||
out = []
|
||||
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] # fixed32, caller unpacks
|
||||
pos += 4
|
||||
else:
|
||||
raise ValueError(f"wire type {wt}")
|
||||
out.append((fnum, wt, v))
|
||||
return out
|
||||
|
||||
|
||||
def frame(mtype: int, payload: bytes) -> bytes:
|
||||
return b"\x00" + varint(len(payload)) + varint(mtype) + payload
|
||||
|
||||
|
||||
def field_bytes(fnum: int, data: bytes) -> bytes:
|
||||
return varint((fnum << 3) | 2) + varint(len(data)) + data
|
||||
|
||||
|
||||
def field_varint(fnum: int, v: int) -> bytes:
|
||||
return varint((fnum << 3) | 0) + varint(v)
|
||||
|
||||
|
||||
def recv_frames(
|
||||
sock: socket.socket, until: set[int], limit: float = 5.0
|
||||
) -> list[tuple[int, bytes]]:
|
||||
sock.settimeout(limit)
|
||||
buf = bytearray()
|
||||
frames = []
|
||||
while True:
|
||||
try:
|
||||
chunk = sock.recv(4096)
|
||||
except TimeoutError:
|
||||
return frames
|
||||
if not chunk:
|
||||
return frames
|
||||
buf += chunk
|
||||
while True:
|
||||
if len(buf) < 3:
|
||||
break
|
||||
if buf[0] != 0:
|
||||
raise ValueError("not plaintext")
|
||||
try:
|
||||
ln, p = decode_varint(buf, 1)
|
||||
mt, p = decode_varint(buf, p)
|
||||
except IndexError:
|
||||
break
|
||||
if len(buf) < p + ln:
|
||||
break
|
||||
frames.append((mt, bytes(buf[p : p + ln])))
|
||||
del buf[: p + ln]
|
||||
if mt in until:
|
||||
return frames
|
||||
|
||||
|
||||
def main() -> None:
|
||||
sock = socket.create_connection((HOST, 6053), timeout=5)
|
||||
sock.sendall(
|
||||
frame(
|
||||
1, field_bytes(1, b"rawactions") + field_varint(2, 1) + field_varint(3, 10)
|
||||
)
|
||||
) # HelloRequest
|
||||
recv_frames(sock, {2})
|
||||
sock.sendall(frame(3, b"")) # ConnectRequest, no password
|
||||
recv_frames(sock, {4})
|
||||
sock.sendall(frame(11, b"")) # ListEntitiesRequest
|
||||
frames = recv_frames(sock, {19})
|
||||
services = {}
|
||||
for mt, payload in frames:
|
||||
if mt != 41:
|
||||
continue
|
||||
name = key = None
|
||||
args = []
|
||||
for fnum, _, v in fields(payload):
|
||||
if fnum == 1:
|
||||
name = v.decode()
|
||||
elif fnum == 2:
|
||||
key = struct.unpack("<I", v)[0]
|
||||
elif fnum == 3:
|
||||
a = {
|
||||
"name": None,
|
||||
"type": 0,
|
||||
"description": None,
|
||||
"example": None,
|
||||
"optional": None,
|
||||
"default": None,
|
||||
}
|
||||
for af, _, av in fields(v):
|
||||
if af == 1:
|
||||
a["name"] = av.decode()
|
||||
elif af == 2:
|
||||
a["type"] = av
|
||||
elif af == 3:
|
||||
a["description"] = av.decode()
|
||||
elif af == 4:
|
||||
a["example"] = av.decode()
|
||||
elif af == 5:
|
||||
a["optional"] = bool(av)
|
||||
elif af == 6:
|
||||
a["default"] = av.decode()
|
||||
else:
|
||||
a[f"field{af}"] = av
|
||||
args.append(a)
|
||||
services[name] = (key, args)
|
||||
if CMD == "list":
|
||||
for name, (key, args) in services.items():
|
||||
print(f"action {name} key={key}")
|
||||
for a in args:
|
||||
extra = {
|
||||
k: v
|
||||
for k, v in a.items()
|
||||
if k not in ("name", "type") and v is not None
|
||||
}
|
||||
print(f" {a['name']}: {TYPE_NAMES.get(a['type'], a['type'])} {extra}")
|
||||
return
|
||||
name = ARGS[0]
|
||||
key, args = services[name]
|
||||
payload = varint((1 << 3) | 5) + struct.pack("<I", key)
|
||||
given = dict(kv.split("=", 1) for kv in ARGS[1:])
|
||||
for a in args:
|
||||
if a["name"] not in given:
|
||||
if os.environ.get("ALLOW_MISSING"):
|
||||
continue # leave the argument out of the request on purpose
|
||||
sys.exit(f"missing {a['name']}")
|
||||
raw = given[a["name"]]
|
||||
t = a["type"]
|
||||
if t == 0:
|
||||
av = field_varint(1, 1 if raw.lower() == "true" else 0)
|
||||
elif t == 1:
|
||||
av = varint((5 << 3) | 0) + svarint(int(raw)) # sint32 int_
|
||||
elif t == 2:
|
||||
av = varint((3 << 3) | 5) + struct.pack("<f", float(raw))
|
||||
elif t == 3:
|
||||
av = field_bytes(4, raw.encode())
|
||||
elif t == 5:
|
||||
av = b"".join(
|
||||
varint((7 << 3) | 0) + svarint(int(x)) for x in raw.split(",") if x
|
||||
) # repeated sint32 int_array
|
||||
else:
|
||||
sys.exit(f"type {t} not supported here")
|
||||
payload += field_bytes(2, av)
|
||||
sock.sendall(frame(42, payload)) # ExecuteServiceRequest
|
||||
print(f"sent {name} with {given}")
|
||||
sock.close()
|
||||
|
||||
|
||||
main()
|
||||
@@ -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,33 +0,0 @@
|
||||
"""Press a template button on the test device over the API, or list its buttons.
|
||||
|
||||
usage: api_button.py HOST KEY list | press "Button name" [...] (KEY of - means a plaintext API)
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from aioesphomeapi import APIClient, ButtonInfo
|
||||
|
||||
HOST, KEY = sys.argv[1], sys.argv[2]
|
||||
CMD, ARGS = sys.argv[3], sys.argv[4:]
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
c = APIClient(HOST, 6053, None, noise_psk=None if KEY == "-" else KEY)
|
||||
await c.connect(login=True)
|
||||
ents, _ = await c.list_entities_services()
|
||||
buttons = {e.name: e for e in ents if isinstance(e, ButtonInfo)}
|
||||
if CMD == "list":
|
||||
print("\n".join(sorted(buttons)))
|
||||
else:
|
||||
for name in ARGS:
|
||||
if name not in buttons:
|
||||
sys.exit(f"no button named {name!r}; have {sorted(buttons)}")
|
||||
c.button_command(buttons[name].key)
|
||||
print("pressed", name)
|
||||
await asyncio.sleep(0.3)
|
||||
await asyncio.sleep(0.5)
|
||||
await c.disconnect()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,73 +0,0 @@
|
||||
"""Per wake cycle timings from a serial capture of the deep sleep timing config.
|
||||
|
||||
usage: cycles.py CAPTURE [LABEL]
|
||||
A cycle starts at the boot banner; the numbers are the device's millis() from the timing lines, and the
|
||||
capture clock gap from the first line of the cycle to the "Dialing" line.
|
||||
"""
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
import statistics
|
||||
import sys
|
||||
|
||||
cap = (
|
||||
pathlib.Path(sys.argv[1]).read_text(encoding="utf-8", errors="replace").splitlines()
|
||||
)
|
||||
label = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
TS = re.compile(r"^\[(\d\d):(\d\d):(\d\d)(?:\.(\d+))?\]")
|
||||
|
||||
|
||||
def secs(line):
|
||||
m = TS.match(line)
|
||||
if not m:
|
||||
return None
|
||||
h, mi, s, f = m.groups()
|
||||
return int(h) * 3600 + int(mi) * 60 + int(s) + (int(f) / 10 ** len(f) if f else 0)
|
||||
|
||||
|
||||
cycles = []
|
||||
cur = None
|
||||
for line in cap:
|
||||
if "rst:0x" in line or (cur is None and "Log initialized" in line):
|
||||
cur = {"start": secs(line), "reset": line.split("]", 1)[-1].strip()[:60]}
|
||||
cycles.append(cur)
|
||||
continue
|
||||
if cur is None:
|
||||
continue
|
||||
if "Dialing" in line:
|
||||
cur.setdefault("dial_cap", secs(line))
|
||||
m = re.search(r"wifi connected at (\d+) ms", line)
|
||||
if m:
|
||||
cur.setdefault("wifi", int(m.group(1)))
|
||||
m = re.search(r"client connected at (\d+) ms \((.*?)\)", line)
|
||||
if m and "client" not in cur:
|
||||
cur["client"] = int(m.group(1))
|
||||
cur["who"] = m.group(2)
|
||||
m = re.search(r"first HA state '(.*?)' at (\d+) ms", line)
|
||||
if m and "state" not in cur:
|
||||
cur["state"] = int(m.group(2))
|
||||
|
||||
print(f"{label} cycles: {len(cycles)}")
|
||||
print(
|
||||
f"{'n':>2} {'wifi ms':>8} {'dial +ms':>9} {'client ms':>10} {'state ms':>9} {'client-wifi':>11} {'state-client':>12} client reset"
|
||||
)
|
||||
for i, c in enumerate(cycles, 1):
|
||||
dial = ""
|
||||
if c.get("dial_cap") is not None and c.get("start") is not None:
|
||||
dial = f"{(c['dial_cap'] - c['start']) * 1000:.0f}"
|
||||
cw = c["client"] - c["wifi"] if "client" in c and "wifi" in c else ""
|
||||
sc = c["state"] - c["client"] if "state" in c and "client" in c else ""
|
||||
print(
|
||||
f"{i:>2} {c.get('wifi', ''):>8} {dial:>9} {c.get('client', ''):>10} {c.get('state', ''):>9} {cw:>11} {sc:>12} {c.get('who', '')} {c.get('reset', '')[:28]}"
|
||||
)
|
||||
for c in cycles:
|
||||
if "client" in c and "wifi" in c:
|
||||
c["client-wifi"] = c["client"] - c["wifi"]
|
||||
if "state" in c and "client" in c:
|
||||
c["state-client"] = c["state"] - c["client"]
|
||||
for key in ("wifi", "client", "state", "client-wifi", "state-client"):
|
||||
vals = [c[key] for c in cycles if key in c]
|
||||
if vals:
|
||||
print(
|
||||
f"{key}: n={len(vals)} min={min(vals)} median={statistics.median(vals):.0f} max={max(vals)}"
|
||||
)
|
||||
@@ -1,107 +0,0 @@
|
||||
"""Per Wi-Fi drop timings from a serial capture of the outgoing connection timing config.
|
||||
|
||||
usage: wificycles.py CAPTURE [LABEL]
|
||||
A cycle starts at "wifi cycle disabling"; the numbers are the device's millis() from the timing lines.
|
||||
"dial" says whether the client that connected first came from the device's own dial ("Dialing" seen after the
|
||||
reconnect and before the hello) or from an incoming connection ("Accept" seen first).
|
||||
"""
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
import statistics
|
||||
import sys
|
||||
|
||||
cap = (
|
||||
pathlib.Path(sys.argv[1]).read_text(encoding="utf-8", errors="replace").splitlines()
|
||||
)
|
||||
label = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
TS = re.compile(r"^\[(\d\d):(\d\d):(\d\d)(?:\.(\d+))?\]")
|
||||
|
||||
|
||||
def secs(line):
|
||||
m = TS.match(line)
|
||||
if not m:
|
||||
return None
|
||||
h, mi, se, f = m.groups()
|
||||
return int(h) * 3600 + int(mi) * 60 + int(se) + (int(f) / 10 ** len(f) if f else 0)
|
||||
|
||||
|
||||
cycles = []
|
||||
cur = None
|
||||
loop_max = []
|
||||
for line in cap:
|
||||
m = re.search(r"loop time max (\d+) ms", line)
|
||||
if m:
|
||||
loop_max.append(int(m.group(1)))
|
||||
if "wifi cycle disabling" in line:
|
||||
cur = {"order": []}
|
||||
cycles.append(cur)
|
||||
continue
|
||||
if cur is None:
|
||||
continue
|
||||
m = re.search(r"wifi connected at (\d+) ms", line)
|
||||
if m and "wifi" not in cur:
|
||||
cur["wifi"] = int(m.group(1))
|
||||
cur["wifi_cap"] = secs(line)
|
||||
if "Dialing" in line:
|
||||
cur["order"].append("dial")
|
||||
cur["dials"] = cur.get("dials", 0) + 1
|
||||
if "dial_cap" not in cur and "wifi_cap" in cur:
|
||||
cur["dial_cap"] = secs(line)
|
||||
elif "dial_cap" not in cur and "dial_before_wifi_cap" not in cur:
|
||||
cur["dial_before_wifi_cap"] = secs(line)
|
||||
if (
|
||||
re.search(r"client disconnected at \d+ ms \(\d+\.\d+\.\d+\.\d+\)", line)
|
||||
and "wifi" in cur
|
||||
and "client" not in cur
|
||||
):
|
||||
cur["dial_closed"] = cur.get("dial_closed", 0) + 1
|
||||
if "Accept " in line and "wifi" in cur:
|
||||
cur["order"].append("accept")
|
||||
m = re.search(r"client connected at (\d+) ms \((.*?)\)", line)
|
||||
if m and "wifi" in cur and "client" not in cur:
|
||||
cur["client"] = int(m.group(1))
|
||||
cur["who"] = m.group(2).split(" ")[0]
|
||||
cur["via"] = cur["order"][0] if cur["order"] else "?"
|
||||
m = re.search(r"Connect (failed|timeout)", line)
|
||||
if m:
|
||||
cur.setdefault("connect_errors", 0)
|
||||
cur["connect_errors"] += 1
|
||||
|
||||
print(f"{label} cycles: {len(cycles)}")
|
||||
print(
|
||||
f"{'n':>2} {'wifi ms':>8} {'dial-wifi cap ms':>16} {'client ms':>10} {'client-wifi':>11} via dials closed client"
|
||||
)
|
||||
for i, c in enumerate(cycles, 1):
|
||||
cw = c["client"] - c["wifi"] if "client" in c and "wifi" in c else ""
|
||||
c["client-wifi"] = cw
|
||||
dw = ""
|
||||
if "wifi_cap" in c and c.get("wifi_cap") is not None:
|
||||
# the first dial of the cycle, whether it was logged before or after the Wi-Fi line
|
||||
if c.get("dial_before_wifi_cap") is not None:
|
||||
dw = f"{(c['dial_before_wifi_cap'] - c['wifi_cap']) * 1000:.0f}"
|
||||
elif "dial_cap" in c and c["dial_cap"] is not None:
|
||||
dw = f"{(c['dial_cap'] - c['wifi_cap']) * 1000:.0f}"
|
||||
c["dial-wifi"] = dw
|
||||
print(
|
||||
f"{i:>2} {c.get('wifi', ''):>8} {dw:>16} {c.get('client', ''):>10} {cw:>11} {c.get('via', ''):7s} {c.get('dials', 0):>5} {c.get('dial_closed', 0):>6} {c.get('who', '')}"
|
||||
)
|
||||
for via in ("dial", "accept"):
|
||||
vals = [
|
||||
c["client-wifi"]
|
||||
for c in cycles
|
||||
if c.get("via") == via and c["client-wifi"] != ""
|
||||
]
|
||||
if vals:
|
||||
print(
|
||||
f"client-wifi via {via}: n={len(vals)} min={min(vals)} median={statistics.median(vals):.0f} max={max(vals)}"
|
||||
)
|
||||
dws = [float(c["dial-wifi"]) for c in cycles if c.get("dial-wifi") not in ("", None)]
|
||||
if dws:
|
||||
print(
|
||||
f"dial after wifi connected (capture clock): n={len(dws)} min={min(dws):.0f} median={statistics.median(dws):.0f} max={max(dws):.0f}"
|
||||
)
|
||||
if loop_max:
|
||||
print(
|
||||
f"loop time max per 5 s: n={len(loop_max)} min={min(loop_max)} median={statistics.median(loop_max):.0f} max={max(loop_max)}"
|
||||
)
|
||||
@@ -1,71 +0,0 @@
|
||||
"""Subscribe to states and logs of a device over the API for N seconds and summarize its float sensors.
|
||||
|
||||
usage: observe.py IP SECONDS OUTFILE [NAME_FILTER]
|
||||
|
||||
Every float sensor state whose entity name contains NAME_FILTER (default: all) is appended to OUTFILE
|
||||
with a relative timestamp, log lines are appended with a LOG prefix, and a one-line summary per sensor
|
||||
(count, min, max, last) plus the warning and error count is printed at the end.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
|
||||
from aioesphomeapi import APIClient, LogLevel
|
||||
|
||||
IP, SECS, OUT = sys.argv[1], float(sys.argv[2]), sys.argv[3]
|
||||
FILTER = sys.argv[4] if len(sys.argv) > 4 else ""
|
||||
# ESPHome LOG_SECRET span; one cut off before its end marker is secret to the end of the line
|
||||
SECRET = re.compile(r"\x1b\[8m.*?(?:\x1b\[28m|$)", re.DOTALL)
|
||||
ANSI = re.compile(r"\x1b\[[0-9;]*m")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
c = APIClient(IP, 6053, None)
|
||||
await c.connect(login=True)
|
||||
di = await c.device_info()
|
||||
ents, _ = await c.list_entities_services()
|
||||
names = {e.key: e.name for e in ents}
|
||||
readings: dict[str, list[float]] = {}
|
||||
warnings: list[str] = []
|
||||
t0 = time.monotonic()
|
||||
with pathlib.Path(OUT).open("w", encoding="utf-8") as out:
|
||||
out.write(
|
||||
f"device {di.name} version {di.esphome_version} compiled {di.compilation_time}\n"
|
||||
)
|
||||
|
||||
def on_state(st) -> None:
|
||||
n = names.get(st.key, str(st.key))
|
||||
if FILTER in n and hasattr(st, "state") and isinstance(st.state, float):
|
||||
readings.setdefault(n, []).append(st.state)
|
||||
out.write(f"[{time.monotonic() - t0:6.1f}] {n}: {st.state}\n")
|
||||
out.flush()
|
||||
|
||||
def on_log(msg) -> None:
|
||||
line = (
|
||||
msg.message.decode(errors="replace")
|
||||
if isinstance(msg.message, bytes)
|
||||
else msg.message
|
||||
)
|
||||
line = ANSI.sub("", SECRET.sub("<secret>", line))
|
||||
out.write(f"[{time.monotonic() - t0:6.1f}] LOG {line}\n")
|
||||
out.flush()
|
||||
if "[W]" in line or "[E]" in line or "Invalid" in line:
|
||||
warnings.append(line)
|
||||
|
||||
c.subscribe_states(on_state)
|
||||
c.subscribe_logs(on_log, log_level=LogLevel.LOG_LEVEL_VERBOSE)
|
||||
await asyncio.sleep(SECS)
|
||||
await c.disconnect()
|
||||
summary = "; ".join(
|
||||
f"{k.split()[-1]} n={len(v)} min={min(v):.3f} max={max(v):.3f} last={v[-1]:.3f}"
|
||||
for k, v in sorted(readings.items())
|
||||
)
|
||||
print(f"{di.compilation_time}: {summary}; warnings/errors {len(warnings)}")
|
||||
for w in warnings[:5]:
|
||||
print(" ", w)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,27 +0,0 @@
|
||||
#!/bin/zsh
|
||||
# usage: run_obs.sh IP SECONDS LABEL [OUTDIR] [NAME_FILTER]
|
||||
# Observes states and logs over the API with a concurrent ping and prints a summary: the device-side
|
||||
# "frames parsed" counter per 10 s, gaps over 5 s between voltage updates seen by the API, and warnings.
|
||||
# Needs a python with aioesphomeapi (PYTHON, default python3).
|
||||
D=${0:A:h}
|
||||
IP=$1; SECS=$2; L=$3; S=${4:-.}; F=${5:-}
|
||||
PY=${PYTHON:-python3}
|
||||
setopt pipefail
|
||||
ping -i 1 -c $SECS $IP > $S/ping-$L.txt 2>&1 &
|
||||
P=$!
|
||||
if ! timeout $((SECS + 40)) $PY $D/observe.py $IP $SECS $S/obs-$L.txt "$F" 2>&1 | sed "s/$IP/<ip>/g"; then
|
||||
echo "observe.py failed or timed out, no summary"; wait $P; exit 1
|
||||
fi
|
||||
wait $P
|
||||
echo "ping: $(tail -2 $S/ping-$L.txt | head -1 | sed "s/$IP/<ip>/g") $(tail -1 $S/ping-$L.txt)"
|
||||
python3 - "$S/obs-$L.txt" <<'PY'
|
||||
import re, sys
|
||||
txt = open(sys.argv[1]).read()
|
||||
fr = [int(m.group(1)) for m in re.finditer(r"frames parsed: (\d+) in 10 s", txt)]
|
||||
print(f"device frame counter per 10 s: n={len(fr)} min={min(fr) if fr else None} max={max(fr) if fr else None} mean={sum(fr)/len(fr) if fr else 0:.1f}")
|
||||
ts = [float(m.group(1)) for m in re.finditer(r"^\[\s*([0-9.]+)\] .*Voltage: ", txt, re.M)]
|
||||
gaps = [round(b - a, 1) for a, b in zip(ts, ts[1:]) if b - a > 5]
|
||||
print(f"API voltage updates {len(ts)}, gaps over 5 s: {gaps}")
|
||||
warn = [l for l in txt.splitlines() if "LOG" in l and ("[W]" in l or "[E]" in l or "Invalid" in l)]
|
||||
print(f"warnings/errors in log: {len(warn)}", *warn[:3], sep="\n ")
|
||||
PY
|
||||
@@ -1,22 +0,0 @@
|
||||
#!/bin/sh
|
||||
# cases.sh DEV_IP KEY CAPTURE LABEL : the SEN0395 flow (settings, switches, junk lines, factory reset, reset) against
|
||||
# templates/dfrobot-sen0395-dut.yaml, with a serial capture of the device running into CAPTURE
|
||||
D=$1; K=$2; LOG=$3; LABEL=$4; PY=${PYTHON:-python3}; CTL="$(dirname "$0")/ctl.py"
|
||||
show() { tail -n +$(($1+1)) "$LOG" | sed 's/\x1b\[[0-9;]*m//g' | grep -a 'dfrobot\|Detected\|\[W\]\|\[E\]\|sen\]' | grep -a -v 'JYBSS\|took a long time' | cut -c1-200; }
|
||||
step() { n0=$(wc -l < "$LOG"); echo "=== $LABEL: $1 ($(date +%T))"; shift; $PY "$CTL" "$D" "$K" "$@" || { rc=$?; echo "driver failed ($rc), aborting"; exit $rc; }; echo "--- device log:"; show "$n0"; }
|
||||
frames() { echo "frames: $(tail -n +$(($1+1)) "$LOG" | grep -a -c 'JYBSS,1') present, $(tail -n +$(($1+1)) "$LOG" | grep -a -c 'JYBSS,0') absent"; }
|
||||
n0=$(wc -l < "$LOG"); echo "=== $LABEL: 20 s of frames ($(date +%T))"; sleep 20; frames "$n0"
|
||||
step "range 0 to 3 m" "press:Range 0 to 3m" wait:12
|
||||
step "range 0 to 9 m" "press:Range 0 to 9m" wait:12
|
||||
step "latency 1 s / 2 s" "press:Latency 1s 2s" wait:12
|
||||
step "latency 0 / 0" "press:Latency 0 0" wait:12
|
||||
step "sensitivity 7" "press:Sensitivity 7" wait:12
|
||||
step "LED off then on" "sw:LED=off" wait:10 "sw:LED=on" wait:10
|
||||
step "sensor active off then on" "sw:Sensor active=off" wait:10 "sw:Sensor active=on" wait:10
|
||||
step "presence via UART off then on" "sw:Presence via UART=off" wait:10 "sw:Presence via UART=on" wait:10
|
||||
step "start after boot off then on" "sw:Start after boot=off" wait:10 "sw:Start after boot=on" wait:10
|
||||
for n in 100 160 200 220 240 256; do step "junk line of $n bytes" "press:Junk $n" wait:7; done
|
||||
step "junk 220 then a command" "press:Junk 220" wait:6 "press:Range 0 to 9m" wait:12
|
||||
step "factory reset" "press:Factory reset" wait:15
|
||||
step "reset" "press:Reset" wait:15
|
||||
n0=$(wc -l < "$LOG"); echo "=== $LABEL: 20 s of frames after ($(date +%T))"; sleep 20; frames "$n0"
|
||||
@@ -1,63 +0,0 @@
|
||||
"""Drive the SEN0395 test device over the API and print its binary sensor and switch updates.
|
||||
usage: ctl.py HOST KEY(- for plaintext) OP [OP ...] OP: press:NAME | sw:NAME=on|off | wait:SECONDS
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
import time
|
||||
|
||||
from aioesphomeapi import (
|
||||
APIClient,
|
||||
BinarySensorState,
|
||||
ButtonInfo,
|
||||
SwitchInfo,
|
||||
SwitchState,
|
||||
)
|
||||
|
||||
HOST, KEY = sys.argv[1], sys.argv[2]
|
||||
OPS = sys.argv[3:]
|
||||
T0 = time.time()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
c = APIClient(HOST, 6053, None, noise_psk=None if KEY == "-" else KEY)
|
||||
await c.connect(login=True)
|
||||
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)}
|
||||
switches = {e.name: e for e in ents if isinstance(e, SwitchInfo)}
|
||||
|
||||
def on_state(s) -> None:
|
||||
e = by_key.get(s.key)
|
||||
if isinstance(s, BinarySensorState):
|
||||
print(
|
||||
f"{time.time() - T0:7.3f} BIN {e.name} = {'ON' if s.state else 'off'}"
|
||||
)
|
||||
elif isinstance(s, SwitchState):
|
||||
print(
|
||||
f"{time.time() - T0:7.3f} SW {e.name} = {'on' if s.state else 'off'}"
|
||||
)
|
||||
|
||||
c.subscribe_states(on_state)
|
||||
await asyncio.sleep(1.0)
|
||||
for op in OPS:
|
||||
kind, _, rest = op.partition(":")
|
||||
if kind == "wait":
|
||||
await asyncio.sleep(float(rest))
|
||||
elif kind == "press":
|
||||
if rest not in buttons:
|
||||
sys.exit(f"no button {rest!r}; have {sorted(buttons)}")
|
||||
print(f"{time.time() - T0:7.3f} >>> press {rest}")
|
||||
c.button_command(buttons[rest].key)
|
||||
elif kind == "sw":
|
||||
name, _, val = rest.partition("=")
|
||||
if name not in switches:
|
||||
sys.exit(f"no switch {name!r}; have {sorted(switches)}")
|
||||
print(f"{time.time() - T0:7.3f} >>> switch {name} {val}")
|
||||
c.switch_command(switches[name].key, val == "on")
|
||||
else:
|
||||
sys.exit(f"unknown op {op!r}")
|
||||
await c.disconnect()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,56 +0,0 @@
|
||||
"""List every entity over the native API with its icon, device class and unit: one sorted JSON line each.
|
||||
|
||||
usage: api_list.py HOST KEY OUT
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from aioesphomeapi import APIClient
|
||||
|
||||
HOST, KEY, OUT = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
c = APIClient(HOST, 6053, None, noise_psk=KEY)
|
||||
await c.connect(login=True)
|
||||
ents, _ = await c.list_entities_services()
|
||||
rows = []
|
||||
for e in ents:
|
||||
row = {
|
||||
"type": type(e).__name__,
|
||||
"name": e.name,
|
||||
"object_id": e.object_id,
|
||||
"icon": e.icon,
|
||||
}
|
||||
for k in (
|
||||
"device_class",
|
||||
"unit_of_measurement",
|
||||
"event_types",
|
||||
"options",
|
||||
"mode",
|
||||
):
|
||||
if hasattr(e, k):
|
||||
v = getattr(e, k)
|
||||
row[k] = (
|
||||
list(v)
|
||||
if isinstance(v, (list, tuple))
|
||||
else (v.name if hasattr(v, "name") else v)
|
||||
)
|
||||
row["entity_category"] = (
|
||||
e.entity_category.name
|
||||
if hasattr(e.entity_category, "name")
|
||||
else e.entity_category
|
||||
)
|
||||
row["disabled_by_default"] = e.disabled_by_default
|
||||
rows.append(row)
|
||||
rows.sort(key=lambda r: (r["type"], r["name"]))
|
||||
with pathlib.Path(OUT).open("w", encoding="utf-8") as f:
|
||||
f.writelines(json.dumps(r, sort_keys=True) + "\n" for r in rows)
|
||||
print(f"{len(rows)} entities listed")
|
||||
await c.disconnect()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,13 +0,0 @@
|
||||
#!/bin/sh
|
||||
# compare.sh NAME_A NAME_B : diff the readback.sh outputs of two device names (api, web, mqttn and, when present, dump)
|
||||
# after replacing each name with DEV. Exit 1 when any pair differs; the diffs stay in cmp-KIND.diff.
|
||||
A=$1; B=$2; rc=0
|
||||
[ -n "$A" ] && [ -n "$B" ] || { echo "usage: compare.sh NAME_A NAME_B"; exit 2; }
|
||||
for k in api web mqttn dump; do
|
||||
ext=jsonl; [ $k = dump ] && ext=txt
|
||||
[ -f "$PWD/$k-$A.$ext" ] && [ -f "$PWD/$k-$B.$ext" ] || { echo "$k: missing"; [ $k = dump ] || rc=1; continue; }
|
||||
sed "s/$A/DEV/g; s/$(echo "$A" | tr - _)/DEV/g" "$PWD/$k-$A.$ext" > "$PWD/cmp-$k-a.txt"
|
||||
sed "s/$B/DEV/g; s/$(echo "$B" | tr - _)/DEV/g" "$PWD/$k-$B.$ext" > "$PWD/cmp-$k-b.txt"
|
||||
if diff -u "$PWD/cmp-$k-a.txt" "$PWD/cmp-$k-b.txt" > "$PWD/cmp-$k.diff"; then echo "$k: identical ($(wc -l < "$PWD/cmp-$k-b.txt" | tr -d ' ') lines)"; else echo "$k: DIFFERS"; head -20 "$PWD/cmp-$k.diff"; rc=1; fi
|
||||
done
|
||||
exit $rc
|
||||
@@ -1,37 +0,0 @@
|
||||
"""Normalise mosquitto_sub output (topic TAB payload) for one device: drop other devices, replace the name, drop dev block.
|
||||
|
||||
usage: mqtt_norm.py IN NAME OUT
|
||||
"""
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
IN, NAME, OUT = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
rows = {}
|
||||
with pathlib.Path(IN).open(encoding="utf-8") as f:
|
||||
for line in f:
|
||||
topic, _, payload = line.rstrip("\n").partition("\t")
|
||||
if (
|
||||
f"/{NAME}/" not in topic and not topic.startswith(f"{NAME}/")
|
||||
) or topic == f"{NAME}/debug":
|
||||
continue
|
||||
topic = topic.replace(NAME, "DEV")
|
||||
try:
|
||||
obj = json.loads(payload)
|
||||
except ValueError:
|
||||
rows[topic] = payload.replace(NAME, "DEV")
|
||||
continue
|
||||
if isinstance(obj, dict):
|
||||
obj.pop("dev", None)
|
||||
obj = {
|
||||
k: (v.replace(NAME, "DEV") if isinstance(v, str) else v)
|
||||
for k, v in obj.items()
|
||||
}
|
||||
rows[topic] = obj
|
||||
with pathlib.Path(OUT).open("w", encoding="utf-8") as f:
|
||||
f.writelines(
|
||||
json.dumps({"topic": t, "payload": rows[t]}, sort_keys=True) + "\n"
|
||||
for t in sorted(rows)
|
||||
)
|
||||
print(f"{len(rows)} topics for {NAME}")
|
||||
@@ -1,18 +0,0 @@
|
||||
#!/bin/sh
|
||||
# readback.sh DEVICE_IP KEY NAME BROKER_HOST [CAPTURE] : record how a device built from templates/entity-icon-dut.yaml
|
||||
# reports its entity icons and device classes: the native API listing (api-NAME.jsonl), the retained MQTT discovery
|
||||
# payloads and states (mqtt-NAME.txt, normalised to mqttn-NAME.jsonl with the device name replaced and the debug topic
|
||||
# dropped), the web_server /events listing plus every REST endpoint with ?detail=all (web-NAME.jsonl) and, when a
|
||||
# serial CAPTURE is given, the dump_config Icon and Device Class lines (dump-NAME.txt, timestamps and line numbers
|
||||
# removed). KEY as for api_button.py. Outputs go to the working directory; compare two names with compare.sh.
|
||||
HERE=$(cd "$(dirname "$0")" && pwd); PY=${PYTHON:-python3}; DEV=$1; KEY=$2; N=$3; B=$4; CAP=$5; rc=0; TAB=$(printf '\t')
|
||||
[ -n "$DEV" ] && [ -n "$KEY" ] && [ -n "$N" ] && [ -n "$B" ] || { echo "usage: readback.sh DEVICE_IP KEY NAME BROKER_HOST [CAPTURE]"; exit 2; }
|
||||
timeout 12 mosquitto_sub -h "$B" -v -t 'homeassistant/#' -t "$N/#" -F "%t$TAB%p" > "$PWD/mqtt-$N.txt" 2> "$PWD/mqtt-$N.err"
|
||||
$PY "$HERE/mqtt_norm.py" "$PWD/mqtt-$N.txt" "$N" "$PWD/mqttn-$N.jsonl" || rc=1
|
||||
$PY "$HERE/api_list.py" "$DEV" "$KEY" "$PWD/api-$N.jsonl" || { echo "API listing failed"; rc=1; }
|
||||
$PY "$HERE/web_dump.py" "$DEV" "$PWD/web-$N.jsonl" || { echo "web_server dump failed"; rc=1; }
|
||||
if [ -n "$CAP" ]; then
|
||||
LC_ALL=C grep -a '\]: Icon: \|\]: Device Class: ' "$CAP" | LC_ALL=C sed 's/\x1b\[[0-9;]*m//g; s/^\[[^]]*\]//; s/:[0-9]*\]:/]:/' | sort > "$PWD/dump-$N.txt"
|
||||
echo "dump_config icon lines $(grep -c 'Icon:' "$PWD/dump-$N.txt"), device class lines $(grep -c 'Device Class:' "$PWD/dump-$N.txt")"
|
||||
fi
|
||||
exit $rc
|
||||
@@ -1,99 +0,0 @@
|
||||
"""Dump the web_server view of every entity: the /events listing (detail all) and each REST endpoint with ?detail=all.
|
||||
|
||||
usage: web_dump.py HOST OUT
|
||||
"""
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
HOST, OUT = sys.argv[1], sys.argv[2]
|
||||
|
||||
|
||||
def sse_listing(seconds: float) -> list[dict]:
|
||||
s = socket.create_connection((HOST, 80), timeout=5)
|
||||
s.sendall(
|
||||
b"GET /events HTTP/1.1\r\nHost: %s\r\nAccept: text/event-stream\r\n\r\n"
|
||||
% HOST.encode()
|
||||
)
|
||||
buf = b""
|
||||
deadline = time.monotonic() + seconds
|
||||
s.settimeout(1.0)
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
data = s.recv(65536)
|
||||
except TimeoutError:
|
||||
continue
|
||||
if not data:
|
||||
break
|
||||
buf += data
|
||||
s.close()
|
||||
head, _, body = buf.partition(b"\r\n\r\n")
|
||||
if b"chunked" in head.lower():
|
||||
out = b""
|
||||
while True:
|
||||
i = body.find(b"\r\n")
|
||||
if i < 0:
|
||||
break
|
||||
size = int(body[:i].split(b";")[0], 16)
|
||||
out += body[i + 2 : i + 2 + size]
|
||||
body = body[i + 2 + size + 2 :]
|
||||
if size == 0:
|
||||
break
|
||||
body = out
|
||||
rows = []
|
||||
for block in body.decode(errors="replace").split("\n\n"):
|
||||
ev, data = None, None
|
||||
for line in block.split("\n"):
|
||||
line = line.rstrip("\r")
|
||||
if line.startswith("event:"):
|
||||
ev = line[6:].strip()
|
||||
elif line.startswith("data:"):
|
||||
data = line[5:].strip()
|
||||
if ev in ("state", "state_detail_all") and data:
|
||||
try:
|
||||
obj = json.loads(data)
|
||||
except ValueError:
|
||||
rows.append({"event": ev, "invalid": data})
|
||||
continue
|
||||
# bare state updates that land inside the window carry no domain; only the listing rows are kept
|
||||
if "domain" in obj:
|
||||
rows.append({"event": ev, **obj})
|
||||
return rows
|
||||
|
||||
|
||||
def get_json(url: str) -> dict:
|
||||
"""One retry: the ESP8266 async server occasionally leaves a request unanswered."""
|
||||
for attempt in (1, 2):
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=5) as resp:
|
||||
return json.loads(resp.read())
|
||||
except TimeoutError:
|
||||
if attempt == 2:
|
||||
raise
|
||||
print(f"retrying {url}", flush=True)
|
||||
return {}
|
||||
|
||||
|
||||
rows = sse_listing(6)
|
||||
ids = sorted({r["id"] for r in rows if "id" in r})
|
||||
rest = []
|
||||
for ident in ids:
|
||||
domain, _, obj = ident.partition("/")
|
||||
url = f"http://{HOST}/{domain}/{urllib.parse.quote(obj)}?detail=all"
|
||||
try:
|
||||
rest.append({"url": url.replace(HOST, "HOST"), **get_json(url)})
|
||||
except Exception as e: # noqa: BLE001
|
||||
rest.append({"url": url.replace(HOST, "HOST"), "error": str(e)})
|
||||
time.sleep(0.3)
|
||||
with pathlib.Path(OUT).open("w", encoding="utf-8") as f:
|
||||
f.writelines(
|
||||
json.dumps(r, sort_keys=True) + "\n"
|
||||
for r in sorted(rows, key=lambda r: (r.get("id", ""), r["event"]))
|
||||
)
|
||||
f.writelines(json.dumps(r, sort_keys=True) + "\n" for r in rest)
|
||||
print(f"{len(rows)} sse rows, {len(ids)} ids, {len(rest)} rest rows")
|
||||
@@ -1,51 +0,0 @@
|
||||
"""ltchiptool for boards whose RTS drives CEN: reset and link on one open port.
|
||||
|
||||
Stock ltchiptool closes and reopens the port after its DTR/RTS reset, and
|
||||
pyserial raises both lines on open, holding CEN low through the BootROM's
|
||||
listen window. Open with both lines released and pulse the reset right
|
||||
before the LinkChecks instead.
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
import bk7231tools.serial.main as bk_main
|
||||
from ltchiptool.__main__ import cli
|
||||
from ltchiptool.soc.bk72xx.flash import BK72XXFlash
|
||||
from serial import Serial
|
||||
|
||||
|
||||
class ReleasedSerial(Serial):
|
||||
def __init__(self, port=None, **kwargs):
|
||||
super().__init__(None, **kwargs)
|
||||
self.dtr = False
|
||||
self.rts = False
|
||||
self.port = port
|
||||
self.open()
|
||||
|
||||
|
||||
bk_main.Serial = ReleasedSerial
|
||||
|
||||
_connect = BK72XXFlash.flash_connect
|
||||
|
||||
|
||||
def flash_hw_reset(self) -> None:
|
||||
self._reset_pending = True
|
||||
|
||||
|
||||
def flash_connect(self) -> None:
|
||||
pending = getattr(self, "_reset_pending", False)
|
||||
if self.bk and self.conn.linked and not pending:
|
||||
return
|
||||
self.flash_build_protocol()
|
||||
if pending:
|
||||
self._reset_pending = False
|
||||
self.bk.hw_reset()
|
||||
self.conn.linked = False # the chip rebooted, so link again below
|
||||
_connect(self)
|
||||
|
||||
|
||||
BK72XXFlash.flash_hw_reset = flash_hw_reset
|
||||
BK72XXFlash.flash_connect = flash_connect
|
||||
|
||||
sys.argv = ["ltchiptool", *sys.argv[1:]]
|
||||
cli()
|
||||
@@ -1,87 +0,0 @@
|
||||
"""ltchiptool for the BW15 kit whose CH340 drives CEN (RTS) and PA00 (DTR).
|
||||
|
||||
A plain open asserts both lines and holds the chip in reset. Here every open keeps DTR high and RTS
|
||||
released; the first open pulses RTS so the ROM comes up; after the command DTR low plus an RTS pulse
|
||||
boots the app. The exit status is ltchiptool's; 2 means the flash succeeded but the app was not
|
||||
booted (boot pulse failed, or no -d PORT to send it to), so the board sits in the ROM until reset.
|
||||
|
||||
Usage: python flash_rtl87xx_kit.py flash write -d <port> firmware.uf2
|
||||
"""
|
||||
|
||||
import sys
|
||||
import time
|
||||
|
||||
import serial
|
||||
|
||||
_first = [True]
|
||||
_orig_open = serial.Serial.open
|
||||
|
||||
|
||||
def _open(self):
|
||||
self.dtr = True # PA00 high: ROM download mode on the next reset
|
||||
self.rts = False # CEN released
|
||||
_orig_open(self)
|
||||
if _first[0]:
|
||||
_first[0] = False
|
||||
self.rts = True
|
||||
time.sleep(0.1)
|
||||
self.rts = False
|
||||
time.sleep(0.3) # reset into the ROM
|
||||
self.reset_input_buffer()
|
||||
|
||||
|
||||
serial.Serial.open = _open
|
||||
|
||||
from ltchiptool.__main__ import cli_entrypoint # noqa: E402
|
||||
|
||||
|
||||
def port_argument(argv: list[str]) -> str | None:
|
||||
for i, a in enumerate(argv):
|
||||
if a in ("-d", "--device") and i + 1 < len(argv):
|
||||
return argv[i + 1]
|
||||
if a.startswith(("-d=", "--device=")):
|
||||
return a.split("=", 1)[1]
|
||||
if a.startswith("-d") and len(a) > 2:
|
||||
return a[2:]
|
||||
return None
|
||||
|
||||
|
||||
def boot_app(port: str) -> None:
|
||||
s = serial.Serial(port=None)
|
||||
s.port = port
|
||||
s.dtr = False
|
||||
s.rts = False
|
||||
_orig_open(s)
|
||||
s.rts = True
|
||||
time.sleep(0.1)
|
||||
s.rts = False
|
||||
s.close()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
rc = 1
|
||||
try:
|
||||
result = cli_entrypoint.main(args=sys.argv[1:], standalone_mode=False)
|
||||
rc = int(result) if isinstance(result, int) else 0
|
||||
finally:
|
||||
port = port_argument(sys.argv)
|
||||
if not port:
|
||||
print(
|
||||
"[flash_rtl87xx_kit] no -d PORT given, the application was not booted",
|
||||
file=sys.stderr,
|
||||
)
|
||||
if rc == 0:
|
||||
rc = 2
|
||||
else:
|
||||
try:
|
||||
boot_app(port)
|
||||
print("[flash_rtl87xx_kit] application booted")
|
||||
except (serial.SerialException, OSError) as err:
|
||||
print(f"[flash_rtl87xx_kit] boot pulse failed: {err}", file=sys.stderr)
|
||||
if rc == 0:
|
||||
rc = 2 # flashed, but the board is still in the ROM: press reset
|
||||
return rc
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,78 +0,0 @@
|
||||
"""Read or drive a bulb directly over its own ESPHome API (an HA-side change, independent of the mirror).
|
||||
|
||||
usage: bulb.py HOST KEY state | on [brightness 0-1] [ct_mireds|rgb r,g,b] | off | restart
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from aioesphomeapi import APIClient, ButtonInfo, LightColorCapability, LightInfo
|
||||
|
||||
HOST, KEY, CMD = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
ARGS = sys.argv[4:]
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
c = APIClient(HOST, 6053, None, noise_psk=None if KEY == "-" else KEY)
|
||||
await c.connect(login=True)
|
||||
ents, _ = await c.list_entities_services()
|
||||
light = next((e for e in ents if isinstance(e, LightInfo)), None)
|
||||
if light is None:
|
||||
sys.exit("no light entity on this device; is HOST a bulb?")
|
||||
if CMD == "state":
|
||||
fut = asyncio.get_running_loop().create_future()
|
||||
|
||||
def on_state(st):
|
||||
if getattr(st, "key", None) == light.key and not fut.done():
|
||||
fut.set_result(st)
|
||||
|
||||
c.subscribe_states(on_state)
|
||||
st = await asyncio.wait_for(fut, 5)
|
||||
print(
|
||||
f"{light.name}: on={st.state} mode={st.color_mode} bri={st.brightness:.2f} "
|
||||
f"ct={st.color_temperature:.1f} rgb={st.red:.2f}/{st.green:.2f}/{st.blue:.2f} "
|
||||
f"white={st.white:.2f} cold={st.cold_white:.2f} warm={st.warm_white:.2f}"
|
||||
)
|
||||
elif CMD == "on":
|
||||
kw = {"state": True}
|
||||
if ARGS:
|
||||
kw["brightness"] = float(ARGS[0])
|
||||
if len(ARGS) > 1:
|
||||
if "," in ARGS[1]:
|
||||
r, g, b = (float(x) for x in ARGS[1].split(","))
|
||||
kw["rgb"] = (r, g, b)
|
||||
kw["color_mode"] = (
|
||||
LightColorCapability.RGB
|
||||
| LightColorCapability.ON_OFF
|
||||
| LightColorCapability.BRIGHTNESS
|
||||
)
|
||||
else:
|
||||
kw["color_temperature"] = float(ARGS[1])
|
||||
kw["color_mode"] = (
|
||||
LightColorCapability.COLOR_TEMPERATURE
|
||||
| LightColorCapability.ON_OFF
|
||||
| LightColorCapability.BRIGHTNESS
|
||||
)
|
||||
c.light_command(light.key, **kw)
|
||||
print("bulb on", kw)
|
||||
elif CMD == "off":
|
||||
c.light_command(light.key, state=False)
|
||||
print("bulb off")
|
||||
elif CMD == "restart":
|
||||
btn = next(
|
||||
(
|
||||
e
|
||||
for e in ents
|
||||
if isinstance(e, ButtonInfo) and "restart" in e.name.lower()
|
||||
),
|
||||
None,
|
||||
)
|
||||
if btn is None:
|
||||
sys.exit("no restart button on this device")
|
||||
c.button_command(btn.key)
|
||||
print("bulb restart pressed")
|
||||
await asyncio.sleep(0.5)
|
||||
await c.disconnect()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,71 +0,0 @@
|
||||
"""Held-report cases for esphome#21144 with persistent API connections, so the steps land inside the 3 s fade.
|
||||
usage: heldcase.py DEV_IP KEY BULB_IP same|many [BULB_KEY] (KEY or BULB_KEY of - means plaintext)
|
||||
t0 press "A 50 fade 3s" on the mirror device (3 s fade to 50%)
|
||||
t0+0.7 set the bulb directly to 90% (Home Assistant reports it to the mirror during the fade: held)
|
||||
t0+1.4 same: press "A 50 fade 3s" again (same target as the running fade)
|
||||
many: press "A many calls" (16 calls in one loop pass, the last one 100% with a 1 s fade)
|
||||
t0+6.5 read the bulb, press Log state so the mirror prints its state
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
import time
|
||||
|
||||
from aioesphomeapi import APIClient, ButtonInfo, LightInfo, LightState
|
||||
|
||||
DEV, KEY, BULB, CASE = sys.argv[1:5]
|
||||
BULB_KEY = sys.argv[5] if len(sys.argv) > 5 else "-"
|
||||
if CASE not in ("same", "many"):
|
||||
sys.exit(f"case must be same or many, got {CASE!r}")
|
||||
T0 = time.time()
|
||||
|
||||
|
||||
def stamp() -> str:
|
||||
return f"{time.time() - T0:6.3f}"
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
dev = APIClient(DEV, 6053, None, noise_psk=None if KEY == "-" else KEY)
|
||||
bulb = APIClient(BULB, 6053, None, noise_psk=None if BULB_KEY == "-" else BULB_KEY)
|
||||
await dev.connect(login=True)
|
||||
await bulb.connect(login=True)
|
||||
dents, _ = await dev.list_entities_services()
|
||||
bents, _ = await bulb.list_entities_services()
|
||||
buttons = {e.name: e for e in dents if isinstance(e, ButtonInfo)}
|
||||
blight = next(e for e in bents if isinstance(e, LightInfo))
|
||||
states = {}
|
||||
|
||||
def on_bulb(s) -> None:
|
||||
if isinstance(s, LightState) and s.key == blight.key:
|
||||
states["bulb"] = s
|
||||
print(f"{stamp()} bulb state: on={s.state} bri={s.brightness:.2f}")
|
||||
|
||||
bulb.subscribe_states(on_bulb)
|
||||
await asyncio.sleep(1.0)
|
||||
print(f"{stamp()} >>> bulb to 100% (precondition)")
|
||||
bulb.light_command(blight.key, state=True, brightness=1.0)
|
||||
await asyncio.sleep(4.0)
|
||||
t = time.time()
|
||||
print(f"{stamp()} >>> t0 press A 50 fade 3s")
|
||||
dev.button_command(buttons["A 50 fade 3s"].key)
|
||||
await asyncio.sleep(0.7 - (time.time() - t))
|
||||
print(f"{stamp()} >>> bulb direct to 90%")
|
||||
bulb.light_command(blight.key, state=True, brightness=0.9)
|
||||
await asyncio.sleep(1.4 - (time.time() - t))
|
||||
name = "A 50 fade 3s" if CASE == "same" else "A many calls"
|
||||
print(f"{stamp()} >>> press {name}")
|
||||
dev.button_command(buttons[name].key)
|
||||
await asyncio.sleep(6.5 - (time.time() - t))
|
||||
print(f"{stamp()} >>> press Log state (the mirror's state is in the device log)")
|
||||
dev.button_command(buttons["Log state"].key)
|
||||
await asyncio.sleep(1.0)
|
||||
b = states.get("bulb")
|
||||
print(
|
||||
f"{stamp()} RESULT bulb "
|
||||
+ (f"bri={b.brightness:.2f}" if b is not None else "no state")
|
||||
)
|
||||
await dev.disconnect()
|
||||
await bulb.disconnect()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,31 +0,0 @@
|
||||
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()
|
||||
|
||||
def on_log(m):
|
||||
t = re.sub(r"\x1b\[[0-9;]*m", "", m.message.decode(errors="replace"))
|
||||
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()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,109 +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"))
|
||||
EXTRAS = not ONLY
|
||||
|
||||
|
||||
async def main():
|
||||
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)
|
||||
|
||||
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}
|
||||
)
|
||||
end = time.monotonic() + 40
|
||||
while time.monotonic() < end and not any(
|
||||
"RESULT" in ln for ln in lines[n0:]
|
||||
):
|
||||
await asyncio.sleep(0.2)
|
||||
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})
|
||||
end = time.monotonic() + 30
|
||||
while (
|
||||
time.monotonic() < end
|
||||
and sum(("BURSTRESP" in ln or "BURSTERR" in ln) for ln in lines[n0:]) < 6
|
||||
):
|
||||
await asyncio.sleep(0.2)
|
||||
await asyncio.sleep(2)
|
||||
print(f"{LABEL} == cancel round {rnd}", flush=True)
|
||||
await c.execute_service(svc["cancel"], {"url": BASE + "/slow?d=2"})
|
||||
await asyncio.sleep(9)
|
||||
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}
|
||||
)
|
||||
end = time.monotonic() + 30
|
||||
while time.monotonic() < end and (
|
||||
sum("BURSTRESP" in ln or "BURSTERR" in ln for ln in lines[n0:]) < 3
|
||||
or not any("RESULT" in ln for ln in lines[n0:])
|
||||
):
|
||||
await asyncio.sleep(0.2)
|
||||
await asyncio.sleep(2)
|
||||
await c.disconnect()
|
||||
|
||||
|
||||
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,52 +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()
|
||||
|
||||
def on_log(m):
|
||||
t = re.sub(r"\x1b\[[0-9;]*m", "", m.message.decode(errors="replace"))
|
||||
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})
|
||||
await asyncio.sleep(45)
|
||||
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()
|
||||
return
|
||||
except Exception: # noqa: BLE001
|
||||
await asyncio.sleep(2)
|
||||
print("after: not reachable")
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,51 +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 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})
|
||||
while time.monotonic() - t0 < 30:
|
||||
try:
|
||||
await asyncio.wait_for(c.device_info(), 1.0)
|
||||
await asyncio.sleep(0.2)
|
||||
except Exception: # noqa: BLE001
|
||||
print(f"{time.monotonic() - t0:7.2f} API connection gone", flush=True)
|
||||
break
|
||||
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
|
||||
except Exception: # noqa: BLE001
|
||||
await asyncio.sleep(1)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,59 +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)
|
||||
for i in range(N):
|
||||
print(f"{LABEL} {time.monotonic() - t0:7.2f} CHECK {i + 1}", flush=True)
|
||||
c.update_command(upd.key, aioesphomeapi.UpdateCommand.CHECK)
|
||||
await asyncio.sleep(25)
|
||||
await c.disconnect()
|
||||
|
||||
|
||||
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,123 +0,0 @@
|
||||
"""Drive an LD24xx harness over the API: press buttons, set selects and numbers, print state updates, save the log.
|
||||
|
||||
usage: lddrive.py HOST KEY LOGFILE OP [OP ...] (KEY of - means a plaintext API)
|
||||
OP: list | press:NAME | sel:NAME=OPTION | set:NAME=VALUE | wait:SECONDS
|
||||
Steps are 2 s apart: the API log stream drops lines while the hub blocks in send_command_.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
from aioesphomeapi import (
|
||||
APIClient,
|
||||
BinarySensorState,
|
||||
ButtonInfo,
|
||||
LogLevel,
|
||||
NumberInfo,
|
||||
NumberState,
|
||||
SelectInfo,
|
||||
SelectState,
|
||||
SensorInfo,
|
||||
SensorState,
|
||||
TextSensorInfo,
|
||||
TextSensorState,
|
||||
)
|
||||
|
||||
HOST, KEY, LOGFILE = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
OPS = sys.argv[4:]
|
||||
T0 = time.time()
|
||||
STEP_GAP_S = 2.0
|
||||
|
||||
|
||||
def stamp() -> str:
|
||||
return f"{time.time() - T0:7.3f}"
|
||||
|
||||
|
||||
async def run(c: APIClient, log) -> None:
|
||||
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)}
|
||||
numbers = {e.name: e for e in ents if isinstance(e, NumberInfo)}
|
||||
|
||||
def on_state(s) -> None:
|
||||
e = by_key.get(s.key)
|
||||
if e is None:
|
||||
return
|
||||
missing = " (missing)" if getattr(s, "missing_state", False) else ""
|
||||
if isinstance(s, TextSensorState):
|
||||
print(f"{stamp()} TXT {e.name} = {s.state!r}{missing}", flush=True)
|
||||
elif isinstance(s, BinarySensorState):
|
||||
print(f"{stamp()} BIN {e.name} = {s.state}{missing}", flush=True)
|
||||
elif isinstance(s, NumberState):
|
||||
print(f"{stamp()} NUM {e.name} = {s.state:.0f}{missing}", flush=True)
|
||||
elif isinstance(s, SelectState):
|
||||
print(f"{stamp()} SEL {e.name} = {s.state!r}{missing}", flush=True)
|
||||
elif (
|
||||
isinstance(s, SensorState)
|
||||
and isinstance(e, SensorInfo)
|
||||
and "Count" in e.name
|
||||
):
|
||||
print(f"{stamp()} CNT {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("=")
|
||||
if name not in numbers:
|
||||
sys.exit(f"no number named {name!r}; have {sorted(numbers)}")
|
||||
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(STEP_GAP_S)
|
||||
await asyncio.sleep(1)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
c = APIClient(HOST, 6053, None, noise_psk=None if KEY == "-" else KEY)
|
||||
await c.connect(login=True)
|
||||
with Path(LOGFILE).open("w", encoding="utf-8") as log:
|
||||
await run(c, log)
|
||||
await c.disconnect()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,33 +0,0 @@
|
||||
"""Summarize an lddrive.py log: for each step, the LD2450 TX frames, commands and publishes.
|
||||
|
||||
usage: txsum.py LOGFILE (diff the output of two builds)
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
|
||||
ANSI = re.compile(r"\x1b\[[0-9;]*m")
|
||||
out: list[str] = []
|
||||
with Path(sys.argv[1]).open(encoding="utf-8", errors="replace") as log:
|
||||
for raw in log:
|
||||
line = ANSI.sub("", raw.rstrip("\n"))
|
||||
m = re.match(r"\s*[\d.]+ (.*)", line)
|
||||
if not m:
|
||||
continue
|
||||
text = m.group(1)
|
||||
if text.startswith(">>>"):
|
||||
out.append(f"\n# {text[4:]}")
|
||||
elif "[uart_debug" in text:
|
||||
out.append(f" TX {text.split('>>> ')[1]}")
|
||||
elif "[ld2450" in text and (
|
||||
"Sending COMMAND" in text
|
||||
or "zone type" in text.lower()
|
||||
or "Query zone" in text
|
||||
):
|
||||
out.append(f" LOG {text.split(']: ', 1)[1]}")
|
||||
elif "[select:" in text and ">>" in text:
|
||||
out.append(f" SEL {text.split(']: ', 1)[1]}")
|
||||
elif "[text_sensor:098]" in text:
|
||||
out.append(f" TXT {text.split(']: ', 1)[1]}")
|
||||
print("\n".join(out))
|
||||
@@ -1,85 +0,0 @@
|
||||
"""Drive LD2450 numbers and selects over the API while printing every LD2450 state update.
|
||||
usage: zonedrive.py HOST KEY(- for plaintext) OP [OP ...]
|
||||
OP: set:NAME=VALUE | sel:NAME=OPTION | wait:SECONDS | list
|
||||
Every state update of an entity whose name contains "LD2450" is printed with a timestamp.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
import time
|
||||
|
||||
from aioesphomeapi import (
|
||||
APIClient,
|
||||
NumberInfo,
|
||||
NumberState,
|
||||
SelectInfo,
|
||||
SelectState,
|
||||
SensorInfo,
|
||||
SensorState,
|
||||
)
|
||||
|
||||
HOST, KEY = 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:
|
||||
c = APIClient(HOST, 6053, None, noise_psk=None if KEY == "-" else KEY)
|
||||
await c.connect(login=True)
|
||||
ents, _ = await c.list_entities_services()
|
||||
by_key = {e.key: e for e in ents}
|
||||
numbers = {e.name: e for e in ents if isinstance(e, NumberInfo)}
|
||||
selects = {e.name: e for e in ents if isinstance(e, SelectInfo)}
|
||||
sensors = {e.name: e for e in ents if isinstance(e, SensorInfo)}
|
||||
|
||||
def on_state(s) -> None:
|
||||
e = by_key.get(s.key)
|
||||
if e is None or "LD2450" not in e.name:
|
||||
return
|
||||
if isinstance(s, NumberState):
|
||||
print(
|
||||
f"{stamp()} NUM {e.name} = {s.state:.0f}{' (missing)' if s.missing_state else ''}"
|
||||
)
|
||||
elif isinstance(s, SelectState):
|
||||
print(f"{stamp()} SEL {e.name} = {s.state}")
|
||||
elif isinstance(s, SensorState) and "Count" in e.name:
|
||||
print(f"{stamp()} CNT {e.name} = {s.state:.0f}")
|
||||
|
||||
c.subscribe_states(on_state)
|
||||
await asyncio.sleep(1.5)
|
||||
for op in OPS:
|
||||
if op == "list":
|
||||
for n in sorted(numbers):
|
||||
print("number:", n)
|
||||
for n in sorted(selects):
|
||||
print("select:", n, selects[n].options)
|
||||
for n in sorted(sensors):
|
||||
if "Count" in n:
|
||||
print("sensor:", n)
|
||||
continue
|
||||
kind, _, rest = op.partition(":")
|
||||
if kind == "wait":
|
||||
await asyncio.sleep(float(rest))
|
||||
continue
|
||||
name, _, value = rest.partition("=")
|
||||
if kind == "set":
|
||||
if name not in numbers:
|
||||
sys.exit(f"no number named {name!r}; have {sorted(numbers)}")
|
||||
print(f"{stamp()} >>> set {name} = {value}")
|
||||
c.number_command(numbers[name].key, float(value))
|
||||
elif kind == "sel":
|
||||
if name not in selects:
|
||||
sys.exit(f"no select named {name!r}; have {sorted(selects)}")
|
||||
print(f"{stamp()} >>> select {name} = {value}")
|
||||
c.select_command(selects[name].key, value)
|
||||
else:
|
||||
sys.exit(f"unknown op {op!r}")
|
||||
await asyncio.sleep(0.3)
|
||||
await c.disconnect()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,116 +0,0 @@
|
||||
// BK72xx crash probe: forces one crash per step and shows what the SDK and the bootloader leave behind.
|
||||
// Steps: 0 undefined instruction, 1 call into unmapped memory, 2 unmapped and unaligned accesses (no fault),
|
||||
// 3 lt_reboot(). The step lives in a flash preference saved and synced before the crash.
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include <FreeRTOS.h>
|
||||
#include <task.h>
|
||||
#include <cstdint>
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/preferences.h"
|
||||
|
||||
extern "C" unsigned bk_misc_get_start_type(void);
|
||||
extern "C" char _bss_end[];
|
||||
|
||||
static constexpr uint32_t PROBE_CANARY_LOW = 0x004000F8; // free word in the SDK-reserved low SRAM
|
||||
static constexpr uint32_t PROBE_CANARY_ITCM = 0x003F3FF0; // top of ITCM
|
||||
static char bkprobe_report[112];
|
||||
static constexpr uint32_t PROBE_MARKS[] = {0x40A1B0, 0x40B000, 0x40C000, 0x40E000, 0x410000, 0x414000, 0x418000,
|
||||
0x41C000, 0x420000, 0x428000, 0x430000, 0x438000, 0x43C000, 0x43E000,
|
||||
0x43F000, 0x43F800, 0x43FC00, 0x43FE00, 0x43FFF0};
|
||||
static constexpr size_t PROBE_MARK_COUNT = sizeof(PROBE_MARKS) / sizeof(PROBE_MARKS[0]);
|
||||
|
||||
static inline uint32_t rd(uint32_t a) { return *(volatile uint32_t *) a; }
|
||||
|
||||
inline esphome::ESPPreferenceObject bkprobe_pref(uint32_t run) {
|
||||
return esphome::global_preferences->make_preference<int>(0xBC000000u + run);
|
||||
}
|
||||
|
||||
inline int bkprobe_boot(uint32_t run) {
|
||||
using namespace esphome;
|
||||
int step = 0;
|
||||
bkprobe_pref(run).load(&step);
|
||||
unsigned st = bk_misc_get_start_type();
|
||||
snprintf(bkprobe_report, sizeof(bkprobe_report), "step=%d reason=%s(%d) start_type=%u low=%08lx itcm=%08lx top=%08lx",
|
||||
step, lt_get_reboot_reason_name(lt_get_reboot_reason()), (int) lt_get_reboot_reason(), st,
|
||||
(unsigned long) rd(PROBE_CANARY_LOW), (unsigned long) rd(PROBE_CANARY_ITCM),
|
||||
(unsigned long) rd(0x0043FFF0u));
|
||||
ESP_LOGI("probe", "%s", bkprobe_report);
|
||||
for (uint32_t a = 0x400000; a < 0x400100; a += 32) {
|
||||
ESP_LOGI("probe", "%06lx: %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx", (unsigned long) a,
|
||||
(unsigned long) rd(a), (unsigned long) rd(a + 4), (unsigned long) rd(a + 8), (unsigned long) rd(a + 12),
|
||||
(unsigned long) rd(a + 16), (unsigned long) rd(a + 20), (unsigned long) rd(a + 24),
|
||||
(unsigned long) rd(a + 28));
|
||||
}
|
||||
for (size_t i = 0; i < PROBE_MARK_COUNT; i += 7) {
|
||||
char line[120];
|
||||
int n = 0;
|
||||
for (size_t j = i; j < i + 7 && j < PROBE_MARK_COUNT; j++)
|
||||
n += snprintf(line + n, sizeof(line) - n, " %06lx=%08lx", (unsigned long) PROBE_MARKS[j],
|
||||
(unsigned long) rd(PROBE_MARKS[j]));
|
||||
ESP_LOGI("probe", "marks%s", line);
|
||||
}
|
||||
uint32_t rec = ((uint32_t) _bss_end + 7) & ~7u;
|
||||
for (uint32_t a = rec; a < rec + 64; a += 32) {
|
||||
ESP_LOGI("probe", "rec %06lx: %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx", (unsigned long) a,
|
||||
(unsigned long) rd(a), (unsigned long) rd(a + 4), (unsigned long) rd(a + 8), (unsigned long) rd(a + 12),
|
||||
(unsigned long) rd(a + 16), (unsigned long) rd(a + 20), (unsigned long) rd(a + 24),
|
||||
(unsigned long) rd(a + 28));
|
||||
}
|
||||
*(volatile uint32_t *) PROBE_CANARY_LOW = 0xC0DE0000u | (uint32_t) step;
|
||||
*(volatile uint32_t *) PROBE_CANARY_ITCM = 0x17C40000u | (uint32_t) step;
|
||||
return step;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) void bkprobe_data_abort() {
|
||||
using namespace esphome;
|
||||
volatile uint32_t v = rd(0xFFFFFFF0);
|
||||
ESP_LOGI("probe", "read 0xFFFFFFF0 -> %08lx (no fault)", (unsigned long) v);
|
||||
uint32_t r;
|
||||
__asm__ volatile("ldr %0, [%1]" : "=r"(r) : "r"(0x00400101) : "memory");
|
||||
ESP_LOGI("probe", "unaligned ldr 0x400101 -> %08lx (no fault)", (unsigned long) r);
|
||||
*(volatile uint32_t *) 0xFFFFFFF0 = 1;
|
||||
ESP_LOGI("probe", "store 0xFFFFFFF0 (no fault)");
|
||||
}
|
||||
|
||||
// act is the step number before it was bumped
|
||||
inline void bkprobe_act(uint32_t run, int act) {
|
||||
using namespace esphome;
|
||||
int next = act + 1;
|
||||
bkprobe_pref(run).save(&next);
|
||||
global_preferences->sync();
|
||||
ESP_LOGI("probe", "acting on step %d (saved %d)", act, next);
|
||||
// mark candidate storage areas so the next boot shows what survives
|
||||
uint32_t rec = ((uint32_t) _bss_end + 7) & ~7u;
|
||||
for (uint32_t i = 0; i < 8; i++)
|
||||
*(volatile uint32_t *) (rec + 32 + i * 4) = 0xA5A50000u | i; // second half of the record area
|
||||
for (size_t i = 0; i < PROBE_MARK_COUNT; i++)
|
||||
*(volatile uint32_t *) PROBE_MARKS[i] = 0x70700000u | (uint32_t) i;
|
||||
ESP_LOGI("probe", "ramtop before: %08lx", (unsigned long) rd(0x0043FFF0u));
|
||||
vTaskDelay(pdMS_TO_TICKS(50));
|
||||
switch (act) {
|
||||
case 0:
|
||||
__builtin_trap(); // undefined instruction
|
||||
break;
|
||||
case 1: {
|
||||
void (*fn)() = (void (*)()) 0xFFFFFFF1; // prefetch abort (unmapped, Thumb)
|
||||
fn();
|
||||
ESP_LOGI("probe", "call 0xFFFFFFF1 returned (no fault)");
|
||||
break;
|
||||
}
|
||||
case 2:
|
||||
bkprobe_data_abort();
|
||||
break;
|
||||
case 3:
|
||||
lt_reboot();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
inline void bkprobe_alive(int step) {
|
||||
using namespace esphome;
|
||||
ESP_LOGI("probe", "alive step=%d uptime=%lus boot: %s", step, (unsigned long) (millis() / 1000), bkprobe_report);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
"""Feed a serial capture through the CLI's stacktrace decoder for a build.
|
||||
|
||||
usage: decode_capture.py CONFIG_YAML CAPTURE
|
||||
|
||||
Run from the directory that holds the config (its .esphome build is used), with the esphome checkout that
|
||||
built it on PYTHONPATH. Lines of the crash report are echoed, decoded frames follow them.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
from esphome.config import read_config
|
||||
from esphome.core import CORE
|
||||
from esphome.stacktrace import LogLineProcessor
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||
yaml, capture = Path(sys.argv[1]), Path(sys.argv[2])
|
||||
CORE.config_path = yaml
|
||||
config = read_config({})
|
||||
proc = LogLineProcessor(config, CORE.target_platform)
|
||||
for line in capture.read_text(encoding="utf-8", errors="replace").splitlines():
|
||||
if "libretiny.crash" in line:
|
||||
print(line[:120])
|
||||
proc.process_line(line)
|
||||
@@ -1,155 +0,0 @@
|
||||
#pragma once
|
||||
// BK7238 bench harness for esphome#21007: one rtc and one flash preference, a step counter in flash,
|
||||
// and an exit action per step so the board drives its own soft reboot, crash and watchdog reboot.
|
||||
#include <libretiny.h>
|
||||
#include <cstring>
|
||||
#include <FreeRTOS.h>
|
||||
#include <task.h>
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/preferences.h"
|
||||
|
||||
using namespace esphome;
|
||||
|
||||
// Boot report kept for the alive line, so a boot the host could not capture is still visible
|
||||
static char ltprefs_report[128];
|
||||
// Last boots' reports, kept in a flash preference so boots the host never saw stay readable
|
||||
struct LtprefsHistory {
|
||||
char line[8][128];
|
||||
};
|
||||
static LtprefsHistory ltprefs_hist;
|
||||
|
||||
inline ESPPreferenceObject ltprefs_step_pref(uint32_t run) {
|
||||
return global_preferences->make_preference<int>(0x3B210070u ^ run, true);
|
||||
}
|
||||
|
||||
// Loads the step and both preferences, logs them, saves this step's value.
|
||||
// Returns the exit action: 0 idle, 1 lt_reboot, 2 crash, 3 watchdog.
|
||||
inline int ltprefs_boot(int &step, uint32_t run) {
|
||||
auto reason = lt_get_reboot_reason();
|
||||
step = 0;
|
||||
ltprefs_step_pref(run).load(&step);
|
||||
auto rtcp = global_preferences->make_preference<uint32_t>(0x1B210070u ^ run, false);
|
||||
auto flp = global_preferences->make_preference<uint32_t>(0x2B210070u ^ run, true);
|
||||
uint32_t rv = 0, fv = 0;
|
||||
// a second pair sharing one key as rtc and as flash, and a third rtc entry, so a hard reset drops three
|
||||
auto rtcp2 = global_preferences->make_preference<uint32_t>(0x5B210070u ^ run, false);
|
||||
auto flp2 = global_preferences->make_preference<uint32_t>(0x5B210070u ^ run, true);
|
||||
auto rtcp3 = global_preferences->make_preference<uint32_t>(0x6B210070u ^ run, false);
|
||||
uint32_t rv2 = 0, fv2 = 0, rv3 = 0;
|
||||
bool rok = rtcp.load(&rv);
|
||||
bool fok = flp.load(&fv);
|
||||
bool rok2 = rtcp2.load(&rv2);
|
||||
bool fok2 = flp2.load(&fv2);
|
||||
bool rok3 = rtcp3.load(&rv3);
|
||||
snprintf(ltprefs_report, sizeof(ltprefs_report),
|
||||
"step=%d reason=%s(%d) rtc=%s%u flash=%s%u sharedkey rtc=%s%u flash=%s%u rtc3=%s%u", step,
|
||||
lt_get_reboot_reason_name(reason), (int) reason, rok ? "" : "none ", rv, fok ? "" : "none ", fv,
|
||||
rok2 ? "" : "none ", rv2, fok2 ? "" : "none ", fv2, rok3 ? "" : "none ", rv3);
|
||||
ESP_LOGI("lttest", "%s", ltprefs_report);
|
||||
auto histp = global_preferences->make_preference<LtprefsHistory>(0x4B210070u ^ run, true);
|
||||
if (!histp.load(<prefs_hist))
|
||||
memset(<prefs_hist, 0, sizeof(ltprefs_hist));
|
||||
memmove(<prefs_hist.line[1], <prefs_hist.line[0], sizeof(ltprefs_hist.line) - sizeof(ltprefs_hist.line[0]));
|
||||
strncpy(ltprefs_hist.line[0], ltprefs_report, sizeof(ltprefs_hist.line[0]) - 1);
|
||||
ltprefs_hist.line[0][sizeof(ltprefs_hist.line[0]) - 1] = 0;
|
||||
if (!histp.save(<prefs_hist)) {
|
||||
ESP_LOGW("lttest", "history save failed");
|
||||
}
|
||||
int act = 0;
|
||||
bool save = true;
|
||||
switch (step) {
|
||||
case 0:
|
||||
act = 1;
|
||||
break; // soft reboot
|
||||
case 1:
|
||||
act = 2;
|
||||
break; // crash
|
||||
case 2:
|
||||
act = 3;
|
||||
break; // watchdog
|
||||
case 3:
|
||||
act = 0;
|
||||
break; // idle: chip-enable reset from the host
|
||||
case 4:
|
||||
act = 1;
|
||||
break; // soft reboot after the hard reset
|
||||
case 5:
|
||||
act = 0;
|
||||
break; // idle: chip-enable reset from the host
|
||||
case 6:
|
||||
act = 1;
|
||||
save = false;
|
||||
break; // no save, soft reboot: deleted, not skipped?
|
||||
case 7:
|
||||
act = 0;
|
||||
break; // idle
|
||||
case 8:
|
||||
act = 2;
|
||||
break; // crash
|
||||
case 9:
|
||||
act = 0;
|
||||
break; // idle
|
||||
case 10:
|
||||
act = 0;
|
||||
break; // idle: power cut by the user
|
||||
default:
|
||||
act = 0;
|
||||
save = false;
|
||||
break;
|
||||
}
|
||||
if (save) {
|
||||
uint32_t v = 100 + step, v2r = 200 + step, v2f = 300 + step, v3 = 400 + step;
|
||||
bool srtc = rtcp.save(&v);
|
||||
bool sfl = flp.save(&v);
|
||||
bool srtc2 = rtcp2.save(&v2r);
|
||||
bool sfl2 = flp2.save(&v2f);
|
||||
bool srtc3 = rtcp3.save(&v3);
|
||||
bool synced = global_preferences->sync();
|
||||
ESP_LOGI("lttest", "save %u/%u/%u/%u: rtc=%d flash=%d sharedkey rtc=%d flash=%d rtc3=%d sync=%d", v, v2r, v2f, v3,
|
||||
srtc, sfl, srtc2, sfl2, srtc3, synced);
|
||||
}
|
||||
ESP_LOGI("lttest", "exit action=%d", act);
|
||||
return act;
|
||||
}
|
||||
|
||||
inline void ltprefs_exit(int &step, uint32_t run, int act) {
|
||||
step++;
|
||||
bool saved = ltprefs_step_pref(run).save(&step);
|
||||
bool synced = global_preferences->sync();
|
||||
ESP_LOGI("lttest", "step %d save=%d sync=%d", step, saved, synced);
|
||||
if (!saved || !synced) {
|
||||
ESP_LOGE("lttest", "step not stored, staying idle instead of repeating the step");
|
||||
return;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(200));
|
||||
switch (act) {
|
||||
case 1:
|
||||
ESP_LOGW("lttest", "soft reboot now");
|
||||
vTaskDelay(pdMS_TO_TICKS(50));
|
||||
lt_reboot();
|
||||
break;
|
||||
case 2:
|
||||
ESP_LOGW("lttest", "crashing now");
|
||||
vTaskDelay(pdMS_TO_TICKS(50));
|
||||
__builtin_trap(); // undefined instruction: a plain bad store does not fault on the ARM968
|
||||
break;
|
||||
case 3:
|
||||
ESP_LOGW("lttest", "watchdog reboot now");
|
||||
vTaskDelay(pdMS_TO_TICKS(50));
|
||||
lt_reboot_wdt();
|
||||
break;
|
||||
default:
|
||||
ESP_LOGW("lttest", "idle, waiting for an external reset");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
inline void ltprefs_alive(int step, int act) {
|
||||
ESP_LOGI("lttest", "alive step=%d act=%d boot: %s", step, act, ltprefs_report);
|
||||
for (int i = 7; i >= 0; i--) {
|
||||
if (ltprefs_hist.line[i][0] != 0) {
|
||||
ESP_LOGI("lttest", " history[-%d]: %s", i, ltprefs_hist.line[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,44 +0,0 @@
|
||||
#!/bin/sh
|
||||
# cases.sh NAME KEY BROKER_HOST SUB_PORT CAPTURE [DEV_HOST] [restart] : subscribe to NAME/# on the broker, send a
|
||||
# switch command and an on_message topic, press the 3000 byte publish button over the API (KEY, - for plaintext),
|
||||
# optionally restart the local broker (its PID from mosquitto.pid in the working directory, written when it was started
|
||||
# with `mosquitto -c mosquitto-ws.conf & echo $! > mosquitto.pid`), and show the device log. Outputs (sub-NAME.txt, mosquitto.out) go to the working directory, which should be the scratch directory.
|
||||
N=$1; KEY=$2; B=$3; SP=$4; LOG=$5; DEV=${6:-$1.local}; RESTART=$7; HERE=$(cd "$(dirname "$0")" && pwd); PY=${PYTHON:-python3}; WORK=$PWD
|
||||
BTN=$HERE/../api_button.py
|
||||
[ -n "$KEY" ] && [ -r "$LOG" ] || { echo "usage: cases.sh NAME KEY BROKER_HOST SUB_PORT CAPTURE [DEV_HOST] [restart] (CAPTURE must be a readable file)"; exit 2; }
|
||||
show() { tail -n +$(($1+1)) "$LOG" | sed 's/\x1b\[[0-9;]*m//g' | grep -a 'mqtt\|\[probe:\|cmd payload\|Relay\|\[W\]\|\[E\]\|Guru\|abort\|Backtrace\|ESPHome version' | grep -a -v 'took a long time\|Publish.*Counter\|sensor/counter' | cut -c1-170; }
|
||||
pub() { mosquitto_pub -h "$B" -p "$SP" -t "$1" -m "$2" || { echo "mosquitto_pub to $1 failed"; exit 1; }; }
|
||||
n0=$(($(wc -l < "$LOG")+0))
|
||||
timeout 75 mosquitto_sub -h "$B" -p "$SP" -v -t "$N/#" > "$WORK/sub-$N.txt" 2> "$WORK/sub-$N.err" &
|
||||
sub_pid=$!
|
||||
sleep 20
|
||||
echo "=== $N: command to the switch and the 3000 byte publish ($(date +%T))"
|
||||
pub "$N/switch/relay/command" ON; sleep 2
|
||||
pub "$N/cmd" "hello-over-$N"; sleep 2
|
||||
$PY "$BTN" "$DEV" "$KEY" press "Publish big" || { echo "button press failed"; exit 1; }; sleep 3
|
||||
pub "$N/switch/relay/command" OFF; sleep 2
|
||||
if [ "$RESTART" = restart ]; then
|
||||
[ -f "$WORK/mosquitto-ws.conf" ] || { echo "no mosquitto-ws.conf in $WORK, cannot restart the broker"; exit 1; }
|
||||
echo "=== $N: broker restart ($(date +%T))"; n1=$(($(wc -l < "$LOG")+0))
|
||||
# Only this run's broker is signalled: its PID comes from mosquitto.pid, written when it was started
|
||||
pid=$(cat "$WORK/mosquitto.pid" 2>/dev/null); [ -n "$pid" ] || { echo "no mosquitto.pid in $WORK, cannot restart the broker"; exit 1; }
|
||||
kill "$pid" || { echo "broker PID $pid is not running, nothing to restart"; exit 1; }; sleep 8
|
||||
nc -z -w 3 "$B" 1883 && { echo "the old broker still answers on 1883 after the kill"; exit 1; }
|
||||
# exec so the PID is the broker's own and no shell stays behind holding the caller's output pipe open
|
||||
(cd "$WORK" && exec mosquitto -c mosquitto-ws.conf > mosquitto.out 2>&1 < /dev/null) &
|
||||
echo $! > "$WORK/mosquitto.pid"; sleep 25
|
||||
for port in $(awk '/^listener/ {print $2}' "$WORK/mosquitto-ws.conf"); do nc -z -w 3 "$B" "$port" || { echo "broker port $port not listening after the restart"; exit 1; }; done
|
||||
tail -n +$((n1+1)) "$LOG" | grep -a -q "MQTT_EVENT_CONNECTED\|\[mqtt:[0-9]*\]: Connected" || { echo "the device did not reconnect after the broker restart"; exit 1; }
|
||||
else
|
||||
echo "=== $N: no broker restart (pass 'restart' as the 7th argument for a local broker)"
|
||||
fi
|
||||
wait $sub_pid; sub_rc=$?
|
||||
[ "$sub_rc" = 124 ] || { echo "subscriber ended with status $sub_rc: $(cat "$WORK/sub-$N.err")"; exit 1; }
|
||||
echo "--- broker saw ($(grep -c . "$WORK/sub-$N.txt") messages): $(cut -c1-60 "$WORK/sub-$N.txt" | awk '{print $1}' | sort | uniq -c | tr '\n' ';')"
|
||||
big=$(grep "^$N/big " "$WORK/sub-$N.txt" | awk '{print length($2)}' | tr '\n' ' ')
|
||||
echo "--- big payload bytes seen: $big"
|
||||
echo "--- device log:"; show "$n0"
|
||||
case " $big " in *" 3000 "*) ;; *) echo "the 3000 byte payload did not reach the broker"; exit 1;; esac
|
||||
for want in "Relay ON" "cmd payload: hello-over-$N" "Relay OFF"; do
|
||||
tail -n +$((n0+1)) "$LOG" | grep -a -q "$want" || { echo "the device never logged '$want': the broker to device path failed"; exit 1; }
|
||||
done
|
||||
@@ -1,24 +0,0 @@
|
||||
#!/bin/sh
|
||||
# cli_tls_check.sh TREE [neg] YAML... : run `esphome clean-mqtt` from the checkout TREE for each config, which goes
|
||||
# through the same TLS setup in esphome/mqtt.py as `esphome logs` over MQTT, without needing a board. clean-mqtt never
|
||||
# exits on its own, so it runs under a 25 s timeout: status 124 after "Connected to MQTT broker!" means the CLI
|
||||
# connected. With neg every config must instead fail with CERTIFICATE_VERIFY_FAILED and never connect, so a negative
|
||||
# that fails for another reason (bad YAML, broker down) is reported as a failure too. A relative YAML path is taken
|
||||
# from the working directory, where the cleanmqtt-NAME.log outputs also go. Exit 1 when any config missed its result.
|
||||
TREE=$1; shift; PY=${PYTHON:-python3}; NEG=0
|
||||
[ "$1" = neg ] && { NEG=1; shift; }
|
||||
[ -d "$TREE/esphome" ] && [ -n "$1" ] || { echo "usage: cli_tls_check.sh TREE [neg] YAML..."; exit 2; }
|
||||
bad=0
|
||||
for y in "$@"; do
|
||||
case $y in /*) ;; *) y=$PWD/$y;; esac
|
||||
n=$(basename "$y" .yaml); log=$PWD/cleanmqtt-$n.log
|
||||
(cd "$TREE" && PYTHONUNBUFFERED=1 timeout 25 $PY -m esphome clean-mqtt "$y" > "$log" 2>&1); rc=$?
|
||||
if [ "$NEG" = 0 ] && [ "$rc" = 124 ] && grep -q "Connected to MQTT broker" "$log"; then
|
||||
echo "$n: connected"
|
||||
elif [ "$NEG" = 1 ] && grep -q "CERTIFICATE_VERIFY_FAILED" "$log" && ! grep -q "Connected to MQTT broker" "$log"; then
|
||||
echo "$n: rejected (CERTIFICATE_VERIFY_FAILED)"
|
||||
else
|
||||
echo "$n: FAILED (status $rc): $(grep -a -m1 -i 'cannot connect\|error' "$log" | cut -c1-160)"; bad=$((bad+1))
|
||||
fi
|
||||
done
|
||||
[ "$bad" = 0 ]
|
||||
@@ -1,53 +0,0 @@
|
||||
#!/bin/sh
|
||||
# flash_and_drive.sh TREE YAML PORT KEY BROKER_HOST MODE [SUB_PORT] : flash YAML from the checkout TREE over the serial
|
||||
# PORT, capture the serial log (cap-NAME.txt in the working directory), wait for the first MQTT connect or TLS error,
|
||||
# then drive the device with cases.sh (KEY as for cases.sh, - for a plaintext API). MODE local runs cases.sh with a
|
||||
# broker restart (the working directory must hold mosquitto-ws.conf and mosquitto.pid), public runs it without a
|
||||
# restart, neg only watches for 100 s (a build that must never connect). SUB_PORT is the plain listener cases.sh
|
||||
# subscribes on (default 1883). Ends with connect, disconnect, handshake error and crash counts, the config dump's
|
||||
# TLS line, the probe heap lines and the broker listener each connection used. Exit 1 when the capture did not start,
|
||||
# the device reached no MQTT event within 90 s (local and public), it crashed, or the mode's own check failed.
|
||||
TREE=$1; YAML=$2; PORT=$3; KEY=$4; B=$5; MODE=$6; SP=${7:-1883}
|
||||
case $YAML in /*) ;; *) YAML=$PWD/$YAML;; esac
|
||||
HERE=$(cd "$(dirname "$0")" && pwd); PY=${PYTHON:-python3}; N=$(basename "$YAML" .yaml); CAP=$PWD/cap-$N.txt; ULOG=$PWD/upload-$N.log
|
||||
[ -d "$TREE/esphome" ] && [ -e "$PORT" ] && [ -n "$KEY" ] && [ -n "$B" ] || { echo "usage: flash_and_drive.sh TREE YAML PORT KEY BROKER_HOST local|public|neg [SUB_PORT]"; exit 2; }
|
||||
case $MODE in local|public|neg) ;; *) echo "MODE must be local, public or neg"; exit 2;; esac
|
||||
pkill -f "[s]erial_capture.py $PORT "; sleep 1
|
||||
echo "=== $N: flash ($(date +%T))"
|
||||
(cd "$TREE" && PYTHONUNBUFFERED=1 timeout 300 $PY -m esphome upload "$YAML" --device "$PORT" > "$ULOG" 2>&1) || { echo "upload failed"; tail -5 "$ULOG"; exit 1; }
|
||||
SECS=200; [ "$MODE" = neg ] && SECS=100
|
||||
# a stale capture from an earlier run must not satisfy the wait below
|
||||
rm -f "$CAP"
|
||||
$PY "$HERE/../serial_capture.py" "$PORT" $SECS "$CAP" > "$PWD/cap-$N.stderr" 2>&1 &
|
||||
cap_pid=$!
|
||||
i=0; until grep -a -q "MQTT_EVENT_CONNECTED\|\[mqtt:[0-9]*\]: Connected\|mbedtls_ssl_handshake returned\|Failed to verify" "$CAP" 2>/dev/null || [ $i -ge 45 ]; do sleep 2; i=$((i+1)); done
|
||||
kill -0 $cap_pid 2>/dev/null && [ -f "$CAP" ] || { echo "serial capture is not running on $PORT"; tail -3 "$PWD/cap-$N.stderr"; exit 1; }
|
||||
DEV=$(grep -a -o 'IP Address: [0-9.]*' "$CAP" | head -1 | awk '{print $3}')
|
||||
if [ $i -ge 45 ] || [ -z "$DEV" ]; then
|
||||
echo "=== $N: no MQTT event or no IP within 90 s ($(date +%T))"
|
||||
[ "$MODE" = neg ] || { pkill -f "[s]erial_capture.py $PORT "; exit 1; }
|
||||
else
|
||||
echo "=== $N: first MQTT event after $((i*2)) s, device $DEV ($(date +%T))"
|
||||
fi
|
||||
grep -a 'ESPHome version\|\]: Transport\|\]: TLS:' "$CAP" | sed 's/\x1b\[[0-9;]*m//g' | cut -c1-120
|
||||
rc=0
|
||||
case $MODE in
|
||||
local) PYTHON=$PY sh "$HERE/cases.sh" "$N" "$KEY" "$B" "$SP" "$CAP" "$DEV" restart; rc=$?;;
|
||||
public) PYTHON=$PY sh "$HERE/cases.sh" "$N" "$KEY" "$B" "$SP" "$CAP" "$DEV"; rc=$?;;
|
||||
neg) sleep 70;;
|
||||
esac
|
||||
wait $cap_pid
|
||||
strip() { sed 's/\x1b\[[0-9;]*m//g'; }
|
||||
# count the backend's own events so the result does not depend on on_connect/on_disconnect log lines in the config
|
||||
connects=$(grep -a -c 'MQTT_EVENT_CONNECTED' "$CAP"); errors=$(grep -a -c 'mbedtls_ssl_handshake returned\|Failed to verify certificate' "$CAP")
|
||||
crashes=$(grep -a -c 'Guru\|abort()\|Backtrace' "$CAP")
|
||||
echo "=== $N: connects $connects, disconnects $(grep -a -c 'MQTT_EVENT_DISCONNECTED' "$CAP"), handshake errors $errors, crashes $crashes"
|
||||
grep -a 'mbedtls_ssl_handshake returned\|Failed to verify\|esp-tls' "$CAP" | strip | sed 's/^\[[^]]*\]//' | sort | uniq -c | sort -rn | head -4 | cut -c1-150
|
||||
grep -a '\[probe:' "$CAP" | strip | sed 's/.*\[probe:[0-9]*\]: //' | sed -n '1p;$p'
|
||||
[ -f "$PWD/mosquitto.log" ] && [ -n "$DEV" ] && echo "broker listeners used by $DEV: $(grep "New connection from $DEV" "$PWD/mosquitto.log" | sed 's/.*on port //' | sort | uniq -c | tr '\n' ';')"
|
||||
[ "$crashes" = 0 ] || { echo "device crashed $crashes time(s)"; exit 1; }
|
||||
if [ "$MODE" = neg ]; then
|
||||
[ "$connects" = 0 ] && [ "$errors" -gt 0 ] || { echo "negative case: expected no connect and a handshake error"; exit 1; }
|
||||
else
|
||||
[ "$rc" = 0 ] || { echo "cases.sh failed with status $rc"; exit 1; }
|
||||
fi
|
||||
@@ -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,36 +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"
|
||||
(cd $T && $PY -m esphome upload $M/$V/32/mq${X}32$V.yaml --device $P32 > $OUT/u32.log 2>&1) &
|
||||
(cd $T && $PY -m esphome upload $M/$V/66/mq${X}66$V.yaml --device $P66 > $OUT/u66.log 2>&1) &
|
||||
wait; echo "upload32: $(tail -1 $OUT/u32.log)"; echo "upload66: $(tail -1 $OUT/u66.log)"
|
||||
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
|
||||
for t in $(grep "homeassistant/button/" $OUT/broker.txt | grep "\"name\":\"mq${X}" | grep -o '"cmd_t":"[^"]*"' | cut -d'"' -f4 | sort -u); do
|
||||
echo "$(date +%T) press $t"; mosquitto_pub -h 127.0.0.1 -t "$t" -m PRESS
|
||||
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 &
|
||||
$PY -m esptool --port $P66 --after no-reset chip-id > $OUT/hold66.log 2>&1 &
|
||||
wait $(jobs -p | grep -v "^$SUB$") 2>/dev/null; sleep 40
|
||||
echo "$(date +%T) 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
|
||||
@@ -1,21 +0,0 @@
|
||||
#!/bin/sh
|
||||
# make_test_ca.sh BROKER_IP : a throwaway CA, a server certificate for the broker address and a client certificate
|
||||
# (30 days), written into the working directory; run it in the scratch directory where a copy of mosquitto-ws.conf
|
||||
# lives. The device config takes ca.crt as certificate_authority (skip_cert_cn_check: true, the name check does not
|
||||
# match an address) and client.crt/client.key as client_certificate/client_certificate_key for the listener that
|
||||
# requires one; other-ca.crt is a second CA for the negative case. The CA carries basicConstraints and keyUsage
|
||||
# because Python's default SSL context (esphome logs, esphome clean-mqtt) rejects a CA without them.
|
||||
set -e
|
||||
IP=$1
|
||||
[ -n "$IP" ] || { echo "usage: make_test_ca.sh BROKER_IP"; exit 2; }
|
||||
openssl req -x509 -newkey rsa:2048 -nodes -keyout ca.key -out ca.crt -days 30 -subj "/CN=hwtest-ca" \
|
||||
-addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign"
|
||||
openssl req -newkey rsa:2048 -nodes -keyout server.key -out server.csr -subj "/CN=hwtest-broker"
|
||||
printf "subjectAltName=IP:%s\nextendedKeyUsage=serverAuth\n" "$IP" > san.ext
|
||||
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 30 -extfile san.ext
|
||||
openssl req -newkey rsa:2048 -nodes -keyout client.key -out client.csr -subj "/CN=hwtest-client"
|
||||
printf "extendedKeyUsage=clientAuth\n" > client.ext
|
||||
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 30 -extfile client.ext
|
||||
openssl req -x509 -newkey rsa:2048 -nodes -keyout other-ca.key -out other-ca.crt -days 30 -subj "/CN=other-ca" \
|
||||
-addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign"
|
||||
openssl verify -CAfile ca.crt server.crt client.crt
|
||||
@@ -1,26 +0,0 @@
|
||||
# Copy next to the certificates in the scratch directory and start it there with
|
||||
# `mosquitto -c mosquitto-ws.conf & echo $! > mosquitto.pid` (cases.sh restarts that PID): plain MQTT, MQTT over TLS,
|
||||
# MQTT over TLS that requires a client certificate, MQTT over WebSocket, and MQTT over WebSocket with TLS
|
||||
# (server.crt, server.key, ca.crt from make_test_ca.sh in the same directory). log_type all gives the listener port
|
||||
# per connection.
|
||||
listener 1883
|
||||
protocol mqtt
|
||||
listener 8883
|
||||
protocol mqtt
|
||||
certfile server.crt
|
||||
keyfile server.key
|
||||
listener 8884
|
||||
protocol mqtt
|
||||
certfile server.crt
|
||||
keyfile server.key
|
||||
cafile ca.crt
|
||||
require_certificate true
|
||||
listener 9001
|
||||
protocol websockets
|
||||
listener 9002
|
||||
protocol websockets
|
||||
certfile server.crt
|
||||
keyfile server.key
|
||||
allow_anonymous true
|
||||
log_type all
|
||||
log_dest file mosquitto.log
|
||||
@@ -1,179 +0,0 @@
|
||||
"""Drive the online_image cases over the native API and judge each from the serial capture."""
|
||||
|
||||
import asyncio
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
|
||||
from aioesphomeapi import (
|
||||
APIClient,
|
||||
APIConnectionError,
|
||||
InvalidEncryptionKeyAPIError,
|
||||
RequiresEncryptionAPIError,
|
||||
)
|
||||
|
||||
HOST, KEY, CAPTURE, BASE, MODE = sys.argv[1:6]
|
||||
CAP_S = 45
|
||||
|
||||
CASES = [
|
||||
# (label, action, path, expected outcome)
|
||||
("ok bmp", "fetch", "ok.bmp", "finished"),
|
||||
("ok png", "fetch", "ok.png", "finished"),
|
||||
("ok jpg", "fetch", "ok.jpg", "finished"),
|
||||
("ok qoi", "fetch", "ok.qoi", "finished"),
|
||||
("truncated bmp", "fetch", "truncated.bmp", "error"),
|
||||
("ok bmp after error", "fetch", "ok.bmp", "finished"),
|
||||
("large header, 256 byte buffer", "fetch_small", "large_header.bmp", "error"),
|
||||
("ok bmp, 256 byte buffer", "fetch_small", "ok.bmp", "finished"),
|
||||
("empty body", "fetch", "empty.bmp", "error"),
|
||||
("stalled connection", "fetch", "stall.bmp", "error"),
|
||||
("closed early", "fetch", "closed_early.bmp", "error"),
|
||||
("slow but alive", "fetch", "slow.bmp", "finished"),
|
||||
("chunked bmp", "fetch", "chunked.bmp", "finished"),
|
||||
("chunked png", "fetch", "chunked.png", "finished"),
|
||||
("chunked qoi", "fetch", "chunked.qoi", "finished"),
|
||||
("chunked bmp cut", "fetch", "chunked_cut.bmp", "error"),
|
||||
("chunked png cut", "fetch", "chunked_cut.png", "any"),
|
||||
("no content-length", "fetch", "noclen.bmp", "any"),
|
||||
("huge jpeg claim", "fetch", "huge.jpg", "error"),
|
||||
("ok jpg after huge", "fetch", "ok.jpg", "finished"),
|
||||
("ok bmp again", "fetch", "ok.bmp", "finished"),
|
||||
("ok bmp refetch: 304", "refetch", "", "finished"),
|
||||
("ok png", "fetch", "ok.png", "finished"),
|
||||
("ok png refetch: 304", "refetch", "", "finished"),
|
||||
("chunked bmp", "fetch", "chunked.bmp", "finished"),
|
||||
("chunked bmp refetch: 304", "refetch", "", "finished"),
|
||||
("chunked png", "fetch", "chunked.png", "finished"),
|
||||
("chunked png refetch: not cached", "refetch", "", "finished"),
|
||||
("chunked png cut", "fetch", "chunked_cut.png", "any"),
|
||||
("chunked png cut refetch: not cached", "refetch", "", "any"),
|
||||
]
|
||||
if MODE == "base":
|
||||
# Each stuck case is followed by a fetch that shows the symptom, then a reboot.
|
||||
CASES = [
|
||||
("ok bmp", "fetch", "ok.bmp", "finished"),
|
||||
("truncated bmp", "fetch", "truncated.bmp", "error"),
|
||||
("ok bmp after truncated", "fetch", "ok.bmp", "finished"),
|
||||
("REBOOT", "", "", ""),
|
||||
("large header, 256 byte buffer", "fetch_small", "large_header.bmp", "error"),
|
||||
("ok bmp, 256 byte buffer", "fetch_small", "ok.bmp", "finished"),
|
||||
("REBOOT", "", "", ""),
|
||||
("empty body", "fetch", "empty.bmp", "error"),
|
||||
("ok bmp after empty", "fetch", "ok.bmp", "finished"),
|
||||
("REBOOT", "", "", ""),
|
||||
("stalled connection", "fetch", "stall.bmp", "error"),
|
||||
("ok bmp after stall", "fetch", "ok.bmp", "finished"),
|
||||
("REBOOT", "", "", ""),
|
||||
("closed early", "fetch", "closed_early.bmp", "error"),
|
||||
("ok bmp after closed early", "fetch", "ok.bmp", "finished"),
|
||||
("REBOOT", "", "", ""),
|
||||
("chunked png", "fetch", "chunked.png", "finished"),
|
||||
("ok bmp after chunked png", "fetch", "ok.bmp", "finished"),
|
||||
("REBOOT", "", "", ""),
|
||||
("chunked bmp cut", "fetch", "chunked_cut.bmp", "error"),
|
||||
("ok bmp after chunked cut", "fetch", "ok.bmp", "finished"),
|
||||
("REBOOT", "", "", ""),
|
||||
("huge jpeg claim", "fetch", "huge.jpg", "error"),
|
||||
("ok jpg after huge", "fetch", "ok.jpg", "finished"),
|
||||
]
|
||||
|
||||
OUTCOME = re.compile(r"download (finished|error): (img_small|img)")
|
||||
INTEREST = re.compile(
|
||||
r"\[(E|W)\]\[online_image|Image already being updated|download (finished|error)|Downloading image|Updating image|Image fully downloaded|HTTP 304|allocat|Panic|abort\(\)|Guru|Backtrace|rst:0x",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def tail(path: str, offset: int) -> tuple[list[str], int]:
|
||||
with pathlib.Path(path).open("rb") as f:
|
||||
f.seek(offset)
|
||||
data = f.read()
|
||||
return data.decode("utf-8", "replace").splitlines(), offset + len(data)
|
||||
|
||||
|
||||
async def connect() -> tuple[APIClient, dict, int]:
|
||||
for _ in range(60):
|
||||
try:
|
||||
c = APIClient(HOST, 6053, None, noise_psk=KEY)
|
||||
await c.connect(login=True)
|
||||
ents, services = await c.list_entities_services()
|
||||
except (InvalidEncryptionKeyAPIError, RequiresEncryptionAPIError) as exc:
|
||||
raise SystemExit(f"API key problem, not retrying: {exc}") from exc
|
||||
except (APIConnectionError, OSError) as exc:
|
||||
# only connection trouble is retried; a wrong key or a missing button must fail at once
|
||||
print(f"connect: {exc}", flush=True)
|
||||
await asyncio.sleep(3)
|
||||
continue
|
||||
btn = next(
|
||||
(e.key for e in ents if getattr(e, "object_id", "") == "reboot"), None
|
||||
)
|
||||
if btn is None:
|
||||
raise SystemExit("the config has no reboot button")
|
||||
return c, {s.name: s for s in services}, btn
|
||||
raise SystemExit("API never connected")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
client, actions, btn = await connect()
|
||||
with pathlib.Path(CAPTURE).open("rb") as f:
|
||||
f.seek(0, 2)
|
||||
offset = f.tell()
|
||||
rows = []
|
||||
for label, action, path, expect in CASES:
|
||||
if label == "REBOOT":
|
||||
client.button_command(btn)
|
||||
await asyncio.sleep(1)
|
||||
await client.disconnect()
|
||||
await asyncio.sleep(8)
|
||||
client, actions, btn = await connect()
|
||||
_, offset = tail(CAPTURE, offset)
|
||||
print("--- rebooted", flush=True)
|
||||
continue
|
||||
img = "img_small" if action.endswith("_small") else "img"
|
||||
t0 = time.monotonic()
|
||||
args = {} if action.startswith("refetch") else {"url": f"{BASE}/{path}"}
|
||||
await client.execute_service(actions[action], args)
|
||||
outcome, notes = "no outcome", []
|
||||
while time.monotonic() - t0 < CAP_S:
|
||||
await asyncio.sleep(0.5)
|
||||
lines, offset = tail(CAPTURE, offset)
|
||||
done = False
|
||||
for line in lines:
|
||||
if INTEREST.search(line):
|
||||
notes.append(line.strip())
|
||||
m = OUTCOME.search(line)
|
||||
if m and m.group(2) == img:
|
||||
outcome = m.group(1)
|
||||
done = True
|
||||
if done:
|
||||
break
|
||||
took = time.monotonic() - t0
|
||||
if outcome == "no outcome":
|
||||
took = CAP_S
|
||||
# drain a little more so the "already being updated" line lands
|
||||
await asyncio.sleep(1)
|
||||
lines, offset = tail(CAPTURE, offset)
|
||||
notes += [line.strip() for line in lines if INTEREST.search(line)]
|
||||
ok = outcome == expect or (expect == "any" and outcome != "no outcome")
|
||||
rows.append((label, path, expect, outcome, took, ok, notes))
|
||||
print(
|
||||
f"{'PASS' if ok else 'FAIL'} {label:32s} {path:18s} expected {expect:9s} got {outcome:10s} {took:5.1f}s",
|
||||
flush=True,
|
||||
)
|
||||
for n in notes:
|
||||
print(f" {n}", flush=True)
|
||||
await asyncio.sleep(1.5)
|
||||
await client.disconnect()
|
||||
print(
|
||||
"\nSUMMARY",
|
||||
"all expectations met"
|
||||
if all(r[5] for r in rows)
|
||||
else "MISMATCHES: " + ", ".join(r[0] for r in rows if not r[5]),
|
||||
flush=True,
|
||||
)
|
||||
if not all(r[5] for r in rows):
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,71 +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 re
|
||||
import sys
|
||||
import time
|
||||
|
||||
from aioesphomeapi import APIClient, ButtonInfo, LogLevel, 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]:
|
||||
for _ in range(30):
|
||||
c = APIClient(HOST, 6053, None, noise_psk=KEY)
|
||||
try:
|
||||
await c.connect(login=True)
|
||||
ents, services = await c.list_entities_services()
|
||||
reboot = next(
|
||||
e.key for e in ents if isinstance(e, ButtonInfo) and e.name == "Reboot"
|
||||
)
|
||||
return (
|
||||
c,
|
||||
{s.name: s for s in services if isinstance(s, UserService)},
|
||||
reboot,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
await asyncio.sleep(2)
|
||||
raise RuntimeError("device did not come back")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
for img in IMAGES:
|
||||
c, actions, reboot = await connect()
|
||||
c.button_command(reboot)
|
||||
await asyncio.sleep(1)
|
||||
await c.disconnect()
|
||||
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,
|
||||
)
|
||||
await c.disconnect()
|
||||
|
||||
|
||||
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)
|
||||
Loaded 100 of 6683 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user