Compare commits

...
Author SHA1 Message Date
J. Nick Koston 1973a1d29d [haier] Use Apply switches 2026-10-20 17:13:15 -10:00
mrtoy-me ded94c6698 [sx126x][sx127x] Move CONF_MODULATION to the shared component constants (#21249) 2026-10-20 16:50:49 -10:00
Jesse Hills e415c099e0 [font] Crop blank space from glyph bitmaps (#21235) 2026-10-21 15:46:15 +13:00
Jesse Hills d25a925a9b [epaper_spi] Only compile the driver sources the configured models need (#21228) 2026-10-21 15:39:52 +13:00
will-tm 41c3bbff25 [vl53l1x] Add VL53L1X time-of-flight distance sensor (#13605) 2026-10-20 16:05:46 -10:00
J. Nick Koston 3b8b6c6429 [ac_dimmer] Pack members and drop the unused zero-cross ISR pin (#21193) 2026-10-20 15:51:07 -10:00
J. Nick Koston 7c58a9698b [tests] Use require_service in the integration tests (#21214) 2026-10-21 01:47:31 +00:00
J. Nick Koston f47dca7e4e [tests] Use the exact entity lookups in the integration tests (#21213) 2026-10-20 15:42:31 -10:00
J. Nick Koston 701ba8eaa5 [key_collector] Stop copying the key strings (#21210) 2026-10-20 15:42:05 -10:00
J. Nick Koston 7af7b6f1d6 [bme680_bsec] Stop copying the device id (#21209) 2026-10-20 15:34:28 -10:00
J. Nick Koston 7fe4352786 [graph] Stop copying the trace name (#21211) 2026-10-20 15:33:38 -10:00
J. Nick Koston e70b0ace13 [display_menu_base] Stop copying the number format and switch texts (#21212) 2026-10-20 15:33:12 -10:00
J. Nick Koston 915458cfcf [tests] Use assert_device_name in the a-l integration tests (#21215) 2026-10-20 15:32:07 -10:00
J. Nick Koston 4eaad21f08 [tests] Use assert_device_name in the m-z integration tests (#21216) 2026-10-20 15:31:14 -10:00
J. Nick Koston 6e4e5ae830 [mqtt] Print the dump_config header in LOG_MQTT_COMPONENT (#21226) 2026-10-20 15:30:18 -10:00
J. Nick Koston a66faec424 [ci] Add the speaker media player, web_server_idf and MQTT WebSocket flows to the hardware-test skill (#21229) 2026-10-20 15:29:45 -10:00
J. Nick Koston d24cadbc8f [components] Use cv.only_when and cv.key_requires for key dependencies (#21236) 2026-10-20 15:27:03 -10:00
J. Nick Koston f9373bd7b3 [core] Add cv.only_when and cv.key_requires key validators (#21234) 2026-10-20 15:27:03 -10:00
Remco van Essen eb32f80d53 [speaker][speaker_source] Add a set volume for announcements that start while nothing is playing (#21002) 2026-10-20 14:48:11 -10:00
cef13c8697 [mqtt] Add MQTT over WebSocket transport for ESP32 IDF (#16056)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-20 23:33:06 +00:00
epicRE 876537186c [apc1][systa_bus] Move CONF_ERROR_CODE to the shared component constants (#21230) 2026-10-20 11:16:19 -10:00
Jacopo Labardi 6bb51c8cd9 [vbus] Discard P1 telegrams after a frame checksum error (#21045) 2026-10-20 11:15:40 -10:00
J. Nick Kostonandpre-commit-ci-lite[bot] 5d9ca0e45b [core] Share one log_entity_header() for entity dump_config headers (#21116)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-10-20 20:53:28 +00:00
f3f056ca41 [gree] Add sleep preset support for GREE YAC1FB9 (#18090)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-20 10:42:40 -10:00
bf36e7c33a [web_server_idf] Reduce loopTask stack usage for state SSE (#21109)
Co-authored-by: Jeroen Jansen <jeroen@Jeroens-MacBook-Air.local>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-10-20 10:41:10 -10:00
dependabot[bot] bac4d2aa29 Bump yamlrocks from 0.7.0 to 0.7.1 (#21223)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-20 19:32:37 +00:00
dependabot[bot] 992860637b Bump pillow from 12.3.0 to 13.0.0 (#21224)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-20 09:32:19 -10:00
dependabot[bot] b0d3899483 Bump pytest-mock from 3.16.0 to 3.17.0 (#21225)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-20 19:32:15 +00:00
dependabot[bot] f46ebdd345 Bump filelock from 4.2.0 to 4.2.1 (#21222)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-20 09:31:45 -10:00
fbe4699ad4 [nextion] Fix: Properly deliver numeric responses (#17744)
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 09:08:41 -10:00
Jesse Hills 6423af2978 [core] Replace flake8 with ruff docstring rules and drop unused scripts (#21176) 2026-10-21 07:32:56 +13:00
J. Nick Koston ebc9619e3b [sx126x] Pass the sx1261 hardware version as a flag (#21202) 2026-10-20 11:36:38 -04:00
324 changed files with 4645 additions and 2239 deletions
+7 -2
View File
@@ -115,7 +115,7 @@ Per-topic scripts, each described in the matching `reference/recipes/<component>
(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), `dfrobot_sen0395/` (API driver and case runner), `homeassistant_light/` (direct bulb driver, held-report case driver), `usb_audio/` (URL player).
capture decoder), `api_outgoing/` (wake cycle and Wi-Fi drop timing readers), `ld2450/` (zone number driver), `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 WebSocket listeners, test CA, transport case runner).
## Templates in `$SKILL/templates`
@@ -131,7 +131,8 @@ capture decoder), `api_outgoing/` (wake cycle and Wi-Fi drop timing readers), `l
`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`.
`dfrobot-sen0395-dut.yaml`, `aux-2-preprod-speaker-player-dut.yaml`, `web-server-sse-dut.yaml`,
`mqtt-transport-dut.yaml`.
## When something looks wrong
@@ -145,6 +146,10 @@ capture decoder), `api_outgoing/` (wake cycle and Wi-Fi drop timing readers), `l
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.
@@ -11,7 +11,7 @@ One file per component, named after it:
- [`hdmi_cec.md`](hdmi_cec.md): two-board wire
- [`ld2450.md`](ld2450.md): polygon zones, zone number round trip through the radar's readback
- [`libretiny.md`](libretiny.md): rtc preference emulation, BK72xx crash report on the next boot
- [`mqtt.md`](mqtt.md): broker bench, QoS, reconnect, crash log over MQTT
- [`mqtt.md`](mqtt.md): broker bench, QoS, reconnect, crash log over MQTT, WebSocket transports with a local and a public broker
- [`nrf52.md`](nrf52.md): dongle board support
- [`online_image.md`](online_image.md): stalled and malformed downloads
- [`openthread.md`](openthread.md): border router on the S3 host plus H2 RCP
@@ -28,3 +28,5 @@ One file per component, named after it:
- [`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
@@ -10,3 +10,22 @@ after bulk subscribe and unsubscribe; read the heap seconds later over several r
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 its three ports answer 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
@@ -0,0 +1,19 @@
# 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
@@ -0,0 +1,31 @@
# 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
@@ -1,6 +1,6 @@
"""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" [...]
usage: api_button.py HOST KEY list | press "Button name" [...] (KEY of - means a plaintext API)
"""
import asyncio
@@ -13,7 +13,7 @@ CMD, ARGS = sys.argv[3], sys.argv[4:]
async def main() -> None:
c = APIClient(HOST, 6053, None, noise_psk=KEY)
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)}
+42
View File
@@ -0,0 +1,42 @@
#!/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; }
(cd "$WORK" && mosquitto -c mosquitto-ws.conf > mosquitto.out 2>&1 & echo $! > "$WORK/mosquitto.pid"); sleep 25
for port in 1883 9001 9002; 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
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# make_test_ca.sh BROKER_IP : a throwaway CA and a server certificate for the broker address (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);
# other-ca.crt is a second CA for the negative case.
set -e
IP=$1
openssl req -x509 -newkey rsa:2048 -nodes -keyout ca.key -out ca.crt -days 30 -subj "/CN=hwtest-ca"
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 -x509 -newkey rsa:2048 -nodes -keyout other-ca.key -out other-ca.crt -days 30 -subj "/CN=other-ca"
openssl verify -CAfile ca.crt server.crt
@@ -0,0 +1,14 @@
# 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 WebSocket, and MQTT over WebSocket with TLS (server.crt and
# server.key from make_test_ca.sh in the same directory). log_type all gives the listener port per connection.
listener 1883
protocol mqtt
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
@@ -0,0 +1,12 @@
#!/bin/sh
# cases.sh HOST KEY MEDIA_URL ANN_URL CAPTURE LABEL : three play, announce, stop cycles on a speaker media player with the
# "Task names" probe button pressed idle, during media, during the announcement, after it and after the stop.
# KEY of - is plaintext. Serve FLAC files with `python3 -m http.server 8765 --directory www` (audio_http refuses WAV and MP3).
H=$1; K=$2; MEDIA=$3; ANN=$4; LOG=$5; LABEL=$6; PY=${PYTHON:-python3}; HERE=$(dirname "$0")
[ -r "$LOG" ] || { echo "usage: cases.sh HOST KEY MEDIA_URL ANN_URL CAPTURE LABEL (CAPTURE must be a readable file)"; exit 2; }
show() { tail -n +$(($1+1)) "$LOG" | sed 's/\x1b\[[0-9;]*m//g' | grep -a '\[tasks:\|speaker_media_player\|speaker_mixer\|\[W\]\|\[E\]\|Guru\|abort\|Backtrace' | grep -a -v 'took a long time' | cut -c1-180; }
for cycle in 1 2 3; do
n0=$(wc -l < "$LOG"); echo "=== $LABEL cycle $cycle ($(date +%T))"
$PY "$HERE/drive.py" "$H" "$K" "press:Task names" wait:1 "play:$MEDIA" wait:5 "press:Task names" wait:1 "ann:$ANN" wait:1.5 "press:Task names" wait:5 "press:Task names" wait:1 stop wait:3 "press:Task names" || { rc=$?; echo "driver failed ($rc), aborting"; exit $rc; }
sleep 1; echo "--- device log:"; show "$n0"
done
@@ -0,0 +1,50 @@
"""Drive the speaker platform media player (the first media player found) over one API connection.
usage: drive.py HOST KEY op [op ...]
ops: play:URL | ann:URL | stop | press:BUTTON | wait:S
"""
import asyncio
import sys
from aioesphomeapi import APIClient, ButtonInfo, MediaPlayerCommand, MediaPlayerInfo
HOST, KEY, OPS = sys.argv[1], sys.argv[2], sys.argv[3:]
async def main() -> None:
c = APIClient(HOST, 6053, None, noise_psk=None if KEY == "-" else KEY)
await c.connect(login=True)
try:
await run_ops(c)
finally:
await c.disconnect()
async def run_ops(c: APIClient) -> None:
ents, _ = await c.list_entities_services()
player = next((e for e in ents if isinstance(e, MediaPlayerInfo)), None)
if player is None:
sys.exit("no media player on this device")
buttons = {e.name: e for e in ents if isinstance(e, ButtonInfo)}
for op in OPS:
kind, _, rest = op.partition(":")
print(f"{asyncio.get_running_loop().time():.1f} {op}", flush=True)
if kind == "play":
c.media_player_command(player.key, media_url=rest)
elif kind == "ann":
c.media_player_command(player.key, media_url=rest, announcement=True)
elif kind == "stop":
c.media_player_command(player.key, command=MediaPlayerCommand.STOP)
elif kind == "press":
if rest not in buttons:
sys.exit(f"no button {rest!r}; have {sorted(buttons)}")
c.button_command(buttons[rest].key)
elif kind == "wait":
await asyncio.sleep(float(rest))
else:
sys.exit(f"unknown op {op!r}")
await asyncio.sleep(0.5)
asyncio.run(main())
@@ -0,0 +1,17 @@
#!/bin/sh
# httpd_cases.sh HOST USER PASS LABEL CAPTURE : HTTPD task stack load for the web_server_idf task size; probe lines from
# CAPTURE, SSE client output into the working directory. A failed step ends the run with its status.
H=$1; U=$2; P=$3; LABEL=$4; LOG=$5; HERE=$(dirname "$0")
[ -r "$LOG" ] || { echo "usage: httpd_cases.sh HOST USER PASS LABEL CAPTURE (CAPTURE must be a readable file)"; exit 2; }
probes() { tail -n +$(($1+1)) "$LOG" | sed 's/\x1b\[[0-9;]*m//g' | grep -a -o "\[[0-9:]*\]\[I\]\[probe:[0-9]*\]: .*httpd min free stack [0-9]*\|\[[0-9:]*\]\[[WE]\]\[[a-z_.]*:[0-9]*\].*\|Guru.*" | grep -a -v "took a long time\|does not fit\|\]\[httpd\]: /" | sed 's/\[I\]\[probe:[0-9]*\]: loopTask min free stack \([0-9]*\), httpd min free stack \([0-9]*\)/ loop \1 httpd \2/' | uniq -f1 | cut -c1-140; }
step() { n0=$(wc -l < "$LOG"); echo "=== $LABEL: $1 ($(date +%T))"; shift; "$@" || { rc=$?; echo "step failed ($rc)"; exit $rc; }; echo "--- device log:"; probes "$n0"; }
step "idle 15 s" sleep 15
step "request mix, 20 rounds" sh "$HERE/httpmix.sh" "$H" "$U" "$P" 20
# Two SSE clients next to the request mix; arguments stay quoted, nothing is reparsed as shell code
concurrent() {
sh "$HERE/ssecurl.sh" "$H" "$U" "$P" 40 "$PWD/sse1-$LABEL.txt" & p1=$!
sh "$HERE/ssecurl.sh" "$H" "$U" "$P" 40 "$PWD/sse2-$LABEL.txt" & p2=$!
sh "$HERE/httpmix.sh" "$H" "$U" "$P" 12 && wait $p1 && wait $p2
}
step "2 SSE clients 40 s with the request mix alongside" concurrent
step "idle 15 s after" sleep 15
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# httpmix.sh HOST USER PASS ROUNDS : authenticated request mix (curl --anyauth follows the server's Basic or Digest
# challenge): page, two json endpoints, a switch POST, a 404, an unauthenticated 401 and a 2 s SSE stream per round
H=$1; U=$2; P=$3; N=$4; ok=0; bad=0
# chk EXPECTED LABEL curl-args... : only LABEL is printed on a miss, never the argument list with the credentials
chk() { exp=$1; label=$2; shift 2; c=$(curl -s -m 6 -o /dev/null -w "%{http_code}" "$@"); if [ "$c" = "$exp" ]; then ok=$((ok+1)); else bad=$((bad+1)); echo "expected $exp got $c: $label"; fi; }
sse_tmp=$(mktemp)
for i in $(seq 1 $N); do
page=$(curl -s -m 6 -o /dev/null -w "%{http_code}" -u "$U:$P" --anyauth "http://$H/")
if [ "$page" = 200 ]; then ok=$((ok+1)); else bad=$((bad+1)); echo "expected 200 got $page: /"; fi
chk 200 "GET /sensor/Fast%201" -u "$U:$P" --anyauth "http://$H/sensor/Fast%201"
chk 200 "GET /text_sensor/Big" -u "$U:$P" --anyauth "http://$H/text_sensor/Big"
chk 200 "GET /switch/Toggle" -u "$U:$P" --anyauth "http://$H/switch/Toggle"
chk 200 "POST /switch/Toggle/toggle" -u "$U:$P" --anyauth -X POST -H "Content-Length: 0" "http://$H/switch/Toggle/toggle"
# The IDF server closes an unknown path without a response: curl ends with 52 (empty reply) or 56 (reset), never a
# timeout (28) or a refused connection (7); only trust the close when the page just answered
c=$(curl -s -m 6 -o /dev/null -w "%{http_code}" -u "$U:$P" --anyauth "http://$H/nonexistent"); rc=$?
if [ "$c" = 000 ] && [ "$page" = 200 ] && { [ "$rc" = 52 ] || [ "$rc" = 56 ]; }; then ok=$((ok+1)); else bad=$((bad+1)); echo "unknown path: got $c, curl status $rc, with the page at $page"; fi
chk 401 "GET / without credentials" "http://$H/"
timeout 2 curl -s -N -u "$U:$P" --anyauth -o "$sse_tmp" "http://$H/events" 2>/dev/null; rc=$?
if [ "$rc" = 124 ] && grep -q "^event: state" "$sse_tmp"; then ok=$((ok+1)); else bad=$((bad+1)); echo "SSE stream: curl status $rc, $(grep -c '^event: state' "$sse_tmp") state events"; fi
sleep 1
done
rm -f "$sse_tmp"
echo "httpmix: $ok ok, $bad unexpected"
[ "$bad" = 0 ]
@@ -0,0 +1,187 @@
"""SSE client(s) for a web_server /events stream: counts state events and checks each is valid JSON.
usage: sse.py HOST SECONDS [--clients N] [--stall] [--churn CYCLES]
--stall opens one extra connection that never reads (the device's socket buffer fills); --churn opens
and abruptly closes a connection CYCLES times, 2 s apart, next to the reading clients.
"""
import argparse
from collections import Counter
import contextlib
import json
import socket
import sys
import threading
import time
ap = argparse.ArgumentParser()
ap.add_argument("host")
ap.add_argument("seconds", type=float)
ap.add_argument("--clients", type=int, default=1)
ap.add_argument("--stall", action="store_true")
ap.add_argument("--churn", type=int, default=0)
args = ap.parse_args()
REQ = b"GET /events HTTP/1.1\r\nHost: %s\r\nAccept: text/event-stream\r\nConnection: keep-alive\r\n\r\n"
def read_chunked(sock, deadline, on_line):
"""Decode HTTP chunked transfer encoding and feed complete event-stream lines to on_line."""
buf = b""
body = b""
headers_done = False
sock.settimeout(1.0)
while time.monotonic() < deadline:
try:
data = sock.recv(65536)
except TimeoutError:
continue
if not data:
return "closed"
buf += data
if not headers_done:
i = buf.find(b"\r\n\r\n")
if i < 0:
continue
headers_done = True
buf = buf[i + 4 :]
while True:
i = buf.find(b"\r\n")
if i < 0:
break
size = int(buf[:i].split(b";")[0], 16)
if len(buf) < i + 2 + size + 2:
break
body += buf[i + 2 : i + 2 + size]
buf = buf[i + 2 + size + 2 :]
if size == 0:
return "closed"
while b"\n" in body:
line, body = body.split(b"\n", 1)
on_line(line.rstrip(b"\r"))
return "deadline"
class Client(threading.Thread):
def __init__(self, idx, seconds):
super().__init__(daemon=True)
self.idx = idx
self.seconds = seconds
self.events = Counter()
self.ids = Counter()
self.invalid = 0
self.max_data = 0
self.bytes = 0
self.end = "?"
self.cur_event = None
def on_line(self, line):
self.bytes += len(line) + 1
if line.startswith(b"event:"):
self.cur_event = line[6:].strip().decode()
elif line.startswith(b"data:"):
ev = self.cur_event or "message"
self.events[ev] += 1
data = line[5:].strip()
self.max_data = max(self.max_data, len(data))
if ev in ("state", "state_detail_all"):
try:
obj = json.loads(data)
self.ids[obj.get("id", "?")] += 1
except ValueError:
self.invalid += 1
elif line == b"":
self.cur_event = None
def run(self):
try:
s = socket.create_connection((args.host, 80), timeout=5)
s.sendall(REQ % args.host.encode())
self.end = read_chunked(s, time.monotonic() + self.seconds, self.on_line)
s.close()
except (OSError, ValueError) as e:
self.end = f"error: {e}"
clients = [Client(i, args.seconds) for i in range(args.clients)]
for c in clients:
c.start()
time.sleep(0.3)
stall_sock = None
if args.stall:
# The window scale is negotiated in the SYN, so the small buffer must be set before connect()
stall_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
stall_sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2048)
stall_sock.settimeout(5)
stall_sock.connect((args.host, 80))
stall_sock.sendall(REQ % args.host.encode())
print("stalled client opened (never reads)", flush=True)
churn_done = 0
for _ in range(args.churn):
try:
cs = socket.create_connection((args.host, 80), timeout=5)
cs.sendall(REQ % args.host.encode())
cs.settimeout(1.0)
with contextlib.suppress(TimeoutError):
cs.recv(4096)
cs.setsockopt(
socket.SOL_SOCKET, socket.SO_LINGER, b"\x01\x00\x00\x00\x00\x00\x00\x00"
) # RST on close
cs.close()
churn_done += 1
except OSError as e:
print("churn error", e, flush=True)
time.sleep(2)
if args.churn:
print(f"churn: {churn_done}/{args.churn} abrupt closes", flush=True)
for c in clients:
c.join()
stall_closed = None
if stall_sock is not None:
# Drain what the small buffer holds: a close shows as b"" or a reset after it. A session the device left
# open keeps feeding events, so the drain has its own deadline and data past it means "still open".
stall_sock.settimeout(2.0)
drain_deadline = time.monotonic() + 5.0
try:
while stall_sock.recv(65536):
if time.monotonic() > drain_deadline:
break
else:
stall_closed = True
except TimeoutError:
pass
except OSError:
stall_closed = True
if stall_closed is None:
stall_closed = False
print(
"stalled client: closed by device"
if stall_closed
else "stalled client: still open",
flush=True,
)
stall_sock.close()
for c in clients:
states = c.events["state"]
print(
f"client {c.idx}: {c.end}, {states} state events, {c.invalid} invalid JSON, max data {c.max_data} B, "
f"{c.bytes} B, other events { {k: v for k, v in c.events.items() if k != 'state'} }",
flush=True,
)
print(" per id:", dict(sorted(c.ids.items())), flush=True)
failed = [
c for c in clients if c.end != "deadline" or c.invalid or not c.events["state"]
]
if failed:
sys.exit(
f"{len(failed)} client(s) did not run clean to the deadline with valid state events"
)
if stall_closed is False:
sys.exit("stalled session was not closed by the device")
if churn_done < args.churn:
sys.exit(f"only {churn_done} of {args.churn} churn connections were made")
@@ -0,0 +1,19 @@
#!/bin/sh
# sse_cases.sh HOST KEY LABEL CAPTURE : the SSE cases against templates/web-server-sse-dut.yaml with a console capture
# running into CAPTURE; KEY is the API key (- for plaintext). The burst client output goes to the working directory.
H=$1; K=$2; LABEL=$3; LOG=$4; PY=${PYTHON:-python3}; HERE=$(dirname "$0"); BTN=$HERE/../api_button.py
[ -r "$LOG" ] || { echo "usage: sse_cases.sh HOST KEY LABEL CAPTURE (CAPTURE must be a readable file)"; exit 2; }
show() { tail -n +$(($1+1)) "$LOG" | sed 's/\x1b\[[0-9;]*m//g' | grep -a '\[probe:\|\[W\]\|\[E\]\|web_server\|Guru\|abort\|Backtrace\|ESPHome version' | grep -a -v 'took a long time' | cut -c1-200; }
step() { n0=$(wc -l < "$LOG"); echo "=== $LABEL: $1 ($(date +%T))"; shift; "$@" || { rc=$?; echo "client failed ($rc), aborting"; exit $rc; }; echo "--- device log:"; show "$n0"; }
step "idle 15 s, no client" sleep 15
step "1 client 60 s" $PY "$HERE/sse.py" "$H" 60 --clients 1
step "4 clients 60 s" $PY "$HERE/sse.py" "$H" 60 --clients 4
step "1 reader plus a stalled client 45 s" $PY "$HERE/sse.py" "$H" 45 --clients 1 --stall
step "1 reader plus 10 abrupt closes 30 s" $PY "$HERE/sse.py" "$H" 30 --clients 1 --churn 10
n0=$(wc -l < "$LOG"); echo "=== $LABEL: 2 clients 25 s with the Burst button at 5 s ($(date +%T))"
$PY "$HERE/sse.py" "$H" 25 --clients 2 > "$PWD/burst-$LABEL.txt" 2>&1 &
pid=$!
sleep 5; $PY "$BTN" "$H" "$K" press "Burst" || { echo "button press failed"; exit 1; }
wait $pid || { cat "$PWD/burst-$LABEL.txt"; echo "SSE clients failed during the burst"; exit 1; }
cat "$PWD/burst-$LABEL.txt"; echo "--- device log:"; show "$n0"
step "idle 15 s after" sleep 15
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
# ssecurl.sh HOST USER PASS SECONDS OUT : one authenticated SSE client through curl; counts state events and checks JSON
H=$1; U=$2; P=$3; T=$4; OUT=$5
timeout "$T" curl -sS -f -N -u "$U:$P" --anyauth "http://$H/events" > "$OUT"; rc=$?
[ "$rc" = 124 ] || { echo "sse: curl ended with status $rc before the $T s deadline"; exit 1; }
python3 - "$OUT" <<'PY'
import json, sys
states = invalid = 0; biggest = 0; ev = None
data = open(sys.argv[1], "rb").read()
lines = data.split(b"\n")
if not data.endswith(b"\n"):
lines = lines[:-1] # the deadline can cut the last line in half; only complete lines are checked
for line in lines:
line = line.rstrip(b"\r")
if line.startswith(b"event:"):
ev = line[6:].strip()
elif line.startswith(b"data:") and ev == b"state":
states += 1; d = line[5:].strip(); biggest = max(biggest, len(d))
try: json.loads(d)
except ValueError: invalid += 1
elif line == b"":
ev = None
print(f"sse: {states} state events, {invalid} invalid JSON, largest {biggest} B")
sys.exit(1 if invalid or not states else 0)
PY
@@ -0,0 +1,66 @@
# Needs packages/aux-2-pre-prod.yaml from NabuCasa/aux-2 at commit 283f2e64 next to this file (see
# reference/recipes/usb_audio.md). The AUX-2 package with the package's speaker_source player swapped for the speaker
# platform player, which is the one built on speaker/media_player/audio_pipeline.cpp, plus the task name probe.
packages:
core: !include aux-2-pre-prod.yaml
esphome:
name: aux-2-dut
name_add_mac_suffix: false
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
api:
encryption:
key: !secret api_key
logger:
level: DEBUG
sendspin:
unpaired_access: true
media_player:
- id: !remove external_media_player
- platform: speaker
id: speaker_media_player
name: Media Player
volume_increment: 0.05
volume_min: 0.4
volume_max: 0.85
announcement_pipeline:
speaker: announcement_resampling_speaker
format: FLAC
num_channels: 1
sample_rate: 48000
media_pipeline:
speaker: media_resampling_speaker
format: FLAC
num_channels: 2
sample_rate: 48000
on_announcement:
- mixer_speaker.apply_ducking:
id: media_mixing_input
decibel_reduction: 20
duration: 0.0s
button:
- platform: template
name: Task names
on_press:
- lambda: |-
static const char *const NAMES[] = {"ann_read", "ann_decode", "med_read", "med_decode"};
for (const char *n : NAMES) {
TaskHandle_t h = xTaskGetHandle(n);
if (h == nullptr) {
ESP_LOGI("tasks", "%s: missing", n);
} else {
ESP_LOGI("tasks", "%s: found as '%s', stack high water %u", n, pcTaskGetName(h),
(unsigned) uxTaskGetStackHighWaterMark(h));
}
}
ESP_LOGI("tasks", "internal free %u, largest block %u", (unsigned) heap_caps_get_free_size(MALLOC_CAP_INTERNAL),
(unsigned) heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL));
@@ -0,0 +1,88 @@
# MQTT transport test (#16056, needs that PR's tree for the transport option): one build per transport, name and mqtt block per file (see reference/recipes/mqtt.md).
esp32:
board: esp32dev
framework:
type: esp-idf
logger:
level: VERBOSE
logs:
wifi: DEBUG
api: DEBUG
api.connection: DEBUG
scheduler: DEBUG
component: DEBUG
sensor: DEBUG
esp32: DEBUG
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
power_save_mode: none
api:
encryption:
key: !secret api_key
reboot_timeout: 0s
ota:
- platform: esphome
interval:
- interval: 10s
then:
- lambda: |-
ESP_LOGI("probe", "mqtt connected %d, internal free %u, largest block %u", id(mq).is_connected(),
(unsigned) heap_caps_get_free_size(MALLOC_CAP_INTERNAL),
(unsigned) heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL));
sensor:
- platform: template
name: Counter
update_interval: 2s
accuracy_decimals: 0
lambda: |-
static uint32_t n = 0;
return n++;
switch:
- platform: template
name: Relay
id: relay
optimistic: true
on_turn_on:
- logger.log: "Relay ON"
on_turn_off:
- logger.log: "Relay OFF"
button:
- platform: template
name: Publish big
on_press:
- mqtt.publish:
topic: ${name}/big
payload: !lambda |-
return std::string(3000, 'q');
substitutions:
name: mqtt-dut
esphome:
name: ${name}
mqtt:
id: mq
broker: !secret broker_ip # test.mosquitto.org for the public bundle run
port: 9002 # 1883 tcp, 9001 ws, 9002 wss, 8081 public wss
transport: wss # drop for tcp
ws_path: /mqtt # ws and wss only
certificate_authority: !secret mqtt_ca # drop for the bundle runs
skip_cert_cn_check: true # with the local CA only: the certificate names an address
reboot_timeout: 0s
discovery: false
on_message:
- topic: ${name}/cmd
then:
- logger.log:
format: "cmd payload: %s"
args: ["x.c_str()"]
@@ -0,0 +1,136 @@
# web_server_idf state SSE and HTTPD task stress (#21109, #21038). Add `auth:` with `type: digest` for the HTTPD
# stack case; the entity endpoints are named after the entities (/sensor/Fast%201, /switch/Toggle/toggle).
esphome:
name: web-server-dut
esp32:
board: esp32dev
framework:
type: esp-idf
logger:
level: DEBUG
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
power_save_mode: none
api:
encryption:
key: !secret api_key
reboot_timeout: 0s
ota:
- platform: esphome
web_server:
port: 80
version: 3
# Stack and heap probe from the main loop task (loopTask) and the HTTPD task.
interval:
- interval: 5s
then:
- lambda: |-
TaskHandle_t httpd = xTaskGetHandle("httpd");
if (httpd == nullptr) {
ESP_LOGW("probe", "httpd task not found, loopTask min free stack %u",
(unsigned) uxTaskGetStackHighWaterMark(nullptr));
return;
}
ESP_LOGI("probe", "loopTask min free stack %u, httpd min free stack %u, internal free %u, largest block %u",
(unsigned) uxTaskGetStackHighWaterMark(nullptr), (unsigned) uxTaskGetStackHighWaterMark(httpd),
(unsigned) heap_caps_get_free_size(MALLOC_CAP_INTERNAL),
(unsigned) heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL));
# Small state events: eight sensors at 200 ms, well under the 1024 byte stack buffer.
sensor:
- platform: template
name: Fast 1
id: fast1
update_interval: 200ms
accuracy_decimals: 3
lambda: return random_float() * 100.0f;
- platform: template
name: Fast 2
update_interval: 200ms
accuracy_decimals: 3
lambda: return random_float() * 100.0f;
- platform: template
name: Fast 3
update_interval: 200ms
accuracy_decimals: 3
lambda: return random_float() * 100.0f;
- platform: template
name: Fast 4
update_interval: 200ms
accuracy_decimals: 3
lambda: return random_float() * 100.0f;
- platform: template
name: Fast 5
update_interval: 200ms
accuracy_decimals: 3
lambda: return random_float() * 100.0f;
- platform: template
name: Fast 6
update_interval: 200ms
accuracy_decimals: 3
lambda: return random_float() * 100.0f;
- platform: template
name: Fast 7
update_interval: 200ms
accuracy_decimals: 3
lambda: return random_float() * 100.0f;
- platform: template
name: Fast 8
update_interval: 200ms
accuracy_decimals: 3
lambda: return random_float() * 100.0f;
# Large state events: the text sensor JSON carries the string twice (value and state).
# mid ~1.3 kB goes to the 2048 byte tail, big ~3.7 kB grows the tail to 4096, huge ~5.7 kB exceeds the
# 5120 byte JSON room and must be dropped with "State event does not fit".
text_sensor:
- platform: template
name: Mid
id: mid
update_interval: 1s
lambda: |-
static uint32_t n = 0;
std::string s = std::to_string(n++) + ":";
s.append(600 - s.size(), 'm');
return s;
- platform: template
name: Big
id: big
update_interval: 2s
lambda: |-
static uint32_t n = 0;
std::string s = std::to_string(n++) + ":";
s.append(1800 - s.size(), 'b');
return s;
- platform: template
name: Huge
id: huge
update_interval: 7s
lambda: |-
static uint32_t n = 0;
std::string s = std::to_string(n++) + ":";
s.append(2800 - s.size(), 'h');
return s;
switch:
- platform: template
name: Toggle
optimistic: true
button:
- platform: template
name: Burst
on_press:
- lambda: |-
for (int i = 0; i < 50; i++) {
id(fast1).publish_state(i);
id(mid).publish_state(std::string(600, 'x'));
}
-4
View File
@@ -28,7 +28,6 @@
// python
"ms-python.python",
"ms-python.pylint",
"ms-python.flake8",
"charliermarsh.ruff",
"visualstudioexptteam.vscodeintellicode",
// yaml
@@ -48,9 +47,6 @@
"pylint.args": [
"--rcfile=${workspaceFolder}/pyproject.toml"
],
"flake8.args": [
"--config=${workspaceFolder}/.flake8"
],
"ruff.configuration": "${workspaceFolder}/pyproject.toml",
"[python]": {
// VS will say "Value is not accepted" before building the devcontainer, but the warning
-42
View File
@@ -1,42 +0,0 @@
[flake8]
max-line-length = 120
# Following 4 for black compatibility
# E501: line too long
# W503: Line break occurred before a binary operator
# E203: Whitespace before ':'
# D202 No blank lines allowed after function docstring
# TODO fix flake8
# D100 Missing docstring in public module
# D101 Missing docstring in public class
# D102 Missing docstring in public method
# D103 Missing docstring in public function
# D104 Missing docstring in public package
# D105 Missing docstring in magic method
# D107 Missing docstring in __init__
# D200 One-line docstring should fit on one line with quotes
# D205 1 blank line required between summary line and description
# D209 Multi-line docstring closing quotes should be on a separate line
# D400 First line should end with a period
# D401 First line should be in imperative mood
ignore =
E501,
W503,
E203,
D202,
D100,
D101,
D102,
D103,
D104,
D105,
D107,
D200,
D205,
D209,
D400,
D401,
exclude = api_pb2.py
@@ -1,39 +0,0 @@
{
"problemMatcher": [
{
"owner": "ruff",
"severity": "error",
"pattern": [
{
"regexp": "^(.*): (Please format this file with the ruff formatter)",
"file": 1,
"message": 2
}
]
},
{
"owner": "flake8",
"severity": "error",
"pattern": [
{
"regexp": "^(.*):(\\d+): ([EFCDNW]\\d{3}.*)$",
"file": 1,
"line": 2,
"message": 3
}
]
},
{
"owner": "pylint",
"severity": "error",
"pattern": [
{
"regexp": "^(.*):(\\d+): (\\[[EFCRW]\\d{4}\\(.*\\),.*\\].*)$",
"file": 1,
"line": 2,
"message": 3
}
]
}
]
}
+1 -1
View File
@@ -85,7 +85,7 @@ jobs:
- name: Verify prek clean
# Second pass: re-run all hooks against the now-fixed tree.
# Auto-fixers exit 0 (nothing to change); any remaining failure
# from a check-only hook (flake8 / yamllint / ci-custom) is a
# from a check-only hook (yamllint / ci-custom) is a
# real issue and fails the workflow loudly. Same PREK_SKIP list as
# above for the same reasons.
env:
-8
View File
@@ -17,14 +17,6 @@ repos:
args: [--fix]
# Run the formatter.
- id: ruff-format
- repo: https://github.com/PyCQA/flake8
rev: 7.4.1
hooks:
- id: flake8
additional_dependencies:
- flake8-docstrings==1.7.0
- pydocstyle==5.1.1
files: ^(esphome|tests)/.+\.py$
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
+1 -1
View File
@@ -55,7 +55,7 @@ file does, and it is the authority when they disagree. The most useful starting
* https://developers.esphome.io/contributing/code/ - contribution rules, public API and breaking changes.
* **Formatting:**
* **Python:** Uses `ruff` and `flake8` for linting and formatting. Configuration is in `pyproject.toml`.
* **Python:** Uses `ruff` for linting and formatting. Configuration is in `pyproject.toml`.
* **C++:** Uses `clang-format` for formatting. Configuration is in `.clang-format`.
* **Naming Conventions:**
+1
View File
@@ -697,6 +697,7 @@ esphome/components/veml3235/* @kbx81
esphome/components/veml7700/* @latonita
esphome/components/version/* @esphome/core
esphome/components/vevor_dtx/* @Bofr5555
esphome/components/vl53l1x/* @will-tm
esphome/components/voice_assistant/* @jesserockz @kahrendt
esphome/components/wake_on_lan/* @clydebarrow @willwill2will54
esphome/components/watchdog/* @oarcher
+10 -18
View File
@@ -184,11 +184,9 @@ void AcDimmer::setup() {
this->store_.zero_cross_pin_number = this->zero_cross_pin_->get_pin();
this->store_.min_power = static_cast<uint16_t>(this->min_power_ * 1000);
this->min_power_ = 0;
this->store_.method = this->method_;
if (setup_zero_cross_pin) {
this->zero_cross_pin_->setup();
this->store_.zero_cross_pin = this->zero_cross_pin_->to_isr();
this->zero_cross_pin_->attach_interrupt(&AcDimmerDataStore::s_gpio_intr, &this->store_,
this->zero_cross_interrupt_type_);
}
@@ -227,24 +225,18 @@ void AcDimmer::dump_config() {
ESP_LOGCONFIG(TAG,
"AcDimmer:\n"
" Min Power: %.1f%%\n"
" Init with half cycle: %s",
this->store_.min_power / 10.0f, YESNO(this->init_with_half_cycle_));
" Init with half cycle: %s\n"
" Interrupt Type: %s\n"
" Method: %s",
this->store_.min_power / 10.0f, YESNO(this->init_with_half_cycle_),
this->zero_cross_interrupt_type_ == gpio::INTERRUPT_RISING_EDGE ? LOG_STR_LITERAL("rising")
: this->zero_cross_interrupt_type_ == gpio::INTERRUPT_FALLING_EDGE ? LOG_STR_LITERAL("falling")
: LOG_STR_LITERAL("any"),
this->store_.method == DIM_METHOD_LEADING_PULSE ? LOG_STR_LITERAL("leading pulse")
: this->store_.method == DIM_METHOD_LEADING ? LOG_STR_LITERAL("leading")
: LOG_STR_LITERAL("trailing"));
LOG_PIN(" Output Pin: ", this->gate_pin_);
LOG_PIN(" Zero-Cross Pin: ", this->zero_cross_pin_);
if (this->zero_cross_interrupt_type_ == gpio::INTERRUPT_RISING_EDGE) {
ESP_LOGCONFIG(TAG, " Interrupt Type: rising");
} else if (this->zero_cross_interrupt_type_ == gpio::INTERRUPT_FALLING_EDGE) {
ESP_LOGCONFIG(TAG, " Interrupt Type: falling");
} else {
ESP_LOGCONFIG(TAG, " Interrupt Type: any");
}
if (method_ == DIM_METHOD_LEADING_PULSE) {
ESP_LOGCONFIG(TAG, " Method: leading pulse");
} else if (method_ == DIM_METHOD_LEADING) {
ESP_LOGCONFIG(TAG, " Method: leading");
} else {
ESP_LOGCONFIG(TAG, " Method: trailing");
}
LOG_FLOAT_OUTPUT(this);
ESP_LOGV(TAG, " Estimated Frequency: %.3fHz", 1e6f / this->store_.cycle_time_us / 2);
}
+9 -12
View File
@@ -6,19 +6,11 @@
namespace esphome::ac_dimmer {
enum DimMethod { DIM_METHOD_LEADING_PULSE = 0, DIM_METHOD_LEADING, DIM_METHOD_TRAILING };
enum DimMethod : uint8_t { DIM_METHOD_LEADING_PULSE = 0, DIM_METHOD_LEADING, DIM_METHOD_TRAILING };
struct AcDimmerDataStore {
/// Zero-cross pin
ISRInternalGPIOPin zero_cross_pin;
/// Zero-cross pin number - used to share ZC pin across multiple dimmers
uint8_t zero_cross_pin_number;
/// Output pin to write to
ISRInternalGPIOPin gate_pin;
/// Value of the dimmer - 0 to 65535.
uint16_t value;
/// Minimum power for activation
uint16_t min_power;
/// Time between the last two ZC pulses
uint32_t cycle_time_us;
/// Time (in micros()) of last ZC signal
@@ -27,6 +19,12 @@ struct AcDimmerDataStore {
uint32_t enable_time_us;
/// Time since last ZC pulse to disable gate pin. 0 means no disable.
uint32_t disable_time_us;
/// Value of the dimmer - 0 to 65535.
uint16_t value;
/// Minimum power for activation
uint16_t min_power;
/// Zero-cross pin number - used to share ZC pin across multiple dimmers
uint8_t zero_cross_pin_number;
/// Set to send the first half ac cycle complete
bool init_cycle;
/// Dimmer method
@@ -50,17 +48,16 @@ class AcDimmer final : public output::FloatOutput, public Component {
void set_zero_cross_pin(InternalGPIOPin *zero_cross_pin) { zero_cross_pin_ = zero_cross_pin; }
void set_zero_cross_interrupt_type(gpio::InterruptType type) { zero_cross_interrupt_type_ = type; }
void set_init_with_half_cycle(bool init_with_half_cycle) { init_with_half_cycle_ = init_with_half_cycle; }
void set_method(DimMethod method) { method_ = method; }
void set_method(DimMethod method) { this->store_.method = method; }
protected:
void write_state(float state) override;
InternalGPIOPin *gate_pin_;
InternalGPIOPin *zero_cross_pin_;
gpio::InterruptType zero_cross_interrupt_type_;
AcDimmerDataStore store_;
gpio::InterruptType zero_cross_interrupt_type_;
bool init_with_half_cycle_;
DimMethod method_;
};
} // namespace esphome::ac_dimmer
+1 -2
View File
@@ -2,7 +2,7 @@ from esphome import automation, pins
from esphome.automation import maybe_simple_id
import esphome.codegen as cg
from esphome.components import sensor, uart
from esphome.components.const import CONF_AQI
from esphome.components.const import CONF_AQI, CONF_ERROR_CODE
import esphome.config_validation as cv
from esphome.const import (
CONF_ECO2,
@@ -55,7 +55,6 @@ CONF_RAW_HUMIDITY = "raw_humidity"
CONF_RS0 = "rs0"
CONF_RS2 = "rs2"
CONF_RS3 = "rs3"
CONF_ERROR_CODE = "error_code"
apc1_ns = cg.esphome_ns.namespace("apc1")
APC1Component = apc1_ns.class_("APC1Component", uart.UARTDevice, cg.Component)
+6 -14
View File
@@ -306,11 +306,6 @@ def _consume_api_sockets(config: ConfigType) -> ConfigType:
def _validate_outgoing_connection(config: ConfigType) -> ConfigType:
if (outgoing := config.get(CONF_OUTGOING_CONNECTION)) is None:
return config
if CONF_ENCRYPTION not in config:
raise cv.Invalid(
"outgoing_connection requires 'encryption' so the peer is verified by key",
path=[CONF_OUTGOING_CONNECTION],
)
# A device with no client reboots once reboot_timeout passes, so a delay that
# reaches it would reboot the device before it ever dials
reboot_timeout = config[CONF_REBOOT_TIMEOUT]
@@ -445,6 +440,11 @@ CONFIG_SCHEMA = cv.All(
}
).extend(cv.COMPONENT_SCHEMA),
cv.rename_key(CONF_SERVICES, CONF_ACTIONS),
cv.key_requires(
CONF_OUTGOING_CONNECTION,
CONF_ENCRYPTION,
hint="The peer is verified by its key",
),
_validate_outgoing_connection,
_consume_api_sockets,
_register_provisioning_source,
@@ -728,15 +728,6 @@ VARIABLES_FIELDS_SCHEMA = cv.All(VARIABLES_SCHEMA, cv.Length(max=_FIELD_MAP_MAX)
def _validate_response_config(config: ConfigType) -> ConfigType:
# Validate dependencies:
# - response_template requires capture_response: true
# - capture_response: true requires on_success
if CONF_RESPONSE_TEMPLATE in config and not config[CONF_CAPTURE_RESPONSE]:
raise cv.Invalid(
f"`{CONF_RESPONSE_TEMPLATE}` requires `{CONF_CAPTURE_RESPONSE}: true` to be set.",
path=[CONF_RESPONSE_TEMPLATE],
)
if config[CONF_CAPTURE_RESPONSE] and CONF_ON_SUCCESS not in config:
raise cv.Invalid(
f"`{CONF_CAPTURE_RESPONSE}: true` requires `{CONF_ON_SUCCESS}` to be set.",
@@ -771,6 +762,7 @@ HOMEASSISTANT_ACTION_ACTION_SCHEMA = cv.All(
),
cv.has_exactly_one_key(CONF_SERVICE, CONF_ACTION),
cv.rename_key(CONF_SERVICE, CONF_ACTION),
cv.only_when(CONF_RESPONSE_TEMPLATE, CONF_CAPTURE_RESPONSE, True),
_validate_response_config,
)
+1 -5
View File
@@ -119,11 +119,6 @@ def _validate_multiple(conf: ConfigType) -> ConfigType:
"is only for standalone inputs (id)",
path=[CONF_MULTIPLE],
)
if CONF_MAX_LENGTH in conf and not conf[CONF_MULTIPLE]:
raise cv.Invalid(
"max_length only applies to an input with multiple: true",
path=[CONF_MAX_LENGTH],
)
return conf
@@ -150,6 +145,7 @@ WIZARD_INPUT_SCHEMA = cv.All(
),
cv.has_exactly_one_key(CONF_ID, CONF_ENTITY),
_validate_multiple,
cv.only_when(CONF_MAX_LENGTH, CONF_MULTIPLE, True),
)
WIZARD_PAGE_SCHEMA = cv.All(
+7 -11
View File
@@ -17,16 +17,6 @@ DEPENDENCIES = ["sensor"]
AQISensor = aqi_ns.class_("AQISensor", sensor.Sensor, cg.Component)
def _validate_extended_range(config: ConfigType) -> ConfigType:
if CONF_EXTENDED_RANGE in config and config[CONF_CALCULATION_TYPE] == "CAQI":
raise cv.Invalid(
f"'{CONF_EXTENDED_RANGE}' is not supported with 'calculation_type: CAQI'. "
"CAQI has no maximum value by specification, so it is always reported unbounded.",
[CONF_EXTENDED_RANGE],
)
return config
CONFIG_SCHEMA = cv.All(
sensor.sensor_schema(
AQISensor,
@@ -45,7 +35,13 @@ CONFIG_SCHEMA = cv.All(
}
)
.extend(cv.COMPONENT_SCHEMA),
_validate_extended_range,
cv.only_when(
CONF_EXTENDED_RANGE,
CONF_CALCULATION_TYPE,
"CAQI",
negate=True,
hint="CAQI has no maximum by specification, so it is always reported unbounded",
),
)
@@ -9,11 +9,9 @@ ESPHOME_LOG_TAG(TAG, "binary_sensor");
// Function implementation of LOG_BINARY_SENSOR macro to reduce code size
void log_binary_sensor(const char *tag, const char *prefix, const char *type, BinarySensor *obj) {
if (obj == nullptr) {
if (!log_entity_header(tag, prefix, type, obj)) {
return;
}
ESP_LOGCONFIG(tag, "%s%s '%s'", prefix, type, obj->get_name().c_str());
LOG_ENTITY_DEVICE_CLASS(tag, prefix, *obj);
}
+12 -20
View File
@@ -91,23 +91,6 @@ def calculate_energy_reference(power_reference: float) -> float:
return power_reference * 3600000 / (1638.4 * 256)
def validate_legacy_mode(config: ConfigType) -> ConfigType:
# Only allow schematic calibration options if legacy_mode is False
if config.get(CONF_LEGACY_MODE, True):
forbidden = [
CONF_REFERENCE_VOLTAGE,
CONF_RESISTOR_SHUNT,
CONF_RESISTOR_ONE,
CONF_RESISTOR_TWO,
]
for key in forbidden:
if key in config:
raise cv.Invalid(
f"Option '{key}' is only allowed when legacy_mode: false"
)
return config
def set_command_defaults(config: ConfigType) -> ConfigType:
# Set defaults for read_command and write_command based on legacy_mode
legacy = config.get(CONF_LEGACY_MODE, True)
@@ -153,7 +136,7 @@ def set_reference_values(config: ConfigType) -> ConfigType:
return config
CONFIG_SCHEMA = (
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(BL0940),
@@ -208,9 +191,18 @@ CONFIG_SCHEMA = (
)
.extend(cv.polling_component_schema("60s"))
.extend(uart.UART_DEVICE_SCHEMA)
.add_extra(validate_legacy_mode)
.add_extra(set_command_defaults)
.add_extra(set_reference_values)
.add_extra(set_reference_values),
cv.only_when(
(
CONF_REFERENCE_VOLTAGE,
CONF_RESISTOR_SHUNT,
CONF_RESISTOR_ONE,
CONF_RESISTOR_TWO,
),
CONF_LEGACY_MODE,
False,
),
)
# BL0940 datasheet: 4800 baud, 8 data bits, no parity (stop bits are 1.5 -- not
+9 -18
View File
@@ -94,24 +94,14 @@ def _esp32_config_schema() -> cv.All:
CONNECTION_SCHEMA = bluetooth_connection.hub_connection_schema(PLATFORM_ESP32)
def validate_connections(config: ConfigType) -> ConfigType:
if CONF_CONNECTIONS in config:
if not config[CONF_ACTIVE]:
raise cv.Invalid(
"Connections can only be used if the proxy is set to active"
)
elif config[CONF_ACTIVE]:
connection_slots: int = config[CONF_CONNECTION_SLOTS]
esp32_ble.consume_connection_slots(connection_slots, "bluetooth_proxy")(
config
)
return {
**config,
CONF_CONNECTIONS: [
CONNECTION_SCHEMA({}) for _ in range(connection_slots)
],
}
return config
if CONF_CONNECTIONS in config or not config[CONF_ACTIVE]:
return config
connection_slots: int = config[CONF_CONNECTION_SLOTS]
esp32_ble.consume_connection_slots(connection_slots, "bluetooth_proxy")(config)
return {
**config,
CONF_CONNECTIONS: [CONNECTION_SCHEMA({}) for _ in range(connection_slots)],
}
return cv.All(
(
@@ -136,6 +126,7 @@ def _esp32_config_schema() -> cv.All:
.extend(esp32_ble_tracker.ESP_BLE_DEVICE_SCHEMA)
.extend(cv.COMPONENT_SCHEMA)
),
cv.only_when(CONF_CONNECTIONS, CONF_ACTIVE, True),
validate_connections,
)
+12 -14
View File
@@ -139,12 +139,12 @@ void BME680BSECComponent::update_subscription_() {
uint8_t num_sensor_settings = BSEC_MAX_PHYSICAL_SENSOR;
this->bsec_status_ =
bsec_update_subscription(virtual_sensors, num_virtual_sensors, sensor_settings, &num_sensor_settings);
ESP_LOGV(TAG, "%s: updating subscription for %d virtual sensors (out=%d sensors)", this->device_id_.c_str(),
ESP_LOGV(TAG, "%s: updating subscription for %d virtual sensors (out=%d sensors)", this->device_id_,
num_virtual_sensors, num_sensor_settings);
}
void BME680BSECComponent::dump_config() {
ESP_LOGCONFIG(TAG, "%s via BSEC:", this->device_id_.c_str());
ESP_LOGCONFIG(TAG, "%s via BSEC:", this->device_id_);
bsec_version_t version;
bsec_get_version(&version);
@@ -208,7 +208,7 @@ void BME680BSECComponent::run_() {
return;
}
ESP_LOGV(TAG, "%s: Performing sensor run", this->device_id_.c_str());
ESP_LOGV(TAG, "%s: Performing sensor run", this->device_id_);
// Restore BSEC library state
// The reinit_bsec_lib_ method is computationally expensive: it takes 1200÷2900 microseconds on a ESP32.
@@ -265,7 +265,7 @@ void BME680BSECComponent::run_() {
}
void BME680BSECComponent::read_() {
ESP_LOGV(TAG, "%s: Reading data", this->device_id_.c_str());
ESP_LOGV(TAG, "%s: Reading data", this->device_id_);
int64_t curr_time_ns = this->get_time_ns_();
if (this->bme680_settings_.trigger_measurement) {
@@ -365,8 +365,7 @@ void BME680BSECComponent::read_() {
ESP_LOGW(TAG, "BSEC failed to process signals (BSEC Error Code %d)", this->bsec_status_);
return;
}
ESP_LOGV(TAG, "%s: after bsec_do_steps: num_inputs=%d num_outputs=%d", this->device_id_.c_str(), num_inputs,
num_outputs);
ESP_LOGV(TAG, "%s: after bsec_do_steps: num_inputs=%d num_outputs=%d", this->device_id_, num_inputs, num_outputs);
// Since we are about to go "out of scope" in the loop, take a snapshot of the state now so we can restore it later
if (BME680BSECComponent::instances.size() > 1)
@@ -381,7 +380,7 @@ void BME680BSECComponent::read_() {
}
void BME680BSECComponent::publish_(const bsec_output_t *outputs, uint8_t num_outputs) {
ESP_LOGV(TAG, "%s: Queuing sensor state publish actions", this->device_id_.c_str());
ESP_LOGV(TAG, "%s: Queuing sensor state publish actions", this->device_id_);
for (uint8_t i = 0; i < num_outputs; i++) {
float signal = outputs[i].signal;
switch (outputs[i].sensor_id) {
@@ -471,7 +470,7 @@ void BME680BSECComponent::snapshot_state_() {
this->bsec_status_ = bsec_get_state(0, this->bsec_state_data_, BSEC_MAX_STATE_BLOB_SIZE, this->work_buffer_,
sizeof(this->work_buffer_), &num_serialized_state);
if (this->bsec_status_ != BSEC_OK) {
ESP_LOGW(TAG, "%s: Failed to fetch BSEC library state for snapshot (BSEC Error Code %d)", this->device_id_.c_str(),
ESP_LOGW(TAG, "%s: Failed to fetch BSEC library state for snapshot (BSEC Error Code %d)", this->device_id_,
this->bsec_status_);
return;
}
@@ -482,7 +481,7 @@ void BME680BSECComponent::snapshot_state_() {
// Used to share the library when using more than one sensor
void BME680BSECComponent::restore_state_() {
if (!this->bsec_state_data_valid_) {
ESP_LOGV(TAG, "%s: BSEC state data NOT valid, aborting restore_state_()", this->device_id_.c_str());
ESP_LOGV(TAG, "%s: BSEC state data NOT valid, aborting restore_state_()", this->device_id_);
return;
}
@@ -527,17 +526,16 @@ void BME680BSECComponent::load_state_() {
return;
}
ESP_LOGV(TAG, "%s: Loading BSEC library state", this->device_id_.c_str());
ESP_LOGV(TAG, "%s: Loading BSEC library state", this->device_id_);
this->bsec_status_ =
bsec_set_state(this->bsec_state_data_, BSEC_MAX_STATE_BLOB_SIZE, this->work_buffer_, sizeof(this->work_buffer_));
if (this->bsec_status_ != BSEC_OK) {
ESP_LOGW(TAG, "%s: Failed to load BSEC library state (BSEC Error Code %d)", this->device_id_.c_str(),
this->bsec_status_);
ESP_LOGW(TAG, "%s: Failed to load BSEC library state (BSEC Error Code %d)", this->device_id_, this->bsec_status_);
return;
}
// All OK: set the BSEC state data as valid
this->bsec_state_data_valid_ = true;
ESP_LOGI(TAG, "%s: Loaded BSEC library state", this->device_id_.c_str());
ESP_LOGI(TAG, "%s: Loaded BSEC library state", this->device_id_);
}
void BME680BSECComponent::save_state_(uint8_t accuracy) {
@@ -552,7 +550,7 @@ void BME680BSECComponent::save_state_(uint8_t accuracy) {
if (!this->bsec_state_data_valid_)
return;
ESP_LOGV(TAG, "%s: Saving state", this->device_id_.c_str());
ESP_LOGV(TAG, "%s: Saving state", this->device_id_);
if (!this->bsec_state_.save(&this->bsec_state_data_)) {
ESP_LOGW(TAG, "Failed to save state");
+2 -2
View File
@@ -36,7 +36,7 @@ enum SampleRate {
class BME680BSECComponent final : public Component, public i2c::I2CDevice {
public:
void set_device_id(const std::string &devid) { this->device_id_.assign(devid); }
void set_device_id(const char *devid) { this->device_id_ = devid; }
void set_temperature_offset(float offset) { this->temperature_offset_ = offset; }
void set_iaq_mode(IAQMode iaq_mode) { this->iaq_mode_ = iaq_mode; }
void set_state_save_interval(uint32_t interval) { this->state_save_interval_ms_ = interval; }
@@ -111,7 +111,7 @@ class BME680BSECComponent final : public Component, public i2c::I2CDevice {
uint32_t last_state_save_ms_ = 0;
bsec_bme_settings_t bme680_settings_;
std::string device_id_;
const char *device_id_{nullptr};
float temperature_offset_{0};
IAQMode iaq_mode_{IAQ_MODE_STATIC};
SupplyVoltage supply_voltage_;
+1 -3
View File
@@ -7,11 +7,9 @@ ESPHOME_LOG_TAG(TAG, "button");
// Function implementation of LOG_BUTTON macro to reduce code size
void log_button(const char *tag, const char *prefix, const char *type, Button *obj) {
if (obj == nullptr) {
if (!log_entity_header(tag, prefix, type, obj)) {
return;
}
ESP_LOGCONFIG(tag, "%s%s '%s'", prefix, type, obj->get_name().c_str());
LOG_ENTITY_ICON(tag, prefix, *obj);
}
+1 -4
View File
@@ -12,10 +12,7 @@
namespace esphome::climate {
#define LOG_CLIMATE(prefix, type, obj) \
if ((obj) != nullptr) { \
ESP_LOGCONFIG(TAG, "%s%s '%s'", prefix, LOG_STR_LITERAL(type), (obj)->get_name().c_str()); \
}
#define LOG_CLIMATE(prefix, type, obj) log_entity_header(TAG, prefix, LOG_STR_LITERAL(type), (obj))
class Climate;
+3
View File
@@ -11,6 +11,7 @@ CONF_ACCELEROMETER_RANGE = "accelerometer_range"
CONF_ADC_AVERAGING = "adc_averaging"
CONF_ADC_TIME = "adc_time"
CONF_ALLOWED_IPS = "allowed_ips"
CONF_ANNOUNCEMENT_VOLUME = "announcement_volume"
CONF_AQI = "aqi"
CONF_AUTOMATIC_BASELINE_CALIBRATION = "automatic_baseline_calibration"
CONF_B_CONSTANT = "b_constant"
@@ -33,6 +34,7 @@ CONF_DRAW_ROUNDING = "draw_rounding"
CONF_DRIVE_STRENGTH = "drive_strength"
CONF_ENABLE_OTA_DOWNGRADE_PROTECTION = "enable_ota_downgrade_protection"
CONF_ENABLED = "enabled"
CONF_ERROR_CODE = "error_code"
CONF_GREEN_CHANNEL = "green_channel"
CONF_GYROSCOPE_ODR = "gyroscope_odr"
CONF_GYROSCOPE_RANGE = "gyroscope_range"
@@ -48,6 +50,7 @@ CONF_LIBRETINY = "libretiny"
CONF_LOOP = "loop"
CONF_MANUFACTURER = "manufacturer"
CONF_MAX_PACKET_SIZE = "max_packet_size"
CONF_MODULATION = "modulation"
CONF_NOX_INDEX = "nox_index"
CONF_ON_PACKET = "on_packet"
CONF_ON_RECEIVE = "on_receive"
+1 -2
View File
@@ -14,8 +14,7 @@ static constexpr float COVER_OPEN = 1.0f;
static constexpr float COVER_CLOSED = 0.0f;
#define LOG_COVER(prefix, type, obj) \
if ((obj) != nullptr) { \
ESP_LOGCONFIG(TAG, "%s%s '%s'", prefix, LOG_STR_LITERAL(type), (obj)->get_name().c_str()); \
if (log_entity_header(TAG, prefix, LOG_STR_LITERAL(type), (obj))) { \
auto traits_ = (obj)->get_traits(); \
if (traits_.get_is_assumed_state()) { \
ESP_LOGCONFIG(TAG, "%s Assumed State: YES", prefix); \
+1 -2
View File
@@ -13,8 +13,7 @@
namespace esphome::datetime {
#define LOG_DATETIME_DATE(prefix, type, obj) \
if ((obj) != nullptr) { \
ESP_LOGCONFIG(TAG, "%s%s '%s'", prefix, LOG_STR_LITERAL(type), (obj)->get_name().c_str()); \
if (log_entity_header(TAG, prefix, LOG_STR_LITERAL(type), (obj))) { \
LOG_ENTITY_ICON(TAG, prefix, *(obj)); \
}
@@ -13,8 +13,7 @@
namespace esphome::datetime {
#define LOG_DATETIME_DATETIME(prefix, type, obj) \
if ((obj) != nullptr) { \
ESP_LOGCONFIG(TAG, "%s%s '%s'", prefix, LOG_STR_LITERAL(type), (obj)->get_name().c_str()); \
if (log_entity_header(TAG, prefix, LOG_STR_LITERAL(type), (obj))) { \
LOG_ENTITY_ICON(TAG, prefix, *(obj)); \
}
+1 -2
View File
@@ -13,8 +13,7 @@
namespace esphome::datetime {
#define LOG_DATETIME_TIME(prefix, type, obj) \
if ((obj) != nullptr) { \
ESP_LOGCONFIG(TAG, "%s%s '%s'", prefix, LOG_STR_LITERAL(type), (obj)->get_name().c_str()); \
if (log_entity_header(TAG, prefix, LOG_STR_LITERAL(type), (obj))) { \
LOG_ENTITY_ICON(TAG, prefix, *(obj)); \
}
+1 -4
View File
@@ -164,10 +164,6 @@ _WAKEUP_PIN_MODE_BOTH_LEVELS = (
def validate_config(config: ConfigType) -> ConfigType:
wakeup_pins = config.get(CONF_WAKEUP_PIN)
has_pin_mode = CONF_WAKEUP_PIN_MODE in config
if has_pin_mode and wakeup_pins is None:
raise cv.Invalid(
"'wakeup_pin_mode' requires 'wakeup_pin'", path=[CONF_WAKEUP_PIN_MODE]
)
multiple_pins = wakeup_pins is not None and len(wakeup_pins) > 1
# wakeup_pin is limited to ESP32 and BK72XX, and only BK72XX accepts a list
if not CORE.is_bk72xx:
@@ -356,6 +352,7 @@ CONFIG_SCHEMA = cv.All(
}
).extend(cv.COMPONENT_SCHEMA),
cv.only_on([PLATFORM_ESP32, PLATFORM_ESP8266, PLATFORM_BK72XX, PLATFORM_NRF52]),
cv.key_requires(CONF_WAKEUP_PIN_MODE, CONF_WAKEUP_PIN),
validate_config,
)
@@ -82,7 +82,7 @@ std::string MenuItemNumber::get_value_text() const {
result = this->value_getter_.value()(this);
} else {
char data[32];
snprintf(data, sizeof(data), this->format_.c_str(), get_number_value_());
snprintf(data, sizeof(data), this->format_, get_number_value_());
result = data;
}
@@ -118,7 +118,8 @@ class MenuItemNumber final : public MenuItemEditable {
public:
explicit MenuItemNumber() : MenuItemEditable(MENU_ITEM_NUMBER) {}
void set_number_variable(number::Number *var) { this->number_var_ = var; }
void set_format(const std::string &fmt) { this->format_ = fmt; }
// Keeps the pointer; the string must outlive the item (codegen passes a literal)
void set_format(const char *fmt) { this->format_ = fmt; }
bool has_value() const override { return true; }
std::string get_value_text() const override;
@@ -130,7 +131,7 @@ class MenuItemNumber final : public MenuItemEditable {
float get_number_value_() const;
number::Number *number_var_{nullptr};
std::string format_;
const char *format_{""};
};
#endif
@@ -139,8 +140,9 @@ class MenuItemSwitch final : public MenuItemEditable {
public:
explicit MenuItemSwitch() : MenuItemEditable(MENU_ITEM_SWITCH) {}
void set_switch_variable(switch_::Switch *var) { this->switch_var_ = var; }
void set_on_text(const std::string &t) { this->switch_on_text_ = t; }
void set_off_text(const std::string &t) { this->switch_off_text_ = t; }
// Both keep the pointer; the strings must outlive the item (codegen passes literals)
void set_on_text(const char *t) { this->switch_on_text_ = t; }
void set_off_text(const char *t) { this->switch_off_text_ = t; }
bool has_value() const override { return true; }
std::string get_value_text() const override;
@@ -153,8 +155,8 @@ class MenuItemSwitch final : public MenuItemEditable {
bool toggle_switch_();
switch_::Switch *switch_var_{nullptr};
std::string switch_on_text_;
std::string switch_off_text_;
const char *switch_on_text_{""};
const char *switch_off_text_{""};
};
#endif
+37
View File
@@ -1,2 +1,39 @@
from collections.abc import Iterable
from dataclasses import dataclass, field
from pathlib import Path
from esphome.core import CORE
CODEOWNERS = ["@esphome/core"]
DOMAIN = "epaper_spi"
# The source file that every model needs.
BASE_SOURCE_FILE = "epaper_spi.cpp"
@dataclass
class EpaperSpiData:
needed_sources: set[str] = field(default_factory=set)
def _get_data() -> EpaperSpiData:
if DOMAIN not in CORE.data:
CORE.data[DOMAIN] = EpaperSpiData()
return CORE.data[DOMAIN]
def register_sources(sources: Iterable[str]) -> None:
"""Record the source files that a configured model's C++ driver class needs."""
_get_data().needed_sources.update(sources)
def FILTER_SOURCE_FILES() -> list[str]: # noqa: N802
"""Exclude the driver sources that no configured model needs."""
if not (needed := _get_data().needed_sources):
return []
keep = needed | {BASE_SOURCE_FILE}
return sorted(
path.name
for path in Path(__file__).parent.glob("*.cpp")
if path.name not in keep
)
+6 -1
View File
@@ -42,7 +42,11 @@ from esphome.const import (
)
from esphome.cpp_generator import RawExpression
from . import models
from . import ( # pylint: disable=unused-import
FILTER_SOURCE_FILES, # noqa: F401
models,
register_sources,
)
AUTO_LOAD = ["split_buffer"]
DEPENDENCIES = ["spi"]
@@ -219,6 +223,7 @@ FINAL_VALIDATE_SCHEMA = _final_validate
async def to_code(config):
model = MODELS[config[CONF_MODEL]]
register_sources(model.source_files)
init_sequence = config.get(CONF_INIT_SEQUENCE)
if init_sequence is None:
@@ -18,17 +18,24 @@ class EpaperModel:
# Whether the driver manages chip-select itself instead of via the SPI bus.
manages_cs: bool = False
# The .cpp files this model's driver class needs: its own and those of every parent class
# except epaper_spi.cpp, which is always built. Subclasses override this next to their class_name.
source_files: tuple[str, ...] = ()
def __init__(
self,
name: str,
class_name: str,
initsequence=(),
source_files: tuple[str, ...] | None = None,
**defaults,
):
name = name.upper()
self.name = name
self.class_name = class_name
self.initsequence = initsequence
if source_files is not None:
self.source_files = source_files
self.defaults = defaults
EpaperModel.models[name] = self
@@ -112,7 +119,13 @@ class EpaperModel:
initsequence.extend(kwargs.pop("add_init_sequence", ()))
defaults = self.defaults.copy()
defaults.update(kwargs)
return self.__class__(name, initsequence=tuple(initsequence), **defaults)
model = self.__class__(name, initsequence=tuple(initsequence), **defaults)
# Subclass constructors do not all take these, so carry them over unless overridden
if "class_name" not in kwargs:
model.class_name = self.class_name
if "source_files" not in kwargs:
model.source_files = self.source_files
return model
def check_requirements(self) -> None:
"""
@@ -4,6 +4,8 @@ from . import EpaperModel
class Inkplate2Model(EpaperModel):
source_files = ("epaper_spi_inkplate2.cpp",)
def __init__(self, name, class_name="EPaperInkplate2", **kwargs):
super().__init__(name, class_name, **kwargs)
@@ -6,6 +6,11 @@ from . import EpaperModel
class Inkplate6ColorModel(EpaperModel):
source_files = (
"epaper_spi_4bpp.cpp",
"epaper_spi_inkplate6color.cpp",
)
def __init__(self, name, class_name="EPaperInkplate6Color", **kwargs):
super().__init__(name, class_name, **kwargs)
@@ -9,6 +9,8 @@ from . import EpaperModel
class JD79660(EpaperModel):
source_files = ("epaper_spi_jd79660.cpp",)
def __init__(self, name, class_name="EPaperJD79660", fast_update=None, **kwargs):
# Only a fast_update sequence lets the driver do anything but a full refresh
kwargs.setdefault("partial_update", fast_update is not None)
@@ -4,6 +4,11 @@ from . import EpaperModel
class SpectraE6(EpaperModel):
source_files = (
"epaper_spi_4bpp.cpp",
"epaper_spi_spectra_e6.cpp",
)
def __init__(self, name, class_name="EPaperSpectraE6", **defaults):
super().__init__(name, class_name, **defaults)
@@ -14,6 +14,11 @@ MONOCHROME = "monochrome"
class SSD1677(EpaperModel):
source_files = (
"epaper_spi_mono.cpp",
"epaper_spi_ssd1677.cpp",
)
def __init__(
self,
name: str,
@@ -116,6 +121,11 @@ seeed_sticky = ssd1677.extend(
seeed_sticky.extend(
"seeed-reterminal-sticky-gray4",
class_name="EPaperSSD1677Gray4",
source_files=(
"epaper_spi_mono.cpp",
"epaper_spi_ssd1677.cpp",
"epaper_spi_ssd1677_gray4.cpp",
),
border_waveform=0x00,
partial_update=MONOCHROME,
# each plane byte is built from two whole buffer bytes
@@ -4,6 +4,11 @@ from . import EpaperModel
class SSD1683(EpaperModel):
source_files = (
"epaper_spi_mono.cpp",
"epaper_spi_ssd1683.cpp",
)
def __init__(self, name, class_name="EPaperSSD1683", data_rate="20MHz", **defaults):
defaults[CONF_DATA_RATE] = data_rate
defaults.setdefault("partial_update", True)
@@ -22,6 +22,8 @@ CONF_CS1_PIN = "cs1_pin"
class T133A01Model(EpaperModel):
"""EpaperModel subclass for T133A01-based 6-color e-paper displays."""
source_files = ("epaper_spi_t133a01.cpp",)
# The driver drives CS and CS1 directly for the dual-CS protocol.
manages_cs = True
@@ -22,6 +22,8 @@ MAX_GATES = 296
class UC8151(EpaperModel):
"""EpaperModel class for black/white/red displays using the UC8151D controller."""
source_files = ("epaper_waveshare_bwr.cpp",)
def __init__(self, name: str, **defaults: Any) -> None:
super().__init__(name, "EPaperWaveshareBWR", **defaults)
@@ -24,6 +24,11 @@ from . import EpaperModel, ultrachip_resolution
class UC8179(EpaperModel):
"""EpaperModel class for monochrome displays using the UC8179 controller."""
source_files = (
"epaper_spi_ultrachip.cpp",
"epaper_spi_uc8179.cpp",
)
def __init__(
self,
name: str,
@@ -19,6 +19,11 @@ from . import EpaperModel, ultrachip_resolution
class UC8279(EpaperModel):
source_files = (
"epaper_spi_ultrachip.cpp",
"epaper_spi_uc8279.cpp",
)
def __init__(
self,
name: str,
@@ -11,6 +11,11 @@ from . import EpaperModel
class WaveshareModel(EpaperModel):
source_files = (
"epaper_spi_mono.cpp",
"epaper_waveshare.cpp",
)
def __init__(
self,
name: str,
@@ -2,6 +2,11 @@ from . import EpaperModel
class WaveshareB(EpaperModel):
source_files = (
"epaper_waveshare_b.cpp",
"epaper_weact_3c.cpp",
)
def __init__(self, name, **defaults):
super().__init__(name, "EpaperWaveshareB", **defaults)
@@ -14,6 +14,8 @@ from . import EpaperModel
class WaveshareBWR(EpaperModel):
"""EpaperModel class for Waveshare Black/White/Red displays using UC8179 controller."""
source_files = ("epaper_waveshare_bwr.cpp",)
def __init__(self, name, **defaults):
super().__init__(name, "EPaperWaveshareBWR", **defaults)
@@ -15,6 +15,8 @@ from . import EpaperModel
class WeActBWR(EpaperModel):
"""Base EpaperModel class for WeAct Black/White/Red displays using SSD1683 controller."""
source_files = ("epaper_weact_3c.cpp",)
def __init__(self, name, **defaults):
super().__init__(name, "EPaperWeAct3C", **defaults)
@@ -183,10 +183,6 @@ def validate_char_on_write(char_config):
def validate_descriptor(desc_config):
if CONF_ON_WRITE in desc_config and not desc_config[CONF_WRITE]:
raise cv.Invalid(
f"{CONF_ON_WRITE} requires the {CONF_WRITE} property to be set"
)
if CONF_MAX_LENGTH not in desc_config:
value = desc_config[CONF_VALUE][CONF_DATA]
if cg.is_template(value):
@@ -436,6 +432,7 @@ DESCRIPTOR_SCHEMA = cv.All(
cv.Required(CONF_VALUE): value_schema(templatable=False),
cv.Optional(CONF_MAX_LENGTH): cv.uint16_t,
},
cv.only_when(CONF_ON_WRITE, CONF_WRITE, True),
validate_descriptor,
)
+1 -2
View File
@@ -15,8 +15,7 @@ namespace esphome::event {
using EventTypes = ConstVector<const char *, true>;
#define LOG_EVENT(prefix, type, obj) \
if ((obj) != nullptr) { \
ESP_LOGCONFIG(TAG, "%s%s '%s'", prefix, LOG_STR_LITERAL(type), (obj)->get_name().c_str()); \
if (log_entity_header(TAG, prefix, LOG_STR_LITERAL(type), (obj))) { \
LOG_ENTITY_ICON(TAG, prefix, *(obj)); \
LOG_ENTITY_DEVICE_CLASS(TAG, prefix, *(obj)); \
}
@@ -37,15 +37,6 @@ def inherit_accuracy_decimals(decimals: int, config: ConfigType) -> int:
return decimals + 1
def validate_time_weighting(config: ConfigType) -> ConfigType:
if CONF_TIME_WEIGHTING in config and CONF_TIME_CONSTANT not in config:
raise cv.Invalid(
f"'{CONF_TIME_WEIGHTING}' can only be used with '{CONF_TIME_CONSTANT}'",
path=[CONF_TIME_WEIGHTING],
)
return config
CONFIG_SCHEMA = cv.All(
sensor.sensor_schema(ExponentialMovingAverageSensor)
.extend(
@@ -61,7 +52,7 @@ CONFIG_SCHEMA = cv.All(
)
.extend(cv.COMPONENT_SCHEMA),
cv.has_at_most_one_key(CONF_ALPHA, CONF_TIME_CONSTANT),
validate_time_weighting,
cv.key_requires(CONF_TIME_WEIGHTING, CONF_TIME_CONSTANT),
)
FINAL_VALIDATE_SCHEMA = cv.All(
+1 -2
View File
@@ -11,8 +11,7 @@
namespace esphome::fan {
#define LOG_FAN(prefix, type, obj) \
if ((obj) != nullptr) { \
ESP_LOGCONFIG(TAG, "%s%s '%s'", prefix, LOG_STR_LITERAL(type), (obj)->get_name().c_str()); \
if (log_entity_header(TAG, prefix, LOG_STR_LITERAL(type), (obj))) { \
(obj)->dump_traits_(TAG, prefix); \
}
@@ -42,12 +42,6 @@ CHIPSETS = [
]
def _validate(value: ConfigType) -> ConfigType:
if value[CONF_CHIPSET] == "NEOPIXEL" and CONF_RGB_ORDER in value:
raise cv.Invalid("NEOPIXEL doesn't support RGB order")
return value
CONFIG_SCHEMA = cv.All(
fastled_base.BASE_SCHEMA.extend(
{
@@ -70,7 +64,7 @@ CONFIG_SCHEMA = cv.All(
max_version=True,
extra_message="Please see note on documentation for FastLED",
),
_validate,
cv.only_when(CONF_RGB_ORDER, CONF_CHIPSET, "NEOPIXEL", negate=True),
)
+40 -16
View File
@@ -612,7 +612,14 @@ class GlyphInfo:
self.height = height
def glyph_to_glyphinfo(glyph, font, size, bpp):
def glyph_to_glyphinfo(glyph, font, size, bpp, crop: bool = True):
"""Render a glyph and pack its bitmap at the given bits per pixel.
With ``crop``, blank rows and columns around the set pixels are dropped and the
offsets adjusted to match. Bitmap fonts (BDF/PCF) render every glyph as a whole
character cell, so this keeps their empty space out of flash. A blank glyph keeps
its offsets and stores no pixels.
"""
# Convert to 32 bit unicode codepoint
glyph = ord(glyph)
scale = 256 // (1 << bpp)
@@ -632,19 +639,36 @@ def glyph_to_glyphinfo(glyph, font, size, bpp):
height = font.glyph.bitmap.rows
buffer = font.glyph.bitmap.buffer
pitch = font.glyph.bitmap.pitch
glyph_data = [0] * ((height * width * bpp + 7) // 8)
src_mode = font.glyph.bitmap.pixel_mode
if src_mode == ft_pixel_mode_mono:
rows = [
[
(1 << bpp) - 1 if buffer[y * pitch + x // 8] & (1 << (7 - x % 8)) else 0
for x in range(width)
]
for y in range(height)
]
else:
rows = [
[buffer[y * pitch + x] // scale for x in range(width)]
for y in range(height)
]
left = 0
top = 0
if crop and width * height > 1:
used_rows = [y for y, row in enumerate(rows) if any(row)]
used_cols = [x for x in range(width) if any(row[x] for row in rows)]
if used_rows:
left = used_cols[0]
top = used_rows[0]
width = used_cols[-1] + 1 - left
height = used_rows[-1] + 1 - top
else:
width = height = 0
glyph_data = [0] * ((height * width * bpp + 7) // 8)
pos = 0
for y in range(height):
for x in range(width):
if src_mode == ft_pixel_mode_mono:
pixel = (
(1 << bpp) - 1
if buffer[y * pitch + x // 8] & (1 << (7 - x % 8))
else 0
)
else:
pixel = buffer[y * pitch + x] // scale
for row in rows[top : top + height]:
for pixel in row[left : left + width]:
for bit_num in range(bpp):
if pixel & (1 << (bpp - bit_num - 1)):
glyph_data[pos // 8] |= 0x80 >> (pos % 8)
@@ -663,8 +687,8 @@ def glyph_to_glyphinfo(glyph, font, size, bpp):
glyph,
glyph_data,
pt_to_px(font.glyph.metrics.horiAdvance),
font.glyph.bitmap_left,
ascender - font.glyph.bitmap_top,
font.glyph.bitmap_left + left,
ascender - font.glyph.bitmap_top + top,
width,
height,
)
@@ -733,9 +757,9 @@ async def to_code(config):
font_height = pt_to_px(base_font.size.height)
ascender = pt_to_px(base_font.size.ascender)
descender = abs(pt_to_px(base_font.size.descender))
g = glyph_to_glyphinfo("x", base_font, size, bpp)
g = glyph_to_glyphinfo("x", base_font, size, bpp, crop=False)
xheight = g.height if len(g.bitmap_data) > 1 else 0
g = glyph_to_glyphinfo("X", base_font, size, bpp)
g = glyph_to_glyphinfo("X", base_font, size, bpp, crop=False)
capheight = g.height if len(g.bitmap_data) > 1 else 0
if font_height == 0:
if not base_font.is_scalable:
+8 -8
View File
@@ -47,7 +47,7 @@ void HistoryData::take_sample(float data) {
}
void GraphTrace::init(Graph *g) {
ESP_LOGI(TAG, "Init trace for sensor %s", this->get_name().c_str());
ESP_LOGI(TAG, "Init trace for sensor %s", this->name_);
this->data_.init(g->get_width());
sensor_->add_on_state_callback([this](float state) { this->data_.take_sample(state); });
this->data_.set_update_time_ms(g->get_duration() * 1000 / g->get_width());
@@ -220,16 +220,16 @@ void GraphLegend::init(Graph *g) {
int valw = 0, valh = 0;
int lt = 0;
for (auto *trace : g->traces_) {
std::string txtstr = trace->get_name();
const char *txtstr = trace->name_;
int fw, fos, fbl, fh;
this->font_label_->measure(txtstr.c_str(), &fw, &fos, &fbl, &fh);
this->font_label_->measure(txtstr, &fw, &fos, &fbl, &fh);
if (fw > txtw)
txtw = fw;
if (fh > txth)
txth = fh;
if (trace->get_line_thickness() > lt)
lt = trace->get_line_thickness();
ESP_LOGI(TAGL, " %s %d %d", txtstr.c_str(), fw, fh);
ESP_LOGI(TAGL, " %s %d %d", txtstr, fw, fh);
if (this->values_ != VALUE_POSITION_TYPE_NONE) {
char valstr[VALUE_ACCURACY_MAX_LEN];
@@ -351,10 +351,10 @@ void Graph::draw_legend(display::Display *buff, uint16_t x_offset, uint16_t y_of
int x = x_offset + legend_->x0_;
int y = y_offset;
for (auto *trace : traces_) {
std::string txtstr = trace->get_name();
ESP_LOGV(TAG, " %s", txtstr.c_str());
const char *txtstr = trace->name_;
ESP_LOGV(TAG, " %s", txtstr);
buff->printf(x, y, legend_->font_label_, trace->get_line_color(), TextAlign::TOP_CENTER, "%s", txtstr.c_str());
buff->printf(x, y, legend_->font_label_, trace->get_line_color(), TextAlign::TOP_CENTER, "%s", txtstr);
if (legend_->lines_) {
uint16_t thick = trace->get_line_thickness();
@@ -393,7 +393,7 @@ void Graph::setup() {
void Graph::dump_config() {
for (auto *trace : traces_) {
ESP_LOGCONFIG(TAG, "Graph for sensor %s", trace->get_name().c_str());
ESP_LOGCONFIG(TAG, "Graph for sensor %s", trace->name_);
}
}
+4 -4
View File
@@ -1,9 +1,9 @@
#pragma once
#include <cstdint>
#include <utility>
#include <vector>
#include "esphome/components/sensor/sensor.h"
#include "esphome/core/color.h"
#include "esphome/core/string_ref.h"
#include "esphome/core/component.h"
namespace esphome {
@@ -108,7 +108,7 @@ class HistoryData {
class GraphTrace final {
public:
void init(Graph *g);
void set_name(std::string name) { name_ = std::move(name); }
void set_name(const char *name) { this->name_ = name; }
void set_sensor(sensor::Sensor *sensor) { sensor_ = sensor; }
uint8_t get_line_thickness() { return this->line_thickness_; }
void set_line_thickness(uint8_t val) { this->line_thickness_ = val; }
@@ -118,12 +118,12 @@ class GraphTrace final {
void set_line_color(Color val) { this->line_color_ = val; }
bool get_continuous() { return this->continuous_; }
void set_continuous(bool continuous) { this->continuous_ = continuous; }
std::string get_name() { return name_; }
StringRef get_name() const { return StringRef(this->name_); }
const HistoryData *get_tracedata() { return &data_; }
protected:
sensor::Sensor *sensor_{nullptr};
std::string name_;
const char *name_{""};
uint8_t line_thickness_{3};
enum LineType line_type_ { LINE_TYPE_SOLID };
Color line_color_{COLOR_ON};
+11 -8
View File
@@ -12,9 +12,12 @@ void GreeClimate::set_model(Model model) {
this->swing_modes_.erase(climate::CLIMATE_SWING_BOTH);
}
if (model == GREE_YX1FF) {
this->fan_modes_.insert(climate::CLIMATE_FAN_QUIET); // YX1FF 4 speed
this->presets_.insert(climate::CLIMATE_PRESET_NONE); // YX1FF sleep mode
this->presets_.insert(climate::CLIMATE_PRESET_SLEEP); // YX1FF sleep mode
this->fan_modes_.insert(climate::CLIMATE_FAN_QUIET); // YX1FF 4 speed
}
// Models with a sleep preset
if (model == GREE_YX1FF || model == GREE_YAC1FB9) {
this->presets_.insert(climate::CLIMATE_PRESET_NONE);
this->presets_.insert(climate::CLIMATE_PRESET_SLEEP);
}
this->model_ = model;
@@ -80,10 +83,10 @@ void GreeClimate::transmit_state() {
if (this->fan_speed_() == GREE_FAN_TURBO) {
remote_state[2] |= GREE_FAN_TURBO_BIT;
}
}
if (this->preset_() == GREE_PRESET_SLEEP) {
remote_state[0] |= GREE_PRESET_SLEEP_BIT;
}
if (this->preset_() == GREE_PRESET_SLEEP) {
remote_state[0] |= GREE_PRESET_SLEEP_BIT;
}
// Calculate the checksum
@@ -228,8 +231,8 @@ uint8_t GreeClimate::temperature_() {
}
uint8_t GreeClimate::preset_() {
// YX1FF has sleep preset
if (this->model_ == GREE_YX1FF) {
// YX1FF and YAC1FB9 have sleep preset
if (this->model_ == GREE_YX1FF || this->model_ == GREE_YAC1FB9) {
switch (this->preset.value_or(climate::CLIMATE_PRESET_NONE)) {
case climate::CLIMATE_PRESET_NONE:
return GREE_PRESET_NONE;
+4 -1
View File
@@ -69,9 +69,12 @@ static constexpr uint8_t GREE_HDIR_MRIGHT = 0x05;
static constexpr uint8_t GREE_HDIR_RIGHT = 0x06;
// Only available on YX1FF
// Turbo (high) fan mode + sleep preset mode
// Turbo (high) fan mode
static constexpr uint8_t GREE_FAN_TURBO = 0x80;
static constexpr uint8_t GREE_FAN_TURBO_BIT = 0x10;
// Available on YX1FF and YAC1FB9
// Sleep preset mode
static constexpr uint8_t GREE_PRESET_NONE = 0x00;
static constexpr uint8_t GREE_PRESET_SLEEP = 0x01;
static constexpr uint8_t GREE_PRESET_SLEEP_BIT = 0x80;
+34 -23
View File
@@ -3,20 +3,11 @@ from esphome.components import switch
import esphome.config_validation as cv
from esphome.const import CONF_BEEPER, CONF_DISPLAY, ENTITY_CATEGORY_CONFIG
import esphome.final_validate as fv
from esphome.types import ConfigType
from ..climate import (
CONF_HAIER_ID,
CONF_PROTOCOL,
PROTOCOL_HON,
HaierClimateBase,
haier_ns,
)
from ..climate import CONF_HAIER_ID, CONF_PROTOCOL, PROTOCOL_HON, HaierClimateBase
CODEOWNERS = ["@paveldn"]
BeeperSwitch = haier_ns.class_("BeeperSwitch", switch.Switch)
HealthModeSwitch = haier_ns.class_("HealthModeSwitch", switch.Switch)
DisplaySwitch = haier_ns.class_("DisplaySwitch", switch.Switch)
QuietModeSwitch = haier_ns.class_("QuietModeSwitch", switch.Switch)
# Haier switches
CONF_HEALTH_MODE = "health_mode"
@@ -32,26 +23,26 @@ CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(CONF_HAIER_ID): cv.use_id(HaierClimateBase),
cv.Optional(CONF_DISPLAY): switch.switch_schema(
DisplaySwitch,
switch.ApplySwitch,
icon=ICON_LED_ON,
entity_category=ENTITY_CATEGORY_CONFIG,
default_restore_mode="DISABLED",
),
cv.Optional(CONF_HEALTH_MODE): switch.switch_schema(
HealthModeSwitch,
switch.ApplySwitch,
icon=ICON_LEAF,
default_restore_mode="DISABLED",
),
# Beeper switch is only supported for HonClimate
cv.Optional(CONF_BEEPER): switch.switch_schema(
BeeperSwitch,
switch.ApplySwitch,
icon=ICON_VOLUME_HIGH,
entity_category=ENTITY_CATEGORY_CONFIG,
default_restore_mode="DISABLED",
),
# Quiet mode is only supported for HonClimate
cv.Optional(CONF_QUIET_MODE): switch.switch_schema(
QuietModeSwitch,
switch.ApplySwitch,
icon=ICON_VOLUME_OFF,
entity_category=ENTITY_CATEGORY_CONFIG,
default_restore_mode="DISABLED",
@@ -77,11 +68,31 @@ def _final_validate(config) -> None:
FINAL_VALIDATE_SCHEMA = _final_validate
async def to_code(config):
parent = await cg.get_variable(config[CONF_HAIER_ID])
for switch_type in [CONF_DISPLAY, CONF_HEALTH_MODE, CONF_BEEPER, CONF_QUIET_MODE]:
if conf := config.get(switch_type):
sw_var = await switch.new_switch(conf)
await cg.register_parented(sw_var, parent)
cg.add(getattr(parent, f"set_{switch_type}_switch")(sw_var))
async def to_code(config: ConfigType) -> None:
hub = await cg.get_variable(config[CONF_HAIER_ID])
switches = switch.sub_switches(config, parent=hub)
# The setters skip an unchanged value; the switch reports the state either way
await switches(
CONF_DISPLAY,
hub.set_display_switch,
apply="set_display_state(state)",
publish="after",
)
await switches(
CONF_HEALTH_MODE,
hub.set_health_mode_switch,
apply="set_health_mode(state)",
publish="after",
)
await switches(
CONF_BEEPER,
hub.set_beeper_switch,
apply="set_beeper_state(state)",
publish="after",
)
await switches(
CONF_QUIET_MODE,
hub.set_quiet_mode_switch,
apply="set_quiet_mode_state(state)",
publish="after",
)
@@ -1,12 +0,0 @@
#include "beeper.h"
namespace esphome::haier {
void BeeperSwitch::write_state(bool state) {
if (this->parent_->get_beeper_state() != state) {
this->parent_->set_beeper_state(state);
}
this->publish_state(state);
}
} // namespace esphome::haier
-16
View File
@@ -1,16 +0,0 @@
#pragma once
#include "esphome/components/switch/switch.h"
#include "../hon_climate.h"
namespace esphome::haier {
class BeeperSwitch final : public switch_::Switch, public Parented<HonClimate> {
public:
BeeperSwitch() = default;
protected:
void write_state(bool state) override;
};
} // namespace esphome::haier
@@ -1,12 +0,0 @@
#include "display.h"
namespace esphome::haier {
void DisplaySwitch::write_state(bool state) {
if (this->parent_->get_display_state() != state) {
this->parent_->set_display_state(state);
}
this->publish_state(state);
}
} // namespace esphome::haier
-16
View File
@@ -1,16 +0,0 @@
#pragma once
#include "esphome/components/switch/switch.h"
#include "../haier_base.h"
namespace esphome::haier {
class DisplaySwitch final : public switch_::Switch, public Parented<HaierClimateBase> {
public:
DisplaySwitch() = default;
protected:
void write_state(bool state) override;
};
} // namespace esphome::haier
@@ -1,12 +0,0 @@
#include "health_mode.h"
namespace esphome::haier {
void HealthModeSwitch::write_state(bool state) {
if (this->parent_->get_health_mode() != state) {
this->parent_->set_health_mode(state);
}
this->publish_state(state);
}
} // namespace esphome::haier
@@ -1,16 +0,0 @@
#pragma once
#include "esphome/components/switch/switch.h"
#include "../haier_base.h"
namespace esphome::haier {
class HealthModeSwitch final : public switch_::Switch, public Parented<HaierClimateBase> {
public:
HealthModeSwitch() = default;
protected:
void write_state(bool state) override;
};
} // namespace esphome::haier
@@ -1,12 +0,0 @@
#include "quiet_mode.h"
namespace esphome::haier {
void QuietModeSwitch::write_state(bool state) {
if (this->parent_->get_quiet_mode_state() != state) {
this->parent_->set_quiet_mode_state(state);
}
this->publish_state(state);
}
} // namespace esphome::haier
@@ -1,16 +0,0 @@
#pragma once
#include "esphome/components/switch/switch.h"
#include "../hon_climate.h"
namespace esphome::haier {
class QuietModeSwitch final : public switch_::Switch, public Parented<HonClimate> {
public:
QuietModeSwitch() = default;
protected:
void write_state(bool state) override;
};
} // namespace esphome::haier
+1 -7
View File
@@ -69,12 +69,6 @@ MODELS = InkplateModel.options(
CONF_CUSTOM_WAVEFORM = "custom_waveform"
def _validate_custom_waveform(config: ConfigType) -> ConfigType:
if CONF_CUSTOM_WAVEFORM in config and config[CONF_MODEL] != "inkplate_10":
raise cv.Invalid("Custom waveforms are only supported on the Inkplate 10")
return config
CONFIG_SCHEMA = cv.All(
display.FULL_DISPLAY_SCHEMA.extend(
{
@@ -143,7 +137,7 @@ CONFIG_SCHEMA = cv.All(
.extend(cv.polling_component_schema("5s"))
.extend(i2c.i2c_device_schema(0x48)),
cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA),
_validate_custom_waveform,
cv.only_when(CONF_CUSTOM_WAVEFORM, CONF_MODEL, "inkplate_10"),
)
+1 -7
View File
@@ -30,18 +30,12 @@ CONFIG_SCHEMA = cv.All(
}
),
cv.has_exactly_one_key(CONF_REMOTE_RECEIVER_ID, CONF_REMOTE_TRANSMITTER_ID),
cv.key_requires(CONF_RECEIVER_FREQUENCY, CONF_REMOTE_RECEIVER_ID),
)
def _final_validate(config: dict[str, Any]) -> None:
"""Validate that transmitters have a proper carrier duty cycle."""
# receiver_frequency is only meaningful for receiver configurations
if CONF_RECEIVER_FREQUENCY in config and CONF_REMOTE_RECEIVER_ID not in config:
raise cv.Invalid(
f"'{CONF_RECEIVER_FREQUENCY}' can only be used with '{CONF_REMOTE_RECEIVER_ID}', "
"not with a transmitter"
)
# Only validate duty cycle if this is an infrared (not RF) configuration with a transmitter
if config.get(CONF_FREQUENCY, 0) != 0 or CONF_REMOTE_TRANSMITTER_ID not in config:
return
@@ -4,6 +4,7 @@
#include "esphome/components/key_provider/key_provider.h"
#include "esphome/core/automation.h"
#include "esphome/core/helpers.h"
#include "esphome/core/string_ref.h"
namespace esphome::key_collector {
@@ -14,12 +15,13 @@ class KeyCollector final : public Component {
void add_provider(key_provider::KeyProvider *provider);
void set_min_length(uint16_t min_length) { this->min_length_ = min_length; };
void set_max_length(uint16_t max_length) { this->max_length_ = max_length; };
void set_start_keys(std::string start_keys) { this->start_keys_ = std::move(start_keys); };
void set_end_keys(std::string end_keys) { this->end_keys_ = std::move(end_keys); };
// The key setters keep the pointer; the strings must outlive the component (codegen passes literals)
void set_start_keys(const char *start_keys) { this->start_keys_ = StringRef(start_keys); };
void set_end_keys(const char *end_keys) { this->end_keys_ = StringRef(end_keys); };
void set_end_key_required(bool end_key_required) { this->end_key_required_ = end_key_required; };
void set_back_keys(std::string back_keys) { this->back_keys_ = std::move(back_keys); };
void set_clear_keys(std::string clear_keys) { this->clear_keys_ = std::move(clear_keys); };
void set_allowed_keys(std::string allowed_keys) { this->allowed_keys_ = std::move(allowed_keys); };
void set_back_keys(const char *back_keys) { this->back_keys_ = StringRef(back_keys); };
void set_clear_keys(const char *clear_keys) { this->clear_keys_ = StringRef(clear_keys); };
void set_allowed_keys(const char *allowed_keys) { this->allowed_keys_ = StringRef(allowed_keys); };
template<typename F> void add_on_progress_callback(F &&callback) {
this->progress_callbacks_.add(std::forward<F>(callback));
}
@@ -38,12 +40,12 @@ class KeyCollector final : public Component {
protected:
uint16_t min_length_{0};
uint16_t max_length_{0};
std::string start_keys_;
std::string end_keys_;
StringRef start_keys_;
StringRef end_keys_;
bool end_key_required_{false};
std::string back_keys_;
std::string clear_keys_;
std::string allowed_keys_;
StringRef back_keys_;
StringRef clear_keys_;
StringRef allowed_keys_;
std::string result_;
uint8_t start_key_{0};
LazyCallbackManager<void(const std::string &, uint8_t)> progress_callbacks_;
+1 -2
View File
@@ -12,8 +12,7 @@ namespace esphome::lock {
class Lock;
#define LOG_LOCK(prefix, type, obj) \
if ((obj) != nullptr) { \
ESP_LOGCONFIG(TAG, "%s%s '%s'", prefix, LOG_STR_LITERAL(type), (obj)->get_name().c_str()); \
if (log_entity_header(TAG, prefix, LOG_STR_LITERAL(type), (obj))) { \
LOG_ENTITY_ICON(TAG, prefix, *(obj)); \
if ((obj)->traits.get_assumed_state()) { \
ESP_LOGCONFIG(TAG, "%s Assumed State: YES", prefix); \
+11 -20
View File
@@ -145,25 +145,6 @@ def _preference_key(config: ConfigType) -> int:
return fnv1_hash(":".join(parts))
def _validate_adc_keys(config: ConfigType) -> ConfigType:
"""Reject the ADC keys where they would be accepted and ignored."""
if CONF_VOLTAGE_DIVIDER not in config and CONF_PIN not in config:
for key in (CONF_ADC_INPUT_MAX, CONF_ADC_PIN_MAX):
if key in config:
raise cv.Invalid(
f"'{key}:' only checks a 'pin:' source or a 'voltage_divider:', "
"so it has no effect here",
path=[key],
)
if CONF_ADC_ATTENUATION in config and CONF_PIN not in config:
raise cv.Invalid(
"'adc_attenuation:' only applies to the ADC of a 'pin:' source - set "
"'attenuation:' on the adc sensor behind 'voltage:' instead",
path=[CONF_ADC_ATTENUATION],
)
return config
def _validate_adc_range(config: ConfigType) -> ConfigType:
"""Reject wiring that puts the supply, the largest possible reading, past the sampler limits.
@@ -405,7 +386,17 @@ CONFIG_SCHEMA = cv.All(
cv.has_at_most_one_key(CONF_VOLTAGE_DIVIDER, CONF_VOLTAGE_MULTIPLIER),
cv.has_at_least_one_key(*GASES),
cv.has_at_most_one_key(CONF_AIR_REFERENCE, CONF_R0, CONF_CALIBRATION),
_validate_adc_keys,
cv.key_requires(
(CONF_ADC_INPUT_MAX, CONF_ADC_PIN_MAX),
CONF_VOLTAGE_DIVIDER,
CONF_PIN,
any_of=True,
),
cv.key_requires(
CONF_ADC_ATTENUATION,
CONF_PIN,
hint="Set 'attenuation:' on the adc sensor behind 'voltage:' instead",
),
_validate_adc_range,
_validate_config,
_validate_enable_pin,
+73 -4
View File
@@ -6,6 +6,7 @@ from esphome.components.esp32 import (
idf_version,
include_builtin_idf_component,
request_tls,
require_certificate_bundle,
)
from esphome.config_helpers import (
filter_source_files_from_defines,
@@ -61,6 +62,7 @@ from esphome.const import (
PLATFORM_ESP8266,
PLATFORM_LN882X,
PLATFORM_RTL87XX,
Framework,
PlatformFramework,
)
from esphome.core import CORE, CoroPriority, coroutine_with_priority
@@ -78,6 +80,13 @@ def AUTO_LOAD():
CONF_IDF_SEND_ASYNC = "idf_send_async"
CONF_WAIT_FOR_CONNECTION = "wait_for_connection"
CONF_TRANSPORT = "transport"
CONF_WS_PATH = "ws_path"
MQTT_TRANSPORT_TCP = "tcp"
MQTT_TRANSPORT_WS = "ws"
MQTT_TRANSPORT_WSS = "wss"
DEFAULT_WS_PATH = "/mqtt"
# Max lengths for stack-based topic building.
# These values are used in cv.Length() validators below to ensure the C++ code
@@ -155,8 +164,54 @@ MQTT_DISCOVERY_OBJECT_ID_GENERATOR_OPTIONS = {
"device_name": MQTTDiscoveryObjectIdGenerator.MQTT_DEVICE_NAME_OBJECT_ID_GENERATOR,
}
# Only ESP-IDF's esp-mqtt implements MQTT over WebSocket
MQTTTransport = mqtt_ns.enum("MQTTTransport", is_class=True)
MQTT_TRANSPORT_OPTIONS = {
MQTT_TRANSPORT_TCP: MQTTTransport.MQTT_TRANSPORT_TCP,
MQTT_TRANSPORT_WS: MQTTTransport.MQTT_TRANSPORT_WS,
MQTT_TRANSPORT_WSS: MQTTTransport.MQTT_TRANSPORT_WSS,
}
def _validate_transport(value: str) -> str:
value = cv.enum(MQTT_TRANSPORT_OPTIONS, lower=True)(value)
if value in (MQTT_TRANSPORT_WS, MQTT_TRANSPORT_WSS):
if not CORE.is_esp32:
raise cv.Invalid(
f"transport '{value}' is currently only supported on ESP32"
)
if CORE.target_framework != Framework.ESP_IDF:
raise cv.Invalid(f"transport '{value}' requires the esp-idf framework")
return value
def validate_config(value):
transport = value.get(CONF_TRANSPORT)
# A certificate with plain ws is almost certainly a typo for wss
if transport == MQTT_TRANSPORT_WS and (
CONF_CERTIFICATE_AUTHORITY in value or CONF_CLIENT_CERTIFICATE in value
):
raise cv.Invalid(
"transport 'ws' is unencrypted; remove the certificate options "
"or switch to transport 'wss'"
)
# TLS runs only with a CA or over wss, so a client certificate needs one of them
if (
CONF_CLIENT_CERTIFICATE in value
and CONF_CERTIFICATE_AUTHORITY not in value
and transport != MQTT_TRANSPORT_WSS
):
raise cv.Invalid(
"'client_certificate' requires 'certificate_authority' or transport 'wss'"
)
if (
transport not in (MQTT_TRANSPORT_WS, MQTT_TRANSPORT_WSS)
and CONF_WS_PATH in value
):
raise cv.Invalid(
f"'{CONF_WS_PATH}' is only valid when 'transport' is 'ws' or 'wss'"
)
# Populate default fields
out = value.copy()
topic_prefix = value[CONF_TOPIC_PREFIX]
@@ -232,6 +287,10 @@ CONFIG_SCHEMA = cv.All(
cv.Optional(CONF_PASSWORD, default=""): cv.sensitive(),
cv.Optional(CONF_CLEAN_SESSION, default=False): cv.boolean,
cv.Optional(CONF_CLIENT_ID): cv.string,
cv.Optional(
CONF_TRANSPORT, default=MQTT_TRANSPORT_TCP
): _validate_transport,
cv.Optional(CONF_WS_PATH): cv.string,
cv.SplitDefault(CONF_IDF_SEND_ASYNC, esp32=False): cv.All(
cv.boolean, cv.only_on_esp32
),
@@ -435,13 +494,23 @@ async def to_code(config):
cg.add(var.set_reboot_timeout(config[CONF_REBOOT_TIMEOUT]))
# esp-idf only
if CONF_CERTIFICATE_AUTHORITY in config:
cg.add(var.set_ca_certificate(config[CONF_CERTIFICATE_AUTHORITY]))
transport = config.get(CONF_TRANSPORT)
ca = cg.add_optional(var.set_ca_certificate, config.get(CONF_CERTIFICATE_AUTHORITY))
if ca is not None or transport == MQTT_TRANSPORT_WSS:
cg.add(var.set_skip_cert_cn_check(config[CONF_SKIP_CERT_CN_CHECK]))
if CONF_CLIENT_CERTIFICATE in config:
cg.add(var.set_cl_certificate(config[CONF_CLIENT_CERTIFICATE]))
if (client_certificate := config.get(CONF_CLIENT_CERTIFICATE)) is not None:
cg.add(var.set_cl_certificate(client_certificate))
cg.add(var.set_cl_key(config[CONF_CLIENT_CERTIFICATE_KEY]))
if CORE.is_esp32:
if transport != MQTT_TRANSPORT_TCP:
cg.add(var.set_transport(transport))
if transport in (MQTT_TRANSPORT_WS, MQTT_TRANSPORT_WSS):
cg.add(var.set_ws_path(config.get(CONF_WS_PATH, DEFAULT_WS_PATH)))
# wss without an explicit CA verifies the broker against the bundled roots
if transport == MQTT_TRANSPORT_WSS and ca is None:
require_certificate_bundle()
if CONF_IDF_SEND_ASYNC in config and config[CONF_IDF_SEND_ASYNC]:
cg.add_define("USE_MQTT_IDF_ENQUEUE")
# end esp-idf
@@ -77,7 +77,6 @@ void MQTTAlarmControlPanelComponent::setup() {
}
void MQTTAlarmControlPanelComponent::dump_config() {
ESP_LOGCONFIG(TAG, "MQTT alarm_control_panel '%s':", this->alarm_control_panel_->get_name().c_str());
LOG_MQTT_COMPONENT(true, true);
ESP_LOGCONFIG(TAG,
" Supported Features: %" PRIu32 "\n"
+7
View File
@@ -20,6 +20,13 @@ enum class MQTTClientDisconnectReason : int8_t {
DNS_RESOLVE_ERROR = 8
};
/// Transport for the broker connection; only the ESP-IDF backend supports WebSocket.
enum class MQTTTransport : uint8_t {
MQTT_TRANSPORT_TCP = 0,
MQTT_TRANSPORT_WS = 1,
MQTT_TRANSPORT_WSS = 2,
};
/// internal struct for MQTT messages.
struct MQTTMessage {
std::string topic;
+38 -7
View File
@@ -8,6 +8,10 @@
#include "esphome/core/log.h"
#include "esphome/core/application.h"
#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
#include "esp_crt_bundle.h"
#endif
namespace esphome::mqtt {
ESPHOME_LOG_TAG(TAG, "mqtt");
@@ -39,17 +43,44 @@ bool MQTTBackendESP32::initialize_() {
if (!this->client_id_.empty()) {
mqtt_cfg_.credentials.client_id = this->client_id_.c_str();
}
if (ca_certificate_.has_value()) {
mqtt_cfg_.broker.verification.certificate = ca_certificate_.value().c_str();
mqtt_cfg_.broker.verification.skip_cert_common_name_check = skip_cert_cn_check_;
mqtt_cfg_.broker.address.transport = MQTT_TRANSPORT_OVER_SSL;
// Plain TCP keeps upgrading to SSL when a CA certificate is configured
bool uses_tls = false;
switch (this->transport_) {
case MQTTTransport::MQTT_TRANSPORT_WS:
mqtt_cfg_.broker.address.transport = MQTT_TRANSPORT_OVER_WS;
break;
case MQTTTransport::MQTT_TRANSPORT_WSS:
mqtt_cfg_.broker.address.transport = MQTT_TRANSPORT_OVER_WSS;
uses_tls = true;
break;
case MQTTTransport::MQTT_TRANSPORT_TCP:
default:
if (this->ca_certificate_.has_value()) {
mqtt_cfg_.broker.address.transport = MQTT_TRANSPORT_OVER_SSL;
uses_tls = true;
} else {
mqtt_cfg_.broker.address.transport = MQTT_TRANSPORT_OVER_TCP;
}
break;
}
// Only set for the WebSocket transports
mqtt_cfg_.broker.address.path = this->ws_path_;
if (uses_tls) {
if (this->ca_certificate_.has_value()) {
mqtt_cfg_.broker.verification.certificate = this->ca_certificate_.value().c_str();
#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
} else {
// wss without a CA verifies the broker against the bundled roots, as http_request does
mqtt_cfg_.broker.verification.crt_bundle_attach = esp_crt_bundle_attach;
#endif
}
mqtt_cfg_.broker.verification.skip_cert_common_name_check = this->skip_cert_cn_check_;
if (this->cl_certificate_.has_value() && this->cl_key_.has_value()) {
mqtt_cfg_.credentials.authentication.certificate = this->cl_certificate_.value().c_str();
mqtt_cfg_.credentials.authentication.key = this->cl_key_.value().c_str();
}
} else {
mqtt_cfg_.broker.address.transport = MQTT_TRANSPORT_OVER_TCP;
}
auto *mqtt_client = esp_mqtt_client_init(&mqtt_cfg_);
@@ -60,7 +91,7 @@ bool MQTTBackendESP32::initialize_() {
#if defined(USE_MQTT_IDF_ENQUEUE)
// Create the task only after MQTT client is initialized successfully
// Use larger stack size when TLS is enabled
size_t stack_size = this->ca_certificate_.has_value() ? TASK_STACK_SIZE_TLS : TASK_STACK_SIZE;
size_t stack_size = uses_tls ? TASK_STACK_SIZE_TLS : TASK_STACK_SIZE;
xTaskCreate(esphome_mqtt_task, "esphome_mqtt", stack_size, (void *) this, TASK_PRIORITY, &this->task_handle_);
if (this->task_handle_ == nullptr) {
ESP_LOGE(TAG, "Failed to create MQTT task");
@@ -218,6 +218,10 @@ class MQTTBackendESP32 final : public MQTTBackend {
void set_cl_certificate(const std::string &cert) { cl_certificate_ = cert; }
void set_cl_key(const std::string &key) { cl_key_ = key; }
void set_skip_cert_cn_check(bool skip_check) { skip_cert_cn_check_ = skip_check; }
void set_transport(MQTTTransport transport) { this->transport_ = transport; }
void set_ws_path(const char *path) { this->ws_path_ = path; }
MQTTTransport get_transport() const { return this->transport_; }
const char *get_ws_path() const { return this->ws_path_; }
// No destructor needed: ESPHome components live for the entire device runtime.
// The MQTT task and queue will run until the device reboots or loses power,
@@ -256,6 +260,8 @@ class MQTTBackendESP32 final : public MQTTBackend {
optional<std::string> cl_certificate_;
optional<std::string> cl_key_;
bool skip_cert_cn_check_{false};
MQTTTransport transport_{MQTTTransport::MQTT_TRANSPORT_TCP};
const char *ws_path_{nullptr};
#if defined(USE_MQTT_IDF_ENQUEUE)
static void esphome_mqtt_task(void *params);
// Pool sized to queue capacity (SIZE-1) — see mqtt_event_pool_ comment.
@@ -17,10 +17,7 @@ void MQTTBinarySensorComponent::setup() {
this->binary_sensor_->add_on_state_callback([this](bool state) { this->publish_state(state); });
}
void MQTTBinarySensorComponent::dump_config() {
ESP_LOGCONFIG(TAG, "MQTT Binary Sensor '%s':", this->binary_sensor_->get_name().c_str());
LOG_MQTT_COMPONENT(true, false);
}
void MQTTBinarySensorComponent::dump_config() { LOG_MQTT_COMPONENT(true, false); }
MQTTBinarySensorComponent::MQTTBinarySensorComponent(binary_sensor::BinarySensor *binary_sensor)
: binary_sensor_(binary_sensor) {
if (this->binary_sensor_->is_status_binary_sensor()) {
+1 -4
View File
@@ -24,10 +24,7 @@ void MQTTButtonComponent::setup() {
}
});
}
void MQTTButtonComponent::dump_config() {
ESP_LOGCONFIG(TAG, "MQTT Button '%s': ", this->button_->get_name().c_str());
LOG_MQTT_COMPONENT(false, true);
}
void MQTTButtonComponent::dump_config() { LOG_MQTT_COMPONENT(false, true); }
void MQTTButtonComponent::send_discovery(JsonObject root, mqtt::SendDiscoveryConfig &config) {
config.state_topic = false;
+10
View File
@@ -213,6 +213,16 @@ void MQTTClientComponent::dump_config() {
this->credentials_.username.c_str(), this->credentials_.client_id.c_str(),
YESNO(this->credentials_.clean_session));
// clang-format on
#ifdef USE_ESP32
if (const MQTTTransport transport = this->mqtt_backend_.get_transport();
transport != MQTTTransport::MQTT_TRANSPORT_TCP) {
ESP_LOGCONFIG(TAG,
" Transport: %s\n"
" WebSocket Path: '%s'",
transport == MQTTTransport::MQTT_TRANSPORT_WSS ? LOG_STR_LITERAL("wss") : LOG_STR_LITERAL("ws"),
this->mqtt_backend_.get_ws_path());
}
#endif
if (this->is_discovery_ip_enabled()) {
ESP_LOGCONFIG(TAG, " Discovery IP enabled");
}
+2
View File
@@ -152,6 +152,8 @@ class MQTTClientComponent final : public Component {
void set_cl_certificate(const char *cert) { this->mqtt_backend_.set_cl_certificate(cert); }
void set_cl_key(const char *key) { this->mqtt_backend_.set_cl_key(key); }
void set_skip_cert_cn_check(bool skip_check) { this->mqtt_backend_.set_skip_cert_cn_check(skip_check); }
void set_transport(MQTTTransport transport) { this->mqtt_backend_.set_transport(transport); }
void set_ws_path(const char *path) { this->mqtt_backend_.set_ws_path(path); }
#endif
const Availability &get_availability();
@@ -38,6 +38,7 @@ inline char *append_char(char *p, char c) {
// Function implementation of LOG_MQTT_COMPONENT macro to reduce code size
void log_mqtt_component(const char *tag, MQTTComponent *obj, bool state_topic, bool command_topic) {
ESP_LOGCONFIG(tag, "MQTT %s '%s':", obj->component_type(), obj->friendly_name_().c_str());
char buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
if (state_topic) {
ESP_LOGCONFIG(tag, " State Topic: '%s'", obj->get_state_topic_to_(buf).c_str());
-1
View File
@@ -63,7 +63,6 @@ void MQTTCoverComponent::setup() {
}
void MQTTCoverComponent::dump_config() {
ESP_LOGCONFIG(TAG, "MQTT cover '%s':", this->cover_->get_name().c_str());
auto traits = this->cover_->get_traits();
bool has_command_topic = traits.get_supports_position() || !traits.get_supports_tilt();
LOG_MQTT_COMPONENT(true, has_command_topic);
+1 -4
View File
@@ -34,10 +34,7 @@ void MQTTDateComponent::setup() {
[this]() { this->publish_state(this->date_->year, this->date_->month, this->date_->day); });
}
void MQTTDateComponent::dump_config() {
ESP_LOGCONFIG(TAG, "MQTT Date '%s':", this->date_->get_name().c_str());
LOG_MQTT_COMPONENT(true, true);
}
void MQTTDateComponent::dump_config() { LOG_MQTT_COMPONENT(true, true); }
MQTT_COMPONENT_TYPE(MQTTDateComponent, "date")
const EntityBase *MQTTDateComponent::get_entity() const { return this->date_; }

Some files were not shown because too many files have changed in this diff Show More